Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Makefile
Original file line numberDiff line numberDiff line change
Expand Up@@ -177,7 +177,7 @@ CWARNFLAGS := -Werror -Wall -Wundef -Wmissing-prototypes -Wmissing-declarations
CDEBUGFLAGS := -g -fstack-protector
CFLAGS := $(CWARNFLAGS) $(CDEBUGFLAGS) -I $(CCANDIR) -I secp256k1/include/ -I . $(FEATURES)

LDLIBS := -lcrypto -lprotobuf-c -lgmp -lsodium
LDLIBS := -lprotobuf-c -lgmp -lsodium -lbase58
$(PROGRAMS): CFLAGS+=-I.

default: $(PROGRAMS) daemon-all
Expand Down
270 changes: 35 additions & 235 deletions bitcoin/base58.c
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,149 +11,28 @@
#include <assert.h>
#include <ccan/build_assert/build_assert.h>
#include <ccan/tal/str/str.h>
#include <openssl/bn.h>
#include <secp256k1.h>
#include <string.h>
#include <libbase58.h>

static const char enc_16[] = "0123456789abcdef";
static const char enc_58[] =
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

static char encode_char(unsigned long val, const char *enc)
{
assert(val < strlen(enc));
return enc[val];
}

static int decode_char(char c, const char *enc)
{
const char *pos = strchr(enc, c);
if (!pos)
return -1;
return pos - enc;
}

/*
* Encode a byte sequence as a base58-encoded string. This is a bit
* weird: returns pointer into buf (or NULL if wouldn't fit).
*/
static char *encode_base58(char *buf, size_t buflen,
const u8 *data, size_t data_len)
{
char *p;
BIGNUM bn;

/* Convert to a bignum. */
BN_init(&bn);
BN_bin2bn(data, data_len, &bn);

/* Add NUL terminator */
if (!buflen) {
p = NULL;
goto out;
}
p = buf + buflen;
*(--p) = '\0';

/* Fill from the back, using a series of divides. */
while (!BN_is_zero(&bn)) {
int rem = BN_div_word(&bn, 58);
if (--p < buf) {
p = NULL;
goto out;
}
*p = encode_char(rem, enc_58);
}

/* Now, this is really weird. We pad with zeroes, but not at
* base 58, but in terms of zero bytes. This means that some
* encodings are shorter than others! */
while (data_len && *data == '\0') {
if (--p < buf) {
p = NULL;
goto out;
}
*p = encode_char(0, enc_58);
data_len--;
data++;
}

out:
BN_free(&bn);
return p;
}

/*
* Decode a base_n-encoded string into a byte sequence.
*/
bool raw_decode_base_n(BIGNUM *bn, const char *src, size_t len, int base)
static bool my_sha256(void *digest, const void *data, size_t datasz)
{
const char *enc;

BN_zero(bn);

assert(base == 16 || base == 58);
switch (base) {
case 16:
enc = enc_16;
break;
case 58:
enc = enc_58;
break;
}

while (len) {
char current = *src;

if (base == 16)
current = tolower(current); /* TODO: Not in ccan. */
int val = decode_char(current, enc);
if (val < 0) {
BN_free(bn);
return false;
}
BN_mul_word(bn, base);
BN_add_word(bn, val);
src++;
len--;
}

sha256(digest, data, datasz);
return true;
}

/*
* Decode a base58-encoded string into a byte sequence.
*/
bool raw_decode_base58(BIGNUM *bn, const char *src, size_t len)
{
return raw_decode_base_n(bn, src, len, 58);
}

void base58_get_checksum(u8 csum[4], const u8 buf[], size_t buflen)
{
struct sha256_double sha_result;

/* Form checksum, using double SHA2 (as per bitcoin standard) */
sha256_double(&sha_result, buf, buflen);

/* Use first four bytes of that as the checksum. */
memcpy(csum, sha_result.sha.u.u8, 4);
}

static char *to_base58(const tal_t *ctx, u8 version,
const struct ripemd160 *rmd)
{
u8 buf[1 + sizeof(*rmd) + 4];
char out[BASE58_ADDR_MAX_LEN + 2], *p;

buf[0] = version;
memcpy(buf+1, rmd, sizeof(*rmd));

/* Append checksum */
base58_get_checksum(buf + 1 + sizeof(*rmd), buf, 1 + sizeof(*rmd));
char out[BASE58_ADDR_MAX_LEN + 1];
size_t outlen = sizeof(out);

p = encode_base58(out, BASE58_ADDR_MAX_LEN, buf, sizeof(buf));
return tal_strdup(ctx, p);
b58_sha256_impl = my_sha256;
if (!b58check_enc(out, &outlen, version, rmd, sizeof(*rmd))) {
return NULL;
}else{
return tal_strdup(ctx, out);
}
}

char *bitcoin_to_base58(const tal_t *ctx, bool test_net,
Expand All@@ -173,30 +52,15 @@ static bool from_base58(u8 *version,
const char *base58, size_t base58_len)
{
u8 buf[1 + sizeof(*rmd) + 4];
BIGNUM bn;
size_t len;
u8 csum[4];

BN_init(&bn);
if (!raw_decode_base58(&bn, base58, base58_len))
return false;

len = BN_num_bytes(&bn);
if (len > sizeof(buf))
return false;

memset(buf, 0, sizeof(buf));
BN_bn2bin(&bn, buf + sizeof(buf) - len);
BN_free(&bn);
b58_sha256_impl = my_sha256;

size_t buflen = sizeof(buf);
b58tobin(buf, &buflen, base58, base58_len);
int r = b58check(buf, sizeof(buf), base58, base58_len);
*version = buf[0];

base58_get_checksum(csum, buf, 1 + sizeof(*rmd));
if (memcmp(csum, buf + 1 + sizeof(*rmd), sizeof(csum)) != 0)
return false;

memcpy(rmd, buf+1, sizeof(*rmd));
return true;
memcpy(rmd, buf + 1, sizeof(*rmd));
return r > 0;
}

bool bitcoin_from_base58(bool *test_net,
Expand DownExpand Up@@ -235,124 +99,60 @@ bool p2sh_from_base58(bool *test_net,
return true;
}

/* buf already contains version and ripemd160. Append checksum and encode */
char *base58_with_check(char dest[BASE58_ADDR_MAX_LEN],
u8 buf[1 + sizeof(struct ripemd160) + 4])
{
/* Append checksum */
base58_get_checksum(buf + 1 + sizeof(struct ripemd160),
buf, 1 + sizeof(struct ripemd160));

/* Now encode. */
return encode_base58(dest, BASE58_ADDR_MAX_LEN, buf,
1 + sizeof(struct ripemd160) + 4);
}

bool ripemd_from_base58(u8 *version,
struct ripemd160 *ripemd160,
const char *base58)
{
u8 buf[1 + sizeof(*ripemd160) + 4];
u8 csum[4];
BIGNUM bn;
size_t len;

/* Too long? Check here before doing arithmetic. */
if (strlen(base58) > BASE58_ADDR_MAX_LEN - 1)
return false;

BN_init(&bn);
/* Fails if it contains invalid characters. */
if (!raw_decode_base58(&bn, base58, strlen(base58)))
return false;

/* Too big? */
len = BN_num_bytes(&bn);
if (len > sizeof(buf)) {
BN_free(&bn);
return false;
}

/* Fill start with zeroes. */
memset(buf, 0, sizeof(buf) - len);
BN_bn2bin(&bn, buf + sizeof(buf) - len);
BN_free(&bn);

/* Check checksum is correct. */
base58_get_checksum(csum, buf, sizeof(buf));
if (memcmp(csum, buf + 1 + sizeof(*ripemd160), 4) != 0)
return false;

*version = buf[0];
memcpy(ripemd160, buf + 1, sizeof(*ripemd160));
return true;
return from_base58(version, ripemd160, base58, strlen(base58));
}

char *key_to_base58(const tal_t *ctx, bool test_net, const struct privkey *key)
{
u8 buf[1 + 32 + 1 + 4];
char out[BASE58_KEY_MAX_LEN + 2], *p;

buf[0] = test_net ? 239 : 128;
memcpy(buf + 1, key->secret, sizeof(key->secret));
u8 buf[32 + 1];
char out[BASE58_KEY_MAX_LEN + 2];
u8 version = test_net ? 239 : 128;
size_t outlen = sizeof(out);

memcpy(buf, key->secret, sizeof(key->secret));
/* Mark this as a compressed key. */
buf[1 + 32] = 1;
buf[32] = 1;

/* Append checksum */
base58_get_checksum(buf + 1 + 32 + 1, buf, 1 + 32 + 1);

p = encode_base58(out, BASE58_KEY_MAX_LEN, buf, sizeof(buf));
return tal_strdup(ctx, p);
b58check_enc(out, &outlen, version, buf, sizeof(buf));
return tal_strdup(ctx, out);
}

bool key_from_base58(secp256k1_context *secpctx,
const char *base58, size_t base58_len,
bool *test_net, struct privkey *priv, struct pubkey *key)
{
// 1 byte version, 32 byte private key, 1 byte compressed, 4 byte checksum
u8 keybuf[1 + 32 + 1 + 4];
u8 csum[4];
BIGNUM bn;
size_t keylen;

BN_init(&bn);
if (!raw_decode_base58(&bn, base58, base58_len))
return false;

keylen = BN_num_bytes(&bn);
if (keylen != 1 + 32 + 1 + 4)
goto fail_free_bn;
BN_bn2bin(&bn, keybuf);
size_t keybuflen = sizeof(keybuf);

base58_get_checksum(csum, keybuf, keylen - sizeof(csum));
if (memcmp(csum, keybuf + keylen - sizeof(csum), sizeof(csum)) != 0)
goto fail_free_bn;
b58tobin(keybuf, &keybuflen, base58, base58_len);
if (b58check(keybuf, sizeof(keybuf), base58, base58_len) < 0)
return false;

/* Byte after key should be 1 to represent a compressed key. */
if (keybuf[1 + 32] != 1)
goto fail_free_bn;
return false;

if (keybuf[0] == 128)
*test_net = false;
else if (keybuf[0] == 239)
*test_net = true;
else
goto fail_free_bn;
return false;

/* Copy out secret. */
memcpy(priv->secret, keybuf + 1, sizeof(priv->secret));

if (!secp256k1_ec_seckey_verify(secpctx, priv->secret))
goto fail_free_bn;
return false;

/* Get public key, too. */
if (!pubkey_from_privkey(secpctx, priv, key))
goto fail_free_bn;
return false;

BN_free(&bn);
return true;

fail_free_bn:
BN_free(&bn);
return false;
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Makefile
Original file line numberDiff line numberDiff line change
Expand Up@@ -177,7 +177,7 @@ CWARNFLAGS := -Werror -Wall -Wundef -Wmissing-prototypes -Wmissing-declarations
CDEBUGFLAGS := -g -fstack-protector
CFLAGS := $(CWARNFLAGS) $(CDEBUGFLAGS) -I $(CCANDIR) -I secp256k1/include/ -I . $(FEATURES)

LDLIBS := -lcrypto -lprotobuf-c -lgmp -lsodium
LDLIBS := -lprotobuf-c -lgmp -lsodium -lbase58
$(PROGRAMS): CFLAGS+=-I.

default: $(PROGRAMS) daemon-all
Expand Down
270 changes: 35 additions & 235 deletions bitcoin/base58.c
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,149 +11,28 @@
#include <assert.h>
#include <ccan/build_assert/build_assert.h>
#include <ccan/tal/str/str.h>
#include <openssl/bn.h>
#include <secp256k1.h>
#include <string.h>
#include <libbase58.h>

static const char enc_16[] = "0123456789abcdef";
static const char enc_58[] =
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

static char encode_char(unsigned long val, const char *enc)
{
assert(val < strlen(enc));
return enc[val];
}

static int decode_char(char c, const char *enc)
{
const char *pos = strchr(enc, c);
if (!pos)
return -1;
return pos - enc;
}

/*
* Encode a byte sequence as a base58-encoded string. This is a bit
* weird: returns pointer into buf (or NULL if wouldn't fit).
*/
static char *encode_base58(char *buf, size_t buflen,
const u8 *data, size_t data_len)
{
char *p;
BIGNUM bn;

/* Convert to a bignum. */
BN_init(&bn);
BN_bin2bn(data, data_len, &bn);

/* Add NUL terminator */
if (!buflen) {
p = NULL;
goto out;
}
p = buf + buflen;
*(--p) = '\0';

/* Fill from the back, using a series of divides. */
while (!BN_is_zero(&bn)) {
int rem = BN_div_word(&bn, 58);
if (--p < buf) {
p = NULL;
goto out;
}
*p = encode_char(rem, enc_58);
}

/* Now, this is really weird. We pad with zeroes, but not at
* base 58, but in terms of zero bytes. This means that some
* encodings are shorter than others! */
while (data_len && *data == '\0') {
if (--p < buf) {
p = NULL;
goto out;
}
*p = encode_char(0, enc_58);
data_len--;
data++;
}

out:
BN_free(&bn);
return p;
}

/*
* Decode a base_n-encoded string into a byte sequence.
*/
bool raw_decode_base_n(BIGNUM *bn, const char *src, size_t len, int base)
static bool my_sha256(void *digest, const void *data, size_t datasz)
{
const char *enc;

BN_zero(bn);

assert(base == 16 || base == 58);
switch (base) {
case 16:
enc = enc_16;
break;
case 58:
enc = enc_58;
break;
}

while (len) {
char current = *src;

if (base == 16)
current = tolower(current); /* TODO: Not in ccan. */
int val = decode_char(current, enc);
if (val < 0) {
BN_free(bn);
return false;
}
BN_mul_word(bn, base);
BN_add_word(bn, val);
src++;
len--;
}

sha256(digest, data, datasz);
return true;
}

/*
* Decode a base58-encoded string into a byte sequence.
*/
bool raw_decode_base58(BIGNUM *bn, const char *src, size_t len)
{
return raw_decode_base_n(bn, src, len, 58);
}

void base58_get_checksum(u8 csum[4], const u8 buf[], size_t buflen)
{
struct sha256_double sha_result;

/* Form checksum, using double SHA2 (as per bitcoin standard) */
sha256_double(&sha_result, buf, buflen);

/* Use first four bytes of that as the checksum. */
memcpy(csum, sha_result.sha.u.u8, 4);
}

static char *to_base58(const tal_t *ctx, u8 version,
const struct ripemd160 *rmd)
{
u8 buf[1 + sizeof(*rmd) + 4];
char out[BASE58_ADDR_MAX_LEN + 2], *p;

buf[0] = version;
memcpy(buf+1, rmd, sizeof(*rmd));

/* Append checksum */
base58_get_checksum(buf + 1 + sizeof(*rmd), buf, 1 + sizeof(*rmd));
char out[BASE58_ADDR_MAX_LEN + 1];
size_t outlen = sizeof(out);

p = encode_base58(out, BASE58_ADDR_MAX_LEN, buf, sizeof(buf));
return tal_strdup(ctx, p);
b58_sha256_impl = my_sha256;
if (!b58check_enc(out, &outlen, version, rmd, sizeof(*rmd))) {
return NULL;
}else{
return tal_strdup(ctx, out);
}
}

char *bitcoin_to_base58(const tal_t *ctx, bool test_net,
Expand All@@ -173,30 +52,15 @@ static bool from_base58(u8 *version,
const char *base58, size_t base58_len)
{
u8 buf[1 + sizeof(*rmd) + 4];
BIGNUM bn;
size_t len;
u8 csum[4];

BN_init(&bn);
if (!raw_decode_base58(&bn, base58, base58_len))
return false;

len = BN_num_bytes(&bn);
if (len > sizeof(buf))
return false;

memset(buf, 0, sizeof(buf));
BN_bn2bin(&bn, buf + sizeof(buf) - len);
BN_free(&bn);
b58_sha256_impl = my_sha256;

size_t buflen = sizeof(buf);
b58tobin(buf, &buflen, base58, base58_len);
int r = b58check(buf, sizeof(buf), base58, base58_len);
*version = buf[0];

base58_get_checksum(csum, buf, 1 + sizeof(*rmd));
if (memcmp(csum, buf + 1 + sizeof(*rmd), sizeof(csum)) != 0)
return false;

memcpy(rmd, buf+1, sizeof(*rmd));
return true;
memcpy(rmd, buf + 1, sizeof(*rmd));
return r > 0;
}

bool bitcoin_from_base58(bool *test_net,
Expand DownExpand Up@@ -235,124 +99,60 @@ bool p2sh_from_base58(bool *test_net,
return true;
}

/* buf already contains version and ripemd160. Append checksum and encode */
char *base58_with_check(char dest[BASE58_ADDR_MAX_LEN],
u8 buf[1 + sizeof(struct ripemd160) + 4])
{
/* Append checksum */
base58_get_checksum(buf + 1 + sizeof(struct ripemd160),
buf, 1 + sizeof(struct ripemd160));

/* Now encode. */
return encode_base58(dest, BASE58_ADDR_MAX_LEN, buf,
1 + sizeof(struct ripemd160) + 4);
}

bool ripemd_from_base58(u8 *version,
struct ripemd160 *ripemd160,
const char *base58)
{
u8 buf[1 + sizeof(*ripemd160) + 4];
u8 csum[4];
BIGNUM bn;
size_t len;

/* Too long? Check here before doing arithmetic. */
if (strlen(base58) > BASE58_ADDR_MAX_LEN - 1)
return false;

BN_init(&bn);
/* Fails if it contains invalid characters. */
if (!raw_decode_base58(&bn, base58, strlen(base58)))
return false;

/* Too big? */
len = BN_num_bytes(&bn);
if (len > sizeof(buf)) {
BN_free(&bn);
return false;
}

/* Fill start with zeroes. */
memset(buf, 0, sizeof(buf) - len);
BN_bn2bin(&bn, buf + sizeof(buf) - len);
BN_free(&bn);

/* Check checksum is correct. */
base58_get_checksum(csum, buf, sizeof(buf));
if (memcmp(csum, buf + 1 + sizeof(*ripemd160), 4) != 0)
return false;

*version = buf[0];
memcpy(ripemd160, buf + 1, sizeof(*ripemd160));
return true;
return from_base58(version, ripemd160, base58, strlen(base58));
}

char *key_to_base58(const tal_t *ctx, bool test_net, const struct privkey *key)
{
u8 buf[1 + 32 + 1 + 4];
char out[BASE58_KEY_MAX_LEN + 2], *p;

buf[0] = test_net ? 239 : 128;
memcpy(buf + 1, key->secret, sizeof(key->secret));
u8 buf[32 + 1];
char out[BASE58_KEY_MAX_LEN + 2];
u8 version = test_net ? 239 : 128;
size_t outlen = sizeof(out);

memcpy(buf, key->secret, sizeof(key->secret));
/* Mark this as a compressed key. */
buf[1 + 32] = 1;
buf[32] = 1;

/* Append checksum */
base58_get_checksum(buf + 1 + 32 + 1, buf, 1 + 32 + 1);

p = encode_base58(out, BASE58_KEY_MAX_LEN, buf, sizeof(buf));
return tal_strdup(ctx, p);
b58check_enc(out, &outlen, version, buf, sizeof(buf));
return tal_strdup(ctx, out);
}

bool key_from_base58(secp256k1_context *secpctx,
const char *base58, size_t base58_len,
bool *test_net, struct privkey *priv, struct pubkey *key)
{
// 1 byte version, 32 byte private key, 1 byte compressed, 4 byte checksum
u8 keybuf[1 + 32 + 1 + 4];
u8 csum[4];
BIGNUM bn;
size_t keylen;

BN_init(&bn);
if (!raw_decode_base58(&bn, base58, base58_len))
return false;

keylen = BN_num_bytes(&bn);
if (keylen != 1 + 32 + 1 + 4)
goto fail_free_bn;
BN_bn2bin(&bn, keybuf);
size_t keybuflen = sizeof(keybuf);

base58_get_checksum(csum, keybuf, keylen - sizeof(csum));
if (memcmp(csum, keybuf + keylen - sizeof(csum), sizeof(csum)) != 0)
goto fail_free_bn;
b58tobin(keybuf, &keybuflen, base58, base58_len);
if (b58check(keybuf, sizeof(keybuf), base58, base58_len) < 0)
return false;

/* Byte after key should be 1 to represent a compressed key. */
if (keybuf[1 + 32] != 1)
goto fail_free_bn;
return false;

if (keybuf[0] == 128)
*test_net = false;
else if (keybuf[0] == 239)
*test_net = true;
else
goto fail_free_bn;
return false;

/* Copy out secret. */
memcpy(priv->secret, keybuf + 1, sizeof(priv->secret));

if (!secp256k1_ec_seckey_verify(secpctx, priv->secret))
goto fail_free_bn;
return false;

/* Get public key, too. */
if (!pubkey_from_privkey(secpctx, priv, key))
goto fail_free_bn;
return false;

BN_free(&bn);
return true;

fail_free_bn:
BN_free(&bn);
return false;
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Makefile
Original file line numberDiff line numberDiff line change
Expand Up@@ -177,7 +177,7 @@ CWARNFLAGS := -Werror -Wall -Wundef -Wmissing-prototypes -Wmissing-declarations
CDEBUGFLAGS := -g -fstack-protector
CFLAGS := $(CWARNFLAGS) $(CDEBUGFLAGS) -I $(CCANDIR) -I secp256k1/include/ -I . $(FEATURES)

LDLIBS := -lcrypto -lprotobuf-c -lgmp -lsodium
LDLIBS := -lprotobuf-c -lgmp -lsodium -lbase58
$(PROGRAMS): CFLAGS+=-I.

default: $(PROGRAMS) daemon-all
Expand Down
270 changes: 35 additions & 235 deletions bitcoin/base58.c
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,149 +11,28 @@
#include <assert.h>
#include <ccan/build_assert/build_assert.h>
#include <ccan/tal/str/str.h>
#include <openssl/bn.h>
#include <secp256k1.h>
#include <string.h>
#include <libbase58.h>

static const char enc_16[] = "0123456789abcdef";
static const char enc_58[] =
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

static char encode_char(unsigned long val, const char *enc)
{
assert(val < strlen(enc));
return enc[val];
}

static int decode_char(char c, const char *enc)
{
const char *pos = strchr(enc, c);
if (!pos)
return -1;
return pos - enc;
}

/*
* Encode a byte sequence as a base58-encoded string. This is a bit
* weird: returns pointer into buf (or NULL if wouldn't fit).
*/
static char *encode_base58(char *buf, size_t buflen,
const u8 *data, size_t data_len)
{
char *p;
BIGNUM bn;

/* Convert to a bignum. */
BN_init(&bn);
BN_bin2bn(data, data_len, &bn);

/* Add NUL terminator */
if (!buflen) {
p = NULL;
goto out;
}
p = buf + buflen;
*(--p) = '\0';

/* Fill from the back, using a series of divides. */
while (!BN_is_zero(&bn)) {
int rem = BN_div_word(&bn, 58);
if (--p < buf) {
p = NULL;
goto out;
}
*p = encode_char(rem, enc_58);
}

/* Now, this is really weird. We pad with zeroes, but not at
* base 58, but in terms of zero bytes. This means that some
* encodings are shorter than others! */
while (data_len && *data == '\0') {
if (--p < buf) {
p = NULL;
goto out;
}
*p = encode_char(0, enc_58);
data_len--;
data++;
}

out:
BN_free(&bn);
return p;
}

/*
* Decode a base_n-encoded string into a byte sequence.
*/
bool raw_decode_base_n(BIGNUM *bn, const char *src, size_t len, int base)
static bool my_sha256(void *digest, const void *data, size_t datasz)
{
const char *enc;

BN_zero(bn);

assert(base == 16 || base == 58);
switch (base) {
case 16:
enc = enc_16;
break;
case 58:
enc = enc_58;
break;
}

while (len) {
char current = *src;

if (base == 16)
current = tolower(current); /* TODO: Not in ccan. */
int val = decode_char(current, enc);
if (val < 0) {
BN_free(bn);
return false;
}
BN_mul_word(bn, base);
BN_add_word(bn, val);
src++;
len--;
}

sha256(digest, data, datasz);
return true;
}

/*
* Decode a base58-encoded string into a byte sequence.
*/
bool raw_decode_base58(BIGNUM *bn, const char *src, size_t len)
{
return raw_decode_base_n(bn, src, len, 58);
}

void base58_get_checksum(u8 csum[4], const u8 buf[], size_t buflen)
{
struct sha256_double sha_result;

/* Form checksum, using double SHA2 (as per bitcoin standard) */
sha256_double(&sha_result, buf, buflen);

/* Use first four bytes of that as the checksum. */
memcpy(csum, sha_result.sha.u.u8, 4);
}

static char *to_base58(const tal_t *ctx, u8 version,
const struct ripemd160 *rmd)
{
u8 buf[1 + sizeof(*rmd) + 4];
char out[BASE58_ADDR_MAX_LEN + 2], *p;

buf[0] = version;
memcpy(buf+1, rmd, sizeof(*rmd));

/* Append checksum */
base58_get_checksum(buf + 1 + sizeof(*rmd), buf, 1 + sizeof(*rmd));
char out[BASE58_ADDR_MAX_LEN + 1];
size_t outlen = sizeof(out);

p = encode_base58(out, BASE58_ADDR_MAX_LEN, buf, sizeof(buf));
return tal_strdup(ctx, p);
b58_sha256_impl = my_sha256;
if (!b58check_enc(out, &outlen, version, rmd, sizeof(*rmd))) {
return NULL;
}else{
return tal_strdup(ctx, out);
}
}

char *bitcoin_to_base58(const tal_t *ctx, bool test_net,
Expand All@@ -173,30 +52,15 @@ static bool from_base58(u8 *version,
const char *base58, size_t base58_len)
{
u8 buf[1 + sizeof(*rmd) + 4];
BIGNUM bn;
size_t len;
u8 csum[4];

BN_init(&bn);
if (!raw_decode_base58(&bn, base58, base58_len))
return false;

len = BN_num_bytes(&bn);
if (len > sizeof(buf))
return false;

memset(buf, 0, sizeof(buf));
BN_bn2bin(&bn, buf + sizeof(buf) - len);
BN_free(&bn);
b58_sha256_impl = my_sha256;

size_t buflen = sizeof(buf);
b58tobin(buf, &buflen, base58, base58_len);
int r = b58check(buf, sizeof(buf), base58, base58_len);
*version = buf[0];

base58_get_checksum(csum, buf, 1 + sizeof(*rmd));
if (memcmp(csum, buf + 1 + sizeof(*rmd), sizeof(csum)) != 0)
return false;

memcpy(rmd, buf+1, sizeof(*rmd));
return true;
memcpy(rmd, buf + 1, sizeof(*rmd));
return r > 0;
}

bool bitcoin_from_base58(bool *test_net,
Expand DownExpand Up@@ -235,124 +99,60 @@ bool p2sh_from_base58(bool *test_net,
return true;
}

/* buf already contains version and ripemd160. Append checksum and encode */
char *base58_with_check(char dest[BASE58_ADDR_MAX_LEN],
u8 buf[1 + sizeof(struct ripemd160) + 4])
{
/* Append checksum */
base58_get_checksum(buf + 1 + sizeof(struct ripemd160),
buf, 1 + sizeof(struct ripemd160));

/* Now encode. */
return encode_base58(dest, BASE58_ADDR_MAX_LEN, buf,
1 + sizeof(struct ripemd160) + 4);
}

bool ripemd_from_base58(u8 *version,
struct ripemd160 *ripemd160,
const char *base58)
{
u8 buf[1 + sizeof(*ripemd160) + 4];
u8 csum[4];
BIGNUM bn;
size_t len;

/* Too long? Check here before doing arithmetic. */
if (strlen(base58) > BASE58_ADDR_MAX_LEN - 1)
return false;

BN_init(&bn);
/* Fails if it contains invalid characters. */
if (!raw_decode_base58(&bn, base58, strlen(base58)))
return false;

/* Too big? */
len = BN_num_bytes(&bn);
if (len > sizeof(buf)) {
BN_free(&bn);
return false;
}

/* Fill start with zeroes. */
memset(buf, 0, sizeof(buf) - len);
BN_bn2bin(&bn, buf + sizeof(buf) - len);
BN_free(&bn);

/* Check checksum is correct. */
base58_get_checksum(csum, buf, sizeof(buf));
if (memcmp(csum, buf + 1 + sizeof(*ripemd160), 4) != 0)
return false;

*version = buf[0];
memcpy(ripemd160, buf + 1, sizeof(*ripemd160));
return true;
return from_base58(version, ripemd160, base58, strlen(base58));
}

char *key_to_base58(const tal_t *ctx, bool test_net, const struct privkey *key)
{
u8 buf[1 + 32 + 1 + 4];
char out[BASE58_KEY_MAX_LEN + 2], *p;

buf[0] = test_net ? 239 : 128;
memcpy(buf + 1, key->secret, sizeof(key->secret));
u8 buf[32 + 1];
char out[BASE58_KEY_MAX_LEN + 2];
u8 version = test_net ? 239 : 128;
size_t outlen = sizeof(out);

memcpy(buf, key->secret, sizeof(key->secret));
/* Mark this as a compressed key. */
buf[1 + 32] = 1;
buf[32] = 1;

/* Append checksum */
base58_get_checksum(buf + 1 + 32 + 1, buf, 1 + 32 + 1);

p = encode_base58(out, BASE58_KEY_MAX_LEN, buf, sizeof(buf));
return tal_strdup(ctx, p);
b58check_enc(out, &outlen, version, buf, sizeof(buf));
return tal_strdup(ctx, out);
}

bool key_from_base58(secp256k1_context *secpctx,
const char *base58, size_t base58_len,
bool *test_net, struct privkey *priv, struct pubkey *key)
{
// 1 byte version, 32 byte private key, 1 byte compressed, 4 byte checksum
u8 keybuf[1 + 32 + 1 + 4];
u8 csum[4];
BIGNUM bn;
size_t keylen;

BN_init(&bn);
if (!raw_decode_base58(&bn, base58, base58_len))
return false;

keylen = BN_num_bytes(&bn);
if (keylen != 1 + 32 + 1 + 4)
goto fail_free_bn;
BN_bn2bin(&bn, keybuf);
size_t keybuflen = sizeof(keybuf);

base58_get_checksum(csum, keybuf, keylen - sizeof(csum));
if (memcmp(csum, keybuf + keylen - sizeof(csum), sizeof(csum)) != 0)
goto fail_free_bn;
b58tobin(keybuf, &keybuflen, base58, base58_len);
if (b58check(keybuf, sizeof(keybuf), base58, base58_len) < 0)
return false;

/* Byte after key should be 1 to represent a compressed key. */
if (keybuf[1 + 32] != 1)
goto fail_free_bn;
return false;

if (keybuf[0] == 128)
*test_net = false;
else if (keybuf[0] == 239)
*test_net = true;
else
goto fail_free_bn;
return false;

/* Copy out secret. */
memcpy(priv->secret, keybuf + 1, sizeof(priv->secret));

if (!secp256k1_ec_seckey_verify(secpctx, priv->secret))
goto fail_free_bn;
return false;

/* Get public key, too. */
if (!pubkey_from_privkey(secpctx, priv, key))
goto fail_free_bn;
return false;

BN_free(&bn);
return true;

fail_free_bn:
BN_free(&bn);
return false;
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Makefile
Original file line numberDiff line numberDiff line change
Expand Up@@ -177,7 +177,7 @@ CWARNFLAGS := -Werror -Wall -Wundef -Wmissing-prototypes -Wmissing-declarations
CDEBUGFLAGS := -g -fstack-protector
CFLAGS := $(CWARNFLAGS) $(CDEBUGFLAGS) -I $(CCANDIR) -I secp256k1/include/ -I . $(FEATURES)

LDLIBS := -lcrypto -lprotobuf-c -lgmp -lsodium
LDLIBS := -lprotobuf-c -lgmp -lsodium -lbase58
$(PROGRAMS): CFLAGS+=-I.

default: $(PROGRAMS) daemon-all
Expand Down
270 changes: 35 additions & 235 deletions bitcoin/base58.c
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,149 +11,28 @@
#include <assert.h>
#include <ccan/build_assert/build_assert.h>
#include <ccan/tal/str/str.h>
#include <openssl/bn.h>
#include <secp256k1.h>
#include <string.h>
#include <libbase58.h>

static const char enc_16[] = "0123456789abcdef";
static const char enc_58[] =
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

static char encode_char(unsigned long val, const char *enc)
{
assert(val < strlen(enc));
return enc[val];
}

static int decode_char(char c, const char *enc)
{
const char *pos = strchr(enc, c);
if (!pos)
return -1;
return pos - enc;
}

/*
* Encode a byte sequence as a base58-encoded string. This is a bit
* weird: returns pointer into buf (or NULL if wouldn't fit).
*/
static char *encode_base58(char *buf, size_t buflen,
const u8 *data, size_t data_len)
{
char *p;
BIGNUM bn;

/* Convert to a bignum. */
BN_init(&bn);
BN_bin2bn(data, data_len, &bn);

/* Add NUL terminator */
if (!buflen) {
p = NULL;
goto out;
}
p = buf + buflen;
*(--p) = '\0';

/* Fill from the back, using a series of divides. */
while (!BN_is_zero(&bn)) {
int rem = BN_div_word(&bn, 58);
if (--p < buf) {
p = NULL;
goto out;
}
*p = encode_char(rem, enc_58);
}

/* Now, this is really weird. We pad with zeroes, but not at
* base 58, but in terms of zero bytes. This means that some
* encodings are shorter than others! */
while (data_len && *data == '\0') {
if (--p < buf) {
p = NULL;
goto out;
}
*p = encode_char(0, enc_58);
data_len--;
data++;
}

out:
BN_free(&bn);
return p;
}

/*
* Decode a base_n-encoded string into a byte sequence.
*/
bool raw_decode_base_n(BIGNUM *bn, const char *src, size_t len, int base)
static bool my_sha256(void *digest, const void *data, size_t datasz)
{
const char *enc;

BN_zero(bn);

assert(base == 16 || base == 58);
switch (base) {
case 16:
enc = enc_16;
break;
case 58:
enc = enc_58;
break;
}

while (len) {
char current = *src;

if (base == 16)
current = tolower(current); /* TODO: Not in ccan. */
int val = decode_char(current, enc);
if (val < 0) {
BN_free(bn);
return false;
}
BN_mul_word(bn, base);
BN_add_word(bn, val);
src++;
len--;
}

sha256(digest, data, datasz);
return true;
}

/*
* Decode a base58-encoded string into a byte sequence.
*/
bool raw_decode_base58(BIGNUM *bn, const char *src, size_t len)
{
return raw_decode_base_n(bn, src, len, 58);
}

void base58_get_checksum(u8 csum[4], const u8 buf[], size_t buflen)
{
struct sha256_double sha_result;

/* Form checksum, using double SHA2 (as per bitcoin standard) */
sha256_double(&sha_result, buf, buflen);

/* Use first four bytes of that as the checksum. */
memcpy(csum, sha_result.sha.u.u8, 4);
}

static char *to_base58(const tal_t *ctx, u8 version,
const struct ripemd160 *rmd)
{
u8 buf[1 + sizeof(*rmd) + 4];
char out[BASE58_ADDR_MAX_LEN + 2], *p;

buf[0] = version;
memcpy(buf+1, rmd, sizeof(*rmd));

/* Append checksum */
base58_get_checksum(buf + 1 + sizeof(*rmd), buf, 1 + sizeof(*rmd));
char out[BASE58_ADDR_MAX_LEN + 1];
size_t outlen = sizeof(out);

p = encode_base58(out, BASE58_ADDR_MAX_LEN, buf, sizeof(buf));
return tal_strdup(ctx, p);
b58_sha256_impl = my_sha256;
if (!b58check_enc(out, &outlen, version, rmd, sizeof(*rmd))) {
return NULL;
}else{
return tal_strdup(ctx, out);
}
}

char *bitcoin_to_base58(const tal_t *ctx, bool test_net,
Expand All@@ -173,30 +52,15 @@ static bool from_base58(u8 *version,
const char *base58, size_t base58_len)
{
u8 buf[1 + sizeof(*rmd) + 4];
BIGNUM bn;
size_t len;
u8 csum[4];

BN_init(&bn);
if (!raw_decode_base58(&bn, base58, base58_len))
return false;

len = BN_num_bytes(&bn);
if (len > sizeof(buf))
return false;

memset(buf, 0, sizeof(buf));
BN_bn2bin(&bn, buf + sizeof(buf) - len);
BN_free(&bn);
b58_sha256_impl = my_sha256;

size_t buflen = sizeof(buf);
b58tobin(buf, &buflen, base58, base58_len);
int r = b58check(buf, sizeof(buf), base58, base58_len);
*version = buf[0];

base58_get_checksum(csum, buf, 1 + sizeof(*rmd));
if (memcmp(csum, buf + 1 + sizeof(*rmd), sizeof(csum)) != 0)
return false;

memcpy(rmd, buf+1, sizeof(*rmd));
return true;
memcpy(rmd, buf + 1, sizeof(*rmd));
return r > 0;
}

bool bitcoin_from_base58(bool *test_net,
Expand DownExpand Up@@ -235,124 +99,60 @@ bool p2sh_from_base58(bool *test_net,
return true;
}

/* buf already contains version and ripemd160. Append checksum and encode */
char *base58_with_check(char dest[BASE58_ADDR_MAX_LEN],
u8 buf[1 + sizeof(struct ripemd160) + 4])
{
/* Append checksum */
base58_get_checksum(buf + 1 + sizeof(struct ripemd160),
buf, 1 + sizeof(struct ripemd160));

/* Now encode. */
return encode_base58(dest, BASE58_ADDR_MAX_LEN, buf,
1 + sizeof(struct ripemd160) + 4);
}

bool ripemd_from_base58(u8 *version,
struct ripemd160 *ripemd160,
const char *base58)
{
u8 buf[1 + sizeof(*ripemd160) + 4];
u8 csum[4];
BIGNUM bn;
size_t len;

/* Too long? Check here before doing arithmetic. */
if (strlen(base58) > BASE58_ADDR_MAX_LEN - 1)
return false;

BN_init(&bn);
/* Fails if it contains invalid characters. */
if (!raw_decode_base58(&bn, base58, strlen(base58)))
return false;

/* Too big? */
len = BN_num_bytes(&bn);
if (len > sizeof(buf)) {
BN_free(&bn);
return false;
}

/* Fill start with zeroes. */
memset(buf, 0, sizeof(buf) - len);
BN_bn2bin(&bn, buf + sizeof(buf) - len);
BN_free(&bn);

/* Check checksum is correct. */
base58_get_checksum(csum, buf, sizeof(buf));
if (memcmp(csum, buf + 1 + sizeof(*ripemd160), 4) != 0)
return false;

*version = buf[0];
memcpy(ripemd160, buf + 1, sizeof(*ripemd160));
return true;
return from_base58(version, ripemd160, base58, strlen(base58));
}

char *key_to_base58(const tal_t *ctx, bool test_net, const struct privkey *key)
{
u8 buf[1 + 32 + 1 + 4];
char out[BASE58_KEY_MAX_LEN + 2], *p;

buf[0] = test_net ? 239 : 128;
memcpy(buf + 1, key->secret, sizeof(key->secret));
u8 buf[32 + 1];
char out[BASE58_KEY_MAX_LEN + 2];
u8 version = test_net ? 239 : 128;
size_t outlen = sizeof(out);

memcpy(buf, key->secret, sizeof(key->secret));
/* Mark this as a compressed key. */
buf[1 + 32] = 1;
buf[32] = 1;

/* Append checksum */
base58_get_checksum(buf + 1 + 32 + 1, buf, 1 + 32 + 1);

p = encode_base58(out, BASE58_KEY_MAX_LEN, buf, sizeof(buf));
return tal_strdup(ctx, p);
b58check_enc(out, &outlen, version, buf, sizeof(buf));
return tal_strdup(ctx, out);
}

bool key_from_base58(secp256k1_context *secpctx,
const char *base58, size_t base58_len,
bool *test_net, struct privkey *priv, struct pubkey *key)
{
// 1 byte version, 32 byte private key, 1 byte compressed, 4 byte checksum
u8 keybuf[1 + 32 + 1 + 4];
u8 csum[4];
BIGNUM bn;
size_t keylen;

BN_init(&bn);
if (!raw_decode_base58(&bn, base58, base58_len))
return false;

keylen = BN_num_bytes(&bn);
if (keylen != 1 + 32 + 1 + 4)
goto fail_free_bn;
BN_bn2bin(&bn, keybuf);
size_t keybuflen = sizeof(keybuf);

base58_get_checksum(csum, keybuf, keylen - sizeof(csum));
if (memcmp(csum, keybuf + keylen - sizeof(csum), sizeof(csum)) != 0)
goto fail_free_bn;
b58tobin(keybuf, &keybuflen, base58, base58_len);
if (b58check(keybuf, sizeof(keybuf), base58, base58_len) < 0)
return false;

/* Byte after key should be 1 to represent a compressed key. */
if (keybuf[1 + 32] != 1)
goto fail_free_bn;
return false;

if (keybuf[0] == 128)
*test_net = false;
else if (keybuf[0] == 239)
*test_net = true;
else
goto fail_free_bn;
return false;

/* Copy out secret. */
memcpy(priv->secret, keybuf + 1, sizeof(priv->secret));

if (!secp256k1_ec_seckey_verify(secpctx, priv->secret))
goto fail_free_bn;
return false;

/* Get public key, too. */
if (!pubkey_from_privkey(secpctx, priv, key))
goto fail_free_bn;
return false;

BN_free(&bn);
return true;

fail_free_bn:
BN_free(&bn);
return false;
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Makefile
Original file line numberDiff line numberDiff line change
Expand Up@@ -177,7 +177,7 @@ CWARNFLAGS := -Werror -Wall -Wundef -Wmissing-prototypes -Wmissing-declarations
CDEBUGFLAGS := -g -fstack-protector
CFLAGS := $(CWARNFLAGS) $(CDEBUGFLAGS) -I $(CCANDIR) -I secp256k1/include/ -I . $(FEATURES)

LDLIBS := -lcrypto -lprotobuf-c -lgmp -lsodium
LDLIBS := -lprotobuf-c -lgmp -lsodium -lbase58
$(PROGRAMS): CFLAGS+=-I.

default: $(PROGRAMS) daemon-all
Expand Down
270 changes: 35 additions & 235 deletions bitcoin/base58.c
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,149 +11,28 @@
#include <assert.h>
#include <ccan/build_assert/build_assert.h>
#include <ccan/tal/str/str.h>
#include <openssl/bn.h>
#include <secp256k1.h>
#include <string.h>
#include <libbase58.h>

static const char enc_16[] = "0123456789abcdef";
static const char enc_58[] =
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

static char encode_char(unsigned long val, const char *enc)
{
assert(val < strlen(enc));
return enc[val];
}

static int decode_char(char c, const char *enc)
{
const char *pos = strchr(enc, c);
if (!pos)
return -1;
return pos - enc;
}

/*
* Encode a byte sequence as a base58-encoded string. This is a bit
* weird: returns pointer into buf (or NULL if wouldn't fit).
*/
static char *encode_base58(char *buf, size_t buflen,
const u8 *data, size_t data_len)
{
char *p;
BIGNUM bn;

/* Convert to a bignum. */
BN_init(&bn);
BN_bin2bn(data, data_len, &bn);

/* Add NUL terminator */
if (!buflen) {
p = NULL;
goto out;
}
p = buf + buflen;
*(--p) = '\0';

/* Fill from the back, using a series of divides. */
while (!BN_is_zero(&bn)) {
int rem = BN_div_word(&bn, 58);
if (--p < buf) {
p = NULL;
goto out;
}
*p = encode_char(rem, enc_58);
}

/* Now, this is really weird. We pad with zeroes, but not at
* base 58, but in terms of zero bytes. This means that some
* encodings are shorter than others! */
while (data_len && *data == '\0') {
if (--p < buf) {
p = NULL;
goto out;
}
*p = encode_char(0, enc_58);
data_len--;
data++;
}

out:
BN_free(&bn);
return p;
}

/*
* Decode a base_n-encoded string into a byte sequence.
*/
bool raw_decode_base_n(BIGNUM *bn, const char *src, size_t len, int base)
static bool my_sha256(void *digest, const void *data, size_t datasz)
{
const char *enc;

BN_zero(bn);

assert(base == 16 || base == 58);
switch (base) {
case 16:
enc = enc_16;
break;
case 58:
enc = enc_58;
break;
}

while (len) {
char current = *src;

if (base == 16)
current = tolower(current); /* TODO: Not in ccan. */
int val = decode_char(current, enc);
if (val < 0) {
BN_free(bn);
return false;
}
BN_mul_word(bn, base);
BN_add_word(bn, val);
src++;
len--;
}

sha256(digest, data, datasz);
return true;
}

/*
* Decode a base58-encoded string into a byte sequence.
*/
bool raw_decode_base58(BIGNUM *bn, const char *src, size_t len)
{
return raw_decode_base_n(bn, src, len, 58);
}

void base58_get_checksum(u8 csum[4], const u8 buf[], size_t buflen)
{
struct sha256_double sha_result;

/* Form checksum, using double SHA2 (as per bitcoin standard) */
sha256_double(&sha_result, buf, buflen);

/* Use first four bytes of that as the checksum. */
memcpy(csum, sha_result.sha.u.u8, 4);
}

static char *to_base58(const tal_t *ctx, u8 version,
const struct ripemd160 *rmd)
{
u8 buf[1 + sizeof(*rmd) + 4];
char out[BASE58_ADDR_MAX_LEN + 2], *p;

buf[0] = version;
memcpy(buf+1, rmd, sizeof(*rmd));

/* Append checksum */
base58_get_checksum(buf + 1 + sizeof(*rmd), buf, 1 + sizeof(*rmd));
char out[BASE58_ADDR_MAX_LEN + 1];
size_t outlen = sizeof(out);

p = encode_base58(out, BASE58_ADDR_MAX_LEN, buf, sizeof(buf));
return tal_strdup(ctx, p);
b58_sha256_impl = my_sha256;
if (!b58check_enc(out, &outlen, version, rmd, sizeof(*rmd))) {
return NULL;
}else{
return tal_strdup(ctx, out);
}
}

char *bitcoin_to_base58(const tal_t *ctx, bool test_net,
Expand All@@ -173,30 +52,15 @@ static bool from_base58(u8 *version,
const char *base58, size_t base58_len)
{
u8 buf[1 + sizeof(*rmd) + 4];
BIGNUM bn;
size_t len;
u8 csum[4];

BN_init(&bn);
if (!raw_decode_base58(&bn, base58, base58_len))
return false;

len = BN_num_bytes(&bn);
if (len > sizeof(buf))
return false;

memset(buf, 0, sizeof(buf));
BN_bn2bin(&bn, buf + sizeof(buf) - len);
BN_free(&bn);
b58_sha256_impl = my_sha256;

size_t buflen = sizeof(buf);
b58tobin(buf, &buflen, base58, base58_len);
int r = b58check(buf, sizeof(buf), base58, base58_len);
*version = buf[0];

base58_get_checksum(csum, buf, 1 + sizeof(*rmd));
if (memcmp(csum, buf + 1 + sizeof(*rmd), sizeof(csum)) != 0)
return false;

memcpy(rmd, buf+1, sizeof(*rmd));
return true;
memcpy(rmd, buf + 1, sizeof(*rmd));
return r > 0;
}

bool bitcoin_from_base58(bool *test_net,
Expand DownExpand Up@@ -235,124 +99,60 @@ bool p2sh_from_base58(bool *test_net,
return true;
}

/* buf already contains version and ripemd160. Append checksum and encode */
char *base58_with_check(char dest[BASE58_ADDR_MAX_LEN],
u8 buf[1 + sizeof(struct ripemd160) + 4])
{
/* Append checksum */
base58_get_checksum(buf + 1 + sizeof(struct ripemd160),
buf, 1 + sizeof(struct ripemd160));

/* Now encode. */
return encode_base58(dest, BASE58_ADDR_MAX_LEN, buf,
1 + sizeof(struct ripemd160) + 4);
}

bool ripemd_from_base58(u8 *version,
struct ripemd160 *ripemd160,
const char *base58)
{
u8 buf[1 + sizeof(*ripemd160) + 4];
u8 csum[4];
BIGNUM bn;
size_t len;

/* Too long? Check here before doing arithmetic. */
if (strlen(base58) > BASE58_ADDR_MAX_LEN - 1)
return false;

BN_init(&bn);
/* Fails if it contains invalid characters. */
if (!raw_decode_base58(&bn, base58, strlen(base58)))
return false;

/* Too big? */
len = BN_num_bytes(&bn);
if (len > sizeof(buf)) {
BN_free(&bn);
return false;
}

/* Fill start with zeroes. */
memset(buf, 0, sizeof(buf) - len);
BN_bn2bin(&bn, buf + sizeof(buf) - len);
BN_free(&bn);

/* Check checksum is correct. */
base58_get_checksum(csum, buf, sizeof(buf));
if (memcmp(csum, buf + 1 + sizeof(*ripemd160), 4) != 0)
return false;

*version = buf[0];
memcpy(ripemd160, buf + 1, sizeof(*ripemd160));
return true;
return from_base58(version, ripemd160, base58, strlen(base58));
}

char *key_to_base58(const tal_t *ctx, bool test_net, const struct privkey *key)
{
u8 buf[1 + 32 + 1 + 4];
char out[BASE58_KEY_MAX_LEN + 2], *p;

buf[0] = test_net ? 239 : 128;
memcpy(buf + 1, key->secret, sizeof(key->secret));
u8 buf[32 + 1];
char out[BASE58_KEY_MAX_LEN + 2];
u8 version = test_net ? 239 : 128;
size_t outlen = sizeof(out);

memcpy(buf, key->secret, sizeof(key->secret));
/* Mark this as a compressed key. */
buf[1 + 32] = 1;
buf[32] = 1;

/* Append checksum */
base58_get_checksum(buf + 1 + 32 + 1, buf, 1 + 32 + 1);

p = encode_base58(out, BASE58_KEY_MAX_LEN, buf, sizeof(buf));
return tal_strdup(ctx, p);
b58check_enc(out, &outlen, version, buf, sizeof(buf));
return tal_strdup(ctx, out);
}

bool key_from_base58(secp256k1_context *secpctx,
const char *base58, size_t base58_len,
bool *test_net, struct privkey *priv, struct pubkey *key)
{
// 1 byte version, 32 byte private key, 1 byte compressed, 4 byte checksum
u8 keybuf[1 + 32 + 1 + 4];
u8 csum[4];
BIGNUM bn;
size_t keylen;

BN_init(&bn);
if (!raw_decode_base58(&bn, base58, base58_len))
return false;

keylen = BN_num_bytes(&bn);
if (keylen != 1 + 32 + 1 + 4)
goto fail_free_bn;
BN_bn2bin(&bn, keybuf);
size_t keybuflen = sizeof(keybuf);

base58_get_checksum(csum, keybuf, keylen - sizeof(csum));
if (memcmp(csum, keybuf + keylen - sizeof(csum), sizeof(csum)) != 0)
goto fail_free_bn;
b58tobin(keybuf, &keybuflen, base58, base58_len);
if (b58check(keybuf, sizeof(keybuf), base58, base58_len) < 0)
return false;

/* Byte after key should be 1 to represent a compressed key. */
if (keybuf[1 + 32] != 1)
goto fail_free_bn;
return false;

if (keybuf[0] == 128)
*test_net = false;
else if (keybuf[0] == 239)
*test_net = true;
else
goto fail_free_bn;
return false;

/* Copy out secret. */
memcpy(priv->secret, keybuf + 1, sizeof(priv->secret));

if (!secp256k1_ec_seckey_verify(secpctx, priv->secret))
goto fail_free_bn;
return false;

/* Get public key, too. */
if (!pubkey_from_privkey(secpctx, priv, key))
goto fail_free_bn;
return false;

BN_free(&bn);
return true;

fail_free_bn:
BN_free(&bn);
return false;
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Makefile
Original file line numberDiff line numberDiff line change
Expand Up@@ -177,7 +177,7 @@ CWARNFLAGS := -Werror -Wall -Wundef -Wmissing-prototypes -Wmissing-declarations
CDEBUGFLAGS := -g -fstack-protector
CFLAGS := $(CWARNFLAGS) $(CDEBUGFLAGS) -I $(CCANDIR) -I secp256k1/include/ -I . $(FEATURES)

LDLIBS := -lcrypto -lprotobuf-c -lgmp -lsodium
LDLIBS := -lprotobuf-c -lgmp -lsodium -lbase58
$(PROGRAMS): CFLAGS+=-I.

default: $(PROGRAMS) daemon-all
Expand Down
270 changes: 35 additions & 235 deletions bitcoin/base58.c
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,149 +11,28 @@
#include <assert.h>
#include <ccan/build_assert/build_assert.h>
#include <ccan/tal/str/str.h>
#include <openssl/bn.h>
#include <secp256k1.h>
#include <string.h>
#include <libbase58.h>

static const char enc_16[] = "0123456789abcdef";
static const char enc_58[] =
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

static char encode_char(unsigned long val, const char *enc)
{
assert(val < strlen(enc));
return enc[val];
}

static int decode_char(char c, const char *enc)
{
const char *pos = strchr(enc, c);
if (!pos)
return -1;
return pos - enc;
}

/*
* Encode a byte sequence as a base58-encoded string. This is a bit
* weird: returns pointer into buf (or NULL if wouldn't fit).
*/
static char *encode_base58(char *buf, size_t buflen,
const u8 *data, size_t data_len)
{
char *p;
BIGNUM bn;

/* Convert to a bignum. */
BN_init(&bn);
BN_bin2bn(data, data_len, &bn);

/* Add NUL terminator */
if (!buflen) {
p = NULL;
goto out;
}
p = buf + buflen;
*(--p) = '\0';

/* Fill from the back, using a series of divides. */
while (!BN_is_zero(&bn)) {
int rem = BN_div_word(&bn, 58);
if (--p < buf) {
p = NULL;
goto out;
}
*p = encode_char(rem, enc_58);
}

/* Now, this is really weird. We pad with zeroes, but not at
* base 58, but in terms of zero bytes. This means that some
* encodings are shorter than others! */
while (data_len && *data == '\0') {
if (--p < buf) {
p = NULL;
goto out;
}
*p = encode_char(0, enc_58);
data_len--;
data++;
}

out:
BN_free(&bn);
return p;
}

/*
* Decode a base_n-encoded string into a byte sequence.
*/
bool raw_decode_base_n(BIGNUM *bn, const char *src, size_t len, int base)
static bool my_sha256(void *digest, const void *data, size_t datasz)
{
const char *enc;

BN_zero(bn);

assert(base == 16 || base == 58);
switch (base) {
case 16:
enc = enc_16;
break;
case 58:
enc = enc_58;
break;
}

while (len) {
char current = *src;

if (base == 16)
current = tolower(current); /* TODO: Not in ccan. */
int val = decode_char(current, enc);
if (val < 0) {
BN_free(bn);
return false;
}
BN_mul_word(bn, base);
BN_add_word(bn, val);
src++;
len--;
}

sha256(digest, data, datasz);
return true;
}

/*
* Decode a base58-encoded string into a byte sequence.
*/
bool raw_decode_base58(BIGNUM *bn, const char *src, size_t len)
{
return raw_decode_base_n(bn, src, len, 58);
}

void base58_get_checksum(u8 csum[4], const u8 buf[], size_t buflen)
{
struct sha256_double sha_result;

/* Form checksum, using double SHA2 (as per bitcoin standard) */
sha256_double(&sha_result, buf, buflen);

/* Use first four bytes of that as the checksum. */
memcpy(csum, sha_result.sha.u.u8, 4);
}

static char *to_base58(const tal_t *ctx, u8 version,
const struct ripemd160 *rmd)
{
u8 buf[1 + sizeof(*rmd) + 4];
char out[BASE58_ADDR_MAX_LEN + 2], *p;

buf[0] = version;
memcpy(buf+1, rmd, sizeof(*rmd));

/* Append checksum */
base58_get_checksum(buf + 1 + sizeof(*rmd), buf, 1 + sizeof(*rmd));
char out[BASE58_ADDR_MAX_LEN + 1];
size_t outlen = sizeof(out);

p = encode_base58(out, BASE58_ADDR_MAX_LEN, buf, sizeof(buf));
return tal_strdup(ctx, p);
b58_sha256_impl = my_sha256;
if (!b58check_enc(out, &outlen, version, rmd, sizeof(*rmd))) {
return NULL;
}else{
return tal_strdup(ctx, out);
}
}

char *bitcoin_to_base58(const tal_t *ctx, bool test_net,
Expand All@@ -173,30 +52,15 @@ static bool from_base58(u8 *version,
const char *base58, size_t base58_len)
{
u8 buf[1 + sizeof(*rmd) + 4];
BIGNUM bn;
size_t len;
u8 csum[4];

BN_init(&bn);
if (!raw_decode_base58(&bn, base58, base58_len))
return false;

len = BN_num_bytes(&bn);
if (len > sizeof(buf))
return false;

memset(buf, 0, sizeof(buf));
BN_bn2bin(&bn, buf + sizeof(buf) - len);
BN_free(&bn);
b58_sha256_impl = my_sha256;

size_t buflen = sizeof(buf);
b58tobin(buf, &buflen, base58, base58_len);
int r = b58check(buf, sizeof(buf), base58, base58_len);
*version = buf[0];

base58_get_checksum(csum, buf, 1 + sizeof(*rmd));
if (memcmp(csum, buf + 1 + sizeof(*rmd), sizeof(csum)) != 0)
return false;

memcpy(rmd, buf+1, sizeof(*rmd));
return true;
memcpy(rmd, buf + 1, sizeof(*rmd));
return r > 0;
}

bool bitcoin_from_base58(bool *test_net,
Expand DownExpand Up@@ -235,124 +99,60 @@ bool p2sh_from_base58(bool *test_net,
return true;
}

/* buf already contains version and ripemd160. Append checksum and encode */
char *base58_with_check(char dest[BASE58_ADDR_MAX_LEN],
u8 buf[1 + sizeof(struct ripemd160) + 4])
{
/* Append checksum */
base58_get_checksum(buf + 1 + sizeof(struct ripemd160),
buf, 1 + sizeof(struct ripemd160));

/* Now encode. */
return encode_base58(dest, BASE58_ADDR_MAX_LEN, buf,
1 + sizeof(struct ripemd160) + 4);
}

bool ripemd_from_base58(u8 *version,
struct ripemd160 *ripemd160,
const char *base58)
{
u8 buf[1 + sizeof(*ripemd160) + 4];
u8 csum[4];
BIGNUM bn;
size_t len;

/* Too long? Check here before doing arithmetic. */
if (strlen(base58) > BASE58_ADDR_MAX_LEN - 1)
return false;

BN_init(&bn);
/* Fails if it contains invalid characters. */
if (!raw_decode_base58(&bn, base58, strlen(base58)))
return false;

/* Too big? */
len = BN_num_bytes(&bn);
if (len > sizeof(buf)) {
BN_free(&bn);
return false;
}

/* Fill start with zeroes. */
memset(buf, 0, sizeof(buf) - len);
BN_bn2bin(&bn, buf + sizeof(buf) - len);
BN_free(&bn);

/* Check checksum is correct. */
base58_get_checksum(csum, buf, sizeof(buf));
if (memcmp(csum, buf + 1 + sizeof(*ripemd160), 4) != 0)
return false;

*version = buf[0];
memcpy(ripemd160, buf + 1, sizeof(*ripemd160));
return true;
return from_base58(version, ripemd160, base58, strlen(base58));
}

char *key_to_base58(const tal_t *ctx, bool test_net, const struct privkey *key)
{
u8 buf[1 + 32 + 1 + 4];
char out[BASE58_KEY_MAX_LEN + 2], *p;

buf[0] = test_net ? 239 : 128;
memcpy(buf + 1, key->secret, sizeof(key->secret));
u8 buf[32 + 1];
char out[BASE58_KEY_MAX_LEN + 2];
u8 version = test_net ? 239 : 128;
size_t outlen = sizeof(out);

memcpy(buf, key->secret, sizeof(key->secret));
/* Mark this as a compressed key. */
buf[1 + 32] = 1;
buf[32] = 1;

/* Append checksum */
base58_get_checksum(buf + 1 + 32 + 1, buf, 1 + 32 + 1);

p = encode_base58(out, BASE58_KEY_MAX_LEN, buf, sizeof(buf));
return tal_strdup(ctx, p);
b58check_enc(out, &outlen, version, buf, sizeof(buf));
return tal_strdup(ctx, out);
}

bool key_from_base58(secp256k1_context *secpctx,
const char *base58, size_t base58_len,
bool *test_net, struct privkey *priv, struct pubkey *key)
{
// 1 byte version, 32 byte private key, 1 byte compressed, 4 byte checksum
u8 keybuf[1 + 32 + 1 + 4];
u8 csum[4];
BIGNUM bn;
size_t keylen;

BN_init(&bn);
if (!raw_decode_base58(&bn, base58, base58_len))
return false;

keylen = BN_num_bytes(&bn);
if (keylen != 1 + 32 + 1 + 4)
goto fail_free_bn;
BN_bn2bin(&bn, keybuf);
size_t keybuflen = sizeof(keybuf);

base58_get_checksum(csum, keybuf, keylen - sizeof(csum));
if (memcmp(csum, keybuf + keylen - sizeof(csum), sizeof(csum)) != 0)
goto fail_free_bn;
b58tobin(keybuf, &keybuflen, base58, base58_len);
if (b58check(keybuf, sizeof(keybuf), base58, base58_len) < 0)
return false;

/* Byte after key should be 1 to represent a compressed key. */
if (keybuf[1 + 32] != 1)
goto fail_free_bn;
return false;

if (keybuf[0] == 128)
*test_net = false;
else if (keybuf[0] == 239)
*test_net = true;
else
goto fail_free_bn;
return false;

/* Copy out secret. */
memcpy(priv->secret, keybuf + 1, sizeof(priv->secret));

if (!secp256k1_ec_seckey_verify(secpctx, priv->secret))
goto fail_free_bn;
return false;

/* Get public key, too. */
if (!pubkey_from_privkey(secpctx, priv, key))
goto fail_free_bn;
return false;

BN_free(&bn);
return true;

fail_free_bn:
BN_free(&bn);
return false;
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Makefile
Original file line numberDiff line numberDiff line change
Expand Up@@ -177,7 +177,7 @@ CWARNFLAGS := -Werror -Wall -Wundef -Wmissing-prototypes -Wmissing-declarations
CDEBUGFLAGS := -g -fstack-protector
CFLAGS := $(CWARNFLAGS) $(CDEBUGFLAGS) -I $(CCANDIR) -I secp256k1/include/ -I . $(FEATURES)

LDLIBS := -lcrypto -lprotobuf-c -lgmp -lsodium
LDLIBS := -lprotobuf-c -lgmp -lsodium -lbase58
$(PROGRAMS): CFLAGS+=-I.

default: $(PROGRAMS) daemon-all
Expand Down
270 changes: 35 additions & 235 deletions bitcoin/base58.c
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,149 +11,28 @@
#include <assert.h>
#include <ccan/build_assert/build_assert.h>
#include <ccan/tal/str/str.h>
#include <openssl/bn.h>
#include <secp256k1.h>
#include <string.h>
#include <libbase58.h>

static const char enc_16[] = "0123456789abcdef";
static const char enc_58[] =
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

static char encode_char(unsigned long val, const char *enc)
{
assert(val < strlen(enc));
return enc[val];
}

static int decode_char(char c, const char *enc)
{
const char *pos = strchr(enc, c);
if (!pos)
return -1;
return pos - enc;
}

/*
* Encode a byte sequence as a base58-encoded string. This is a bit
* weird: returns pointer into buf (or NULL if wouldn't fit).
*/
static char *encode_base58(char *buf, size_t buflen,
const u8 *data, size_t data_len)
{
char *p;
BIGNUM bn;

/* Convert to a bignum. */
BN_init(&bn);
BN_bin2bn(data, data_len, &bn);

/* Add NUL terminator */
if (!buflen) {
p = NULL;
goto out;
}
p = buf + buflen;
*(--p) = '\0';

/* Fill from the back, using a series of divides. */
while (!BN_is_zero(&bn)) {
int rem = BN_div_word(&bn, 58);
if (--p < buf) {
p = NULL;
goto out;
}
*p = encode_char(rem, enc_58);
}

/* Now, this is really weird. We pad with zeroes, but not at
* base 58, but in terms of zero bytes. This means that some
* encodings are shorter than others! */
while (data_len && *data == '\0') {
if (--p < buf) {
p = NULL;
goto out;
}
*p = encode_char(0, enc_58);
data_len--;
data++;
}

out:
BN_free(&bn);
return p;
}

/*
* Decode a base_n-encoded string into a byte sequence.
*/
bool raw_decode_base_n(BIGNUM *bn, const char *src, size_t len, int base)
static bool my_sha256(void *digest, const void *data, size_t datasz)
{
const char *enc;

BN_zero(bn);

assert(base == 16 || base == 58);
switch (base) {
case 16:
enc = enc_16;
break;
case 58:
enc = enc_58;
break;
}

while (len) {
char current = *src;

if (base == 16)
current = tolower(current); /* TODO: Not in ccan. */
int val = decode_char(current, enc);
if (val < 0) {
BN_free(bn);
return false;
}
BN_mul_word(bn, base);
BN_add_word(bn, val);
src++;
len--;
}

sha256(digest, data, datasz);
return true;
}

/*
* Decode a base58-encoded string into a byte sequence.
*/
bool raw_decode_base58(BIGNUM *bn, const char *src, size_t len)
{
return raw_decode_base_n(bn, src, len, 58);
}

void base58_get_checksum(u8 csum[4], const u8 buf[], size_t buflen)
{
struct sha256_double sha_result;

/* Form checksum, using double SHA2 (as per bitcoin standard) */
sha256_double(&sha_result, buf, buflen);

/* Use first four bytes of that as the checksum. */
memcpy(csum, sha_result.sha.u.u8, 4);
}

static char *to_base58(const tal_t *ctx, u8 version,
const struct ripemd160 *rmd)
{
u8 buf[1 + sizeof(*rmd) + 4];
char out[BASE58_ADDR_MAX_LEN + 2], *p;

buf[0] = version;
memcpy(buf+1, rmd, sizeof(*rmd));

/* Append checksum */
base58_get_checksum(buf + 1 + sizeof(*rmd), buf, 1 + sizeof(*rmd));
char out[BASE58_ADDR_MAX_LEN + 1];
size_t outlen = sizeof(out);

p = encode_base58(out, BASE58_ADDR_MAX_LEN, buf, sizeof(buf));
return tal_strdup(ctx, p);
b58_sha256_impl = my_sha256;
if (!b58check_enc(out, &outlen, version, rmd, sizeof(*rmd))) {
return NULL;
}else{
return tal_strdup(ctx, out);
}
}

char *bitcoin_to_base58(const tal_t *ctx, bool test_net,
Expand All@@ -173,30 +52,15 @@ static bool from_base58(u8 *version,
const char *base58, size_t base58_len)
{
u8 buf[1 + sizeof(*rmd) + 4];
BIGNUM bn;
size_t len;
u8 csum[4];

BN_init(&bn);
if (!raw_decode_base58(&bn, base58, base58_len))
return false;

len = BN_num_bytes(&bn);
if (len > sizeof(buf))
return false;

memset(buf, 0, sizeof(buf));
BN_bn2bin(&bn, buf + sizeof(buf) - len);
BN_free(&bn);
b58_sha256_impl = my_sha256;

size_t buflen = sizeof(buf);
b58tobin(buf, &buflen, base58, base58_len);
int r = b58check(buf, sizeof(buf), base58, base58_len);
*version = buf[0];

base58_get_checksum(csum, buf, 1 + sizeof(*rmd));
if (memcmp(csum, buf + 1 + sizeof(*rmd), sizeof(csum)) != 0)
return false;

memcpy(rmd, buf+1, sizeof(*rmd));
return true;
memcpy(rmd, buf + 1, sizeof(*rmd));
return r > 0;
}

bool bitcoin_from_base58(bool *test_net,
Expand DownExpand Up@@ -235,124 +99,60 @@ bool p2sh_from_base58(bool *test_net,
return true;
}

/* buf already contains version and ripemd160. Append checksum and encode */
char *base58_with_check(char dest[BASE58_ADDR_MAX_LEN],
u8 buf[1 + sizeof(struct ripemd160) + 4])
{
/* Append checksum */
base58_get_checksum(buf + 1 + sizeof(struct ripemd160),
buf, 1 + sizeof(struct ripemd160));

/* Now encode. */
return encode_base58(dest, BASE58_ADDR_MAX_LEN, buf,
1 + sizeof(struct ripemd160) + 4);
}

bool ripemd_from_base58(u8 *version,
struct ripemd160 *ripemd160,
const char *base58)
{
u8 buf[1 + sizeof(*ripemd160) + 4];
u8 csum[4];
BIGNUM bn;
size_t len;

/* Too long? Check here before doing arithmetic. */
if (strlen(base58) > BASE58_ADDR_MAX_LEN - 1)
return false;

BN_init(&bn);
/* Fails if it contains invalid characters. */
if (!raw_decode_base58(&bn, base58, strlen(base58)))
return false;

/* Too big? */
len = BN_num_bytes(&bn);
if (len > sizeof(buf)) {
BN_free(&bn);
return false;
}

/* Fill start with zeroes. */
memset(buf, 0, sizeof(buf) - len);
BN_bn2bin(&bn, buf + sizeof(buf) - len);
BN_free(&bn);

/* Check checksum is correct. */
base58_get_checksum(csum, buf, sizeof(buf));
if (memcmp(csum, buf + 1 + sizeof(*ripemd160), 4) != 0)
return false;

*version = buf[0];
memcpy(ripemd160, buf + 1, sizeof(*ripemd160));
return true;
return from_base58(version, ripemd160, base58, strlen(base58));
}

char *key_to_base58(const tal_t *ctx, bool test_net, const struct privkey *key)
{
u8 buf[1 + 32 + 1 + 4];
char out[BASE58_KEY_MAX_LEN + 2], *p;

buf[0] = test_net ? 239 : 128;
memcpy(buf + 1, key->secret, sizeof(key->secret));
u8 buf[32 + 1];
char out[BASE58_KEY_MAX_LEN + 2];
u8 version = test_net ? 239 : 128;
size_t outlen = sizeof(out);

memcpy(buf, key->secret, sizeof(key->secret));
/* Mark this as a compressed key. */
buf[1 + 32] = 1;
buf[32] = 1;

/* Append checksum */
base58_get_checksum(buf + 1 + 32 + 1, buf, 1 + 32 + 1);

p = encode_base58(out, BASE58_KEY_MAX_LEN, buf, sizeof(buf));
return tal_strdup(ctx, p);
b58check_enc(out, &outlen, version, buf, sizeof(buf));
return tal_strdup(ctx, out);
}

bool key_from_base58(secp256k1_context *secpctx,
const char *base58, size_t base58_len,
bool *test_net, struct privkey *priv, struct pubkey *key)
{
// 1 byte version, 32 byte private key, 1 byte compressed, 4 byte checksum
u8 keybuf[1 + 32 + 1 + 4];
u8 csum[4];
BIGNUM bn;
size_t keylen;

BN_init(&bn);
if (!raw_decode_base58(&bn, base58, base58_len))
return false;

keylen = BN_num_bytes(&bn);
if (keylen != 1 + 32 + 1 + 4)
goto fail_free_bn;
BN_bn2bin(&bn, keybuf);
size_t keybuflen = sizeof(keybuf);

base58_get_checksum(csum, keybuf, keylen - sizeof(csum));
if (memcmp(csum, keybuf + keylen - sizeof(csum), sizeof(csum)) != 0)
goto fail_free_bn;
b58tobin(keybuf, &keybuflen, base58, base58_len);
if (b58check(keybuf, sizeof(keybuf), base58, base58_len) < 0)
return false;

/* Byte after key should be 1 to represent a compressed key. */
if (keybuf[1 + 32] != 1)
goto fail_free_bn;
return false;

if (keybuf[0] == 128)
*test_net = false;
else if (keybuf[0] == 239)
*test_net = true;
else
goto fail_free_bn;
return false;

/* Copy out secret. */
memcpy(priv->secret, keybuf + 1, sizeof(priv->secret));

if (!secp256k1_ec_seckey_verify(secpctx, priv->secret))
goto fail_free_bn;
return false;

/* Get public key, too. */
if (!pubkey_from_privkey(secpctx, priv, key))
goto fail_free_bn;
return false;

BN_free(&bn);
return true;

fail_free_bn:
BN_free(&bn);
return false;
}
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Makefile
Original file line numberDiff line numberDiff line change
Expand Up@@ -177,7 +177,7 @@ CWARNFLAGS := -Werror -Wall -Wundef -Wmissing-prototypes -Wmissing-declarations
CDEBUGFLAGS := -g -fstack-protector
CFLAGS := $(CWARNFLAGS) $(CDEBUGFLAGS) -I $(CCANDIR) -I secp256k1/include/ -I . $(FEATURES)

LDLIBS := -lcrypto -lprotobuf-c -lgmp -lsodium
LDLIBS := -lprotobuf-c -lgmp -lsodium -lbase58
$(PROGRAMS): CFLAGS+=-I.

default: $(PROGRAMS) daemon-all
Expand Down
270 changes: 35 additions & 235 deletions bitcoin/base58.c
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,149 +11,28 @@
#include <assert.h>
#include <ccan/build_assert/build_assert.h>
#include <ccan/tal/str/str.h>
#include <openssl/bn.h>
#include <secp256k1.h>
#include <string.h>
#include <libbase58.h>

static const char enc_16[] = "0123456789abcdef";
static const char enc_58[] =
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

static char encode_char(unsigned long val, const char *enc)
{
assert(val < strlen(enc));
return enc[val];
}

static int decode_char(char c, const char *enc)
{
const char *pos = strchr(enc, c);
if (!pos)
return -1;
return pos - enc;
}

/*
* Encode a byte sequence as a base58-encoded string. This is a bit
* weird: returns pointer into buf (or NULL if wouldn't fit).
*/
static char *encode_base58(char *buf, size_t buflen,
const u8 *data, size_t data_len)
{
char *p;
BIGNUM bn;

/* Convert to a bignum. */
BN_init(&bn);
BN_bin2bn(data, data_len, &bn);

/* Add NUL terminator */
if (!buflen) {
p = NULL;
goto out;
}
p = buf + buflen;
*(--p) = '\0';

/* Fill from the back, using a series of divides. */
while (!BN_is_zero(&bn)) {
int rem = BN_div_word(&bn, 58);
if (--p < buf) {
p = NULL;
goto out;
}
*p = encode_char(rem, enc_58);
}

/* Now, this is really weird. We pad with zeroes, but not at
* base 58, but in terms of zero bytes. This means that some
* encodings are shorter than others! */
while (data_len && *data == '\0') {
if (--p < buf) {
p = NULL;
goto out;
}
*p = encode_char(0, enc_58);
data_len--;
data++;
}

out:
BN_free(&bn);
return p;
}

/*
* Decode a base_n-encoded string into a byte sequence.
*/
bool raw_decode_base_n(BIGNUM *bn, const char *src, size_t len, int base)
static bool my_sha256(void *digest, const void *data, size_t datasz)
{
const char *enc;

BN_zero(bn);

assert(base == 16 || base == 58);
switch (base) {
case 16:
enc = enc_16;
break;
case 58:
enc = enc_58;
break;
}

while (len) {
char current = *src;

if (base == 16)
current = tolower(current); /* TODO: Not in ccan. */
int val = decode_char(current, enc);
if (val < 0) {
BN_free(bn);
return false;
}
BN_mul_word(bn, base);
BN_add_word(bn, val);
src++;
len--;
}

sha256(digest, data, datasz);
return true;
}

/*
* Decode a base58-encoded string into a byte sequence.
*/
bool raw_decode_base58(BIGNUM *bn, const char *src, size_t len)
{
return raw_decode_base_n(bn, src, len, 58);
}

void base58_get_checksum(u8 csum[4], const u8 buf[], size_t buflen)
{
struct sha256_double sha_result;

/* Form checksum, using double SHA2 (as per bitcoin standard) */
sha256_double(&sha_result, buf, buflen);

/* Use first four bytes of that as the checksum. */
memcpy(csum, sha_result.sha.u.u8, 4);
}

static char *to_base58(const tal_t *ctx, u8 version,
const struct ripemd160 *rmd)
{
u8 buf[1 + sizeof(*rmd) + 4];
char out[BASE58_ADDR_MAX_LEN + 2], *p;

buf[0] = version;
memcpy(buf+1, rmd, sizeof(*rmd));

/* Append checksum */
base58_get_checksum(buf + 1 + sizeof(*rmd), buf, 1 + sizeof(*rmd));
char out[BASE58_ADDR_MAX_LEN + 1];
size_t outlen = sizeof(out);

p = encode_base58(out, BASE58_ADDR_MAX_LEN, buf, sizeof(buf));
return tal_strdup(ctx, p);
b58_sha256_impl = my_sha256;
if (!b58check_enc(out, &outlen, version, rmd, sizeof(*rmd))) {
return NULL;
}else{
return tal_strdup(ctx, out);
}
}

char *bitcoin_to_base58(const tal_t *ctx, bool test_net,
Expand All@@ -173,30 +52,15 @@ static bool from_base58(u8 *version,
const char *base58, size_t base58_len)
{
u8 buf[1 + sizeof(*rmd) + 4];
BIGNUM bn;
size_t len;
u8 csum[4];

BN_init(&bn);
if (!raw_decode_base58(&bn, base58, base58_len))
return false;

len = BN_num_bytes(&bn);
if (len > sizeof(buf))
return false;

memset(buf, 0, sizeof(buf));
BN_bn2bin(&bn, buf + sizeof(buf) - len);
BN_free(&bn);
b58_sha256_impl = my_sha256;

size_t buflen = sizeof(buf);
b58tobin(buf, &buflen, base58, base58_len);
int r = b58check(buf, sizeof(buf), base58, base58_len);
*version = buf[0];

base58_get_checksum(csum, buf, 1 + sizeof(*rmd));
if (memcmp(csum, buf + 1 + sizeof(*rmd), sizeof(csum)) != 0)
return false;

memcpy(rmd, buf+1, sizeof(*rmd));
return true;
memcpy(rmd, buf + 1, sizeof(*rmd));
return r > 0;
}

bool bitcoin_from_base58(bool *test_net,
Expand DownExpand Up@@ -235,124 +99,60 @@ bool p2sh_from_base58(bool *test_net,
return true;
}

/* buf already contains version and ripemd160. Append checksum and encode */
char *base58_with_check(char dest[BASE58_ADDR_MAX_LEN],
u8 buf[1 + sizeof(struct ripemd160) + 4])
{
/* Append checksum */
base58_get_checksum(buf + 1 + sizeof(struct ripemd160),
buf, 1 + sizeof(struct ripemd160));

/* Now encode. */
return encode_base58(dest, BASE58_ADDR_MAX_LEN, buf,
1 + sizeof(struct ripemd160) + 4);
}

bool ripemd_from_base58(u8 *version,
struct ripemd160 *ripemd160,
const char *base58)
{
u8 buf[1 + sizeof(*ripemd160) + 4];
u8 csum[4];
BIGNUM bn;
size_t len;

/* Too long? Check here before doing arithmetic. */
if (strlen(base58) > BASE58_ADDR_MAX_LEN - 1)
return false;

BN_init(&bn);
/* Fails if it contains invalid characters. */
if (!raw_decode_base58(&bn, base58, strlen(base58)))
return false;

/* Too big? */
len = BN_num_bytes(&bn);
if (len > sizeof(buf)) {
BN_free(&bn);
return false;
}

/* Fill start with zeroes. */
memset(buf, 0, sizeof(buf) - len);
BN_bn2bin(&bn, buf + sizeof(buf) - len);
BN_free(&bn);

/* Check checksum is correct. */
base58_get_checksum(csum, buf, sizeof(buf));
if (memcmp(csum, buf + 1 + sizeof(*ripemd160), 4) != 0)
return false;

*version = buf[0];
memcpy(ripemd160, buf + 1, sizeof(*ripemd160));
return true;
return from_base58(version, ripemd160, base58, strlen(base58));
}

char *key_to_base58(const tal_t *ctx, bool test_net, const struct privkey *key)
{
u8 buf[1 + 32 + 1 + 4];
char out[BASE58_KEY_MAX_LEN + 2], *p;

buf[0] = test_net ? 239 : 128;
memcpy(buf + 1, key->secret, sizeof(key->secret));
u8 buf[32 + 1];
char out[BASE58_KEY_MAX_LEN + 2];
u8 version = test_net ? 239 : 128;
size_t outlen = sizeof(out);

memcpy(buf, key->secret, sizeof(key->secret));
/* Mark this as a compressed key. */
buf[1 + 32] = 1;
buf[32] = 1;

/* Append checksum */
base58_get_checksum(buf + 1 + 32 + 1, buf, 1 + 32 + 1);

p = encode_base58(out, BASE58_KEY_MAX_LEN, buf, sizeof(buf));
return tal_strdup(ctx, p);
b58check_enc(out, &outlen, version, buf, sizeof(buf));
return tal_strdup(ctx, out);
}

bool key_from_base58(secp256k1_context *secpctx,
const char *base58, size_t base58_len,
bool *test_net, struct privkey *priv, struct pubkey *key)
{
// 1 byte version, 32 byte private key, 1 byte compressed, 4 byte checksum
u8 keybuf[1 + 32 + 1 + 4];
u8 csum[4];
BIGNUM bn;
size_t keylen;

BN_init(&bn);
if (!raw_decode_base58(&bn, base58, base58_len))
return false;

keylen = BN_num_bytes(&bn);
if (keylen != 1 + 32 + 1 + 4)
goto fail_free_bn;
BN_bn2bin(&bn, keybuf);
size_t keybuflen = sizeof(keybuf);

base58_get_checksum(csum, keybuf, keylen - sizeof(csum));
if (memcmp(csum, keybuf + keylen - sizeof(csum), sizeof(csum)) != 0)
goto fail_free_bn;
b58tobin(keybuf, &keybuflen, base58, base58_len);
if (b58check(keybuf, sizeof(keybuf), base58, base58_len) < 0)
return false;

/* Byte after key should be 1 to represent a compressed key. */
if (keybuf[1 + 32] != 1)
goto fail_free_bn;
return false;

if (keybuf[0] == 128)
*test_net = false;
else if (keybuf[0] == 239)
*test_net = true;
else
goto fail_free_bn;
return false;

/* Copy out secret. */
memcpy(priv->secret, keybuf + 1, sizeof(priv->secret));

if (!secp256k1_ec_seckey_verify(secpctx, priv->secret))
goto fail_free_bn;
return false;

/* Get public key, too. */
if (!pubkey_from_privkey(secpctx, priv, key))
goto fail_free_bn;
return false;

BN_free(&bn);
return true;

fail_free_bn:
BN_free(&bn);
return false;
}
Loading