Skip to content
This repository has been archived by the owner on Aug 1, 2023. It is now read-only.

Add base58 #150

Merged
merged 1 commit into from
Sep 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
68 changes: 68 additions & 0 deletions io/src/main/java/org/apache/tuweni/io/Base58.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE
* file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file
* to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.apache.tuweni.io;

import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Objects.requireNonNull;

import org.apache.tuweni.bytes.Bytes;

/**
* Utility methods for encoding and decoding base58 strings.
*/
public final class Base58 {
private Base58() {}

/**
* Encode a byte array to a base58 encoded string.
*
* @param bytes The bytes to encode.
* @return A base58 encoded string.
*/
public static String encodeBytes(byte[] bytes) {
requireNonNull(bytes);
return new String(Base58Codec.encode(bytes), UTF_8);
}

/**
* Encode bytes to a base58 encoded string.
*
* @param bytes The bytes to encode.
* @return A base58 encoded string.
*/
public static String encode(Bytes bytes) {
requireNonNull(bytes);
return encodeBytes(bytes.toArrayUnsafe());
}

/**
* Decode a base58 encoded string to a byte array.
*
* @param b58 The base58 encoded string.
* @return A byte array.
*/
public static byte[] decodeBytes(String b58) {
requireNonNull(b58);
return Base58Codec.decode(b58);
}

/**
* Decode a base58 encoded string to bytes.
*
* @param b58 The base58 encoded string.
* @return The decoded bytes.
*/
public static Bytes decode(String b58) {
return Bytes.wrap(decodeBytes(b58));
}
}
104 changes: 104 additions & 0 deletions io/src/main/java/org/apache/tuweni/io/Base58Codec.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE
* file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file
* to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.apache.tuweni.io;

import java.util.Arrays;

class Base58Codec {

// @formatter:off
private static final byte[] ENCODE_TABLE = {
'1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z'
};

private static final byte[] DECODE_TABLE = {
// 0 1 2 3 4 5 6 7 8 9 A B C D E F
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 00-0f
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10-1f
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 20-2f + - /
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, -1, -1, -1, -1, -1, -1, // 30-3f 0-9
-1, 9, 10, 11, 12, 13, 14, 15, 16, -1, 17, 18, 19, 20, 21, -1, // 40-4f A-O
22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, -1, -1, // 50-5f P-Z _
-1, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, -1, 44, 45, 46, // 60-6f a-o
47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57 // 70-7a p-z
};
// @formatter:on

static byte[] encode(byte[] decoded) {
byte[] input = Arrays.copyOf(decoded, decoded.length);
byte[] encoded = new byte[input.length * 2];
int inputStart = 0;
int outputStart = encoded.length;
int zeros = 0;

while (inputStart < input.length) {
if (input[inputStart] == 0 && outputStart == encoded.length) {
zeros++;
inputStart++;
continue;
}
int remainder = 0;
for (int i = 0; i < input.length; i++) {
int digit = (int) input[i] & 0xFF;
int temp = remainder * 256 + digit;
input[i] = (byte) (temp / 58);
remainder = temp % 58;
}
encoded[--outputStart] = ENCODE_TABLE[remainder];
if (input[inputStart] == 0) {
inputStart++;
}
}
Arrays.fill(encoded, outputStart - zeros, outputStart, ENCODE_TABLE[0]);
return Arrays.copyOfRange(encoded, outputStart - zeros, encoded.length);
}

static byte[] decode(String encoded) {
byte[] input = new byte[encoded.length()];
byte[] decoded = new byte[input.length];
for (int i = 0; i < input.length; i++) {
input[i] = DECODE_TABLE[encoded.charAt(i)];
if (input[i] == -1) {
throw new IllegalArgumentException("Invalid character " + encoded.charAt(i));
}
}
int inputStart = 0;
int outputStart = input.length;
int zeros = 0;

while (inputStart < input.length) {
if (input[inputStart] == 0 && outputStart == input.length) {
zeros++;
inputStart++;
continue;
}
int remainder = 0;
for (int i = 0; i < input.length; i++) {
int digit = (int) input[i] & 0xFF;
int temp = remainder * 58 + digit;
input[i] = (byte) (temp / 256);
remainder = temp % 256;
}
decoded[--outputStart] = (byte) remainder;
if (input[inputStart] == 0) {
inputStart++;
}
}
Arrays.fill(decoded, outputStart - zeros, outputStart, (byte) 0);
return Arrays.copyOfRange(decoded, outputStart - zeros, decoded.length);
}
}
81 changes: 81 additions & 0 deletions io/src/test/java/org/apache/tuweni/io/Base58Test.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE
* file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file
* to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.apache.tuweni.io;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import org.apache.tuweni.bytes.Bytes;

import java.nio.charset.StandardCharsets;

import org.junit.jupiter.api.Test;

class Base58Test {

@Test
void testHelloWorld() {
String result = Base58.encode(Bytes.wrap("Hello World!".getBytes(StandardCharsets.US_ASCII)));
assertEquals("2NEpo7TZRRrLZSi2U", result);
}

@Test
void testQuickBrownFox() {
String result =
Base58.encode(Bytes.wrap("The quick brown fox jumps over the lazy dog.".getBytes(StandardCharsets.US_ASCII)));
assertEquals("USm3fpXnKG5EUBx2ndxBDMPVciP5hGey2Jh4NDv6gmeo1LkMeiKrLJUUBk6Z", result);
}

@Test
void testHex() {
Bytes value = Bytes.fromHexString("1220BA8632EF1A07986B171B3C8FAF0F79B3EE01B6C30BBE15A13261AD6CB0D02E3A");
assertEquals("QmatmE9msSfkKxoffpHwNLNKgwZG8eT9Bud6YoPab52vpy", Base58.encode(value));
}

@Test
void testHexDecode() {
Bytes value = Bytes.fromHexString("00000000");
assertEquals(value, Bytes.wrap(Base58.decode(Base58.encode(value))));
}

@Test
void testHexDecodeOne() {
Bytes value = Bytes.fromHexString("01");
assertEquals(value, Bytes.wrap(Base58.decode(Base58.encode(value))));
}

@Test
void testHexDecode256() {
Bytes value = Bytes.fromHexString("0100");
assertEquals(value, Bytes.wrap(Base58.decode(Base58.encode(value))));
}

@Test
void testZeros() {
Bytes value = Bytes.fromHexString("000000");
assertEquals("111", Base58.encode(value));
}

@Test
void testZerosThenOne() {
Bytes value = Bytes.fromHexString("00000001");
assertEquals("1112", Base58.encode(value));
}

@Test
void testBadCharacter() {
assertThrows(IllegalArgumentException.class, () -> {
Base58.decode("%^");
});
}
}