commit 2723bd9700bad2a8dcecbbc7cba0828602d80183
parent 8c99d101c6376a35bd048c1b9565c0d07e3961e4
Author: NicholasFarrow <nicholas.w.farrow@gmail.com>
Date: Fri, 17 Jul 2020 02:01:03 +1000
Fix leading zeros
Diffstat:
2 files changed, 36 insertions(+), 12 deletions(-)
diff --git a/base58.h b/base58.h
@@ -0,0 +1,27 @@
+#include <stdio.h>
+
+typedef unsigned char byte;
+
+/* See https://en.wikipedia.org/wiki/Positional_notation#Base_conversion */
+char* base58(byte *s, int s_size, char *out, int out_size) {
+ static const char *base_chars = "123456789"
+ "ABCDEFGHJKLMNPQRSTUVWXYZ"
+ "abcdefghijkmnopqrstuvwxyz";
+
+ byte s_cp[s_size];
+ memcpy(s_cp, s, s_size);
+
+ int c, i, n;
+
+ out[n = out_size] = 0;
+ while (n--) {
+ for (c = i = 0; i < s_size; i++) {
+ c = c * 256 + s_cp[i];
+ s_cp[i] = c / 58;
+ c %= 58;
+ }
+ out[n] = base_chars[c];
+ }
+
+ return out;
+}
diff --git a/createPubKey.h b/createPubKey.h
@@ -18,9 +18,6 @@ void str_to_byte(const char *src, byte *dst, int n) {
while (n--) sscanf(src + n * 2, "%2hhx", dst + n);
}
-/*
-char *coin_encode(const char *x, const char *y, char *out) {
-*/
char *pubkey_to_P2PKH(const unsigned char *pubkey64, char *out) {
byte s[65];
byte rmd[5 + RIPEMD160_DIGEST_LENGTH];
@@ -37,15 +34,15 @@ char *pubkey_to_P2PKH(const unsigned char *pubkey64, char *out) {
base58(rmd, 25, out, 34);
- /* Count the number of 1s at the beginning of the address */
- int n = 0;
- for (n = 0; out[n] == '1'; n++);
+ /* Count the number of extra 1s at the beginning of the address */
+ int k;
+ for (k = 1; out[k] == '1'; k++);
- /* Do we need to remove any 1s? */
- if (n > 1) {
- memmove(out, out + (n-1), 34-(n-1));
-
- out[34-(n-1)] = '\0';
- }
+ /* Count the number of extra leading 0x00 bytes */
+ int n;
+ for (n = 1; rmd[n] == 0x00; n++);
+ /* Remove k-n leading 1's from the address */
+ memmove(out, out + (k-n), 34-(k-n));
+ out[34-(k-n)] = '\0';
}