Skip to content

Add Base58 library #5762

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 29 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
5 changes: 5 additions & 0 deletions .changeset/loose-lamps-bake.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'openzeppelin-solidity': minor
---

`Base58`: Add a library for encoding and decoding bytes buffers into base58 strings.
1 change: 1 addition & 0 deletions contracts/mocks/Stateless.sol
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ pragma solidity ^0.8.26;
import {Address} from "../utils/Address.sol";
import {Arrays} from "../utils/Arrays.sol";
import {AuthorityUtils} from "../access/manager/AuthorityUtils.sol";
import {Base58} from "../utils/Base58.sol";
import {Base64} from "../utils/Base64.sol";
import {BitMaps} from "../utils/structs/BitMaps.sol";
import {Blockhash} from "../utils/Blockhash.sol";
Expand Down
135 changes: 135 additions & 0 deletions contracts/utils/Base58.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.24;

import {Bytes} from "./Bytes.sol";

/**
* @dev Provides a set of functions to operate with Base58 strings.
*
* Based on the original https://github.com/storyicon/base58-solidity/commit/807428e5174e61867e4c606bdb26cba58a8c5cb1[implementation of storyicon] (MIT).
*/
library Base58 {
using Bytes for bytes;

string internal constant _TABLE = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

function encode(bytes memory data) internal pure returns (string memory) {
return string(_encode(data));
}

function decode(string memory data) internal pure returns (bytes memory) {
return _decode(bytes(data));
}

function _encode(bytes memory data) private pure returns (bytes memory) {
unchecked {
uint256 dataCLZ = _countLeading(data, 0x00);
uint256 slotLength = dataCLZ + ((data.length - dataCLZ) * 8351) / 6115 + 1;

bytes memory slot = new bytes(slotLength);
uint256 end = slotLength;
for (uint256 i = 0; i < data.length; i++) {
uint256 ptr = slotLength;
for (uint256 carry = _mload8i(data, i); ptr > end || carry != 0; --ptr) {
carry += 256 * _mload8i(slot, ptr - 1);
_mstore8i(slot, ptr - 1, uint8(carry % 58));
carry /= 58;
}
end = ptr;
}

uint256 slotCLZ = _countLeading(slot, 0x00);
uint256 resultLength = slotLength + dataCLZ - slotCLZ;

bytes memory cache = bytes(_TABLE);
for (uint256 i = 0; i < resultLength; ++i) {
uint256 idx = _mload8i(slot, i + slotCLZ - dataCLZ);
bytes1 c = _mload8(cache, idx);
_mstore8(slot, i, c);
}

assembly ("memory-safe") {
mstore(slot, resultLength)
}

return slot;
}
}

function _decode(bytes memory data) private pure returns (bytes memory) {
unchecked {
uint256 b58Length = data.length;

uint256 size = 2 * ((b58Length * 8351) / 6115 + 1);
bytes memory binu = new bytes(size);

bytes memory cache = bytes(_TABLE);
uint32[] memory outi = new uint32[]((b58Length + 3) / 4);
for (uint256 i = 0; i < data.length; i++) {
bytes1 r = _mload8(data, i);
uint256 c = cache.indexOf(r); // can we avoid the loop here ?
require(c != type(uint256).max, "invalid base58 digit");
for (uint256 k = outi.length; k > 0; --k) {
uint256 t = uint64(outi[k - 1]) * 58 + c;
c = t >> 32;
outi[k - 1] = uint32(t & 0xffffffff);
}
}

uint256 ptr = 0;
uint256 mask = ((b58Length - 1) % 4) + 1;
for (uint256 j = 0; j < outi.length; ++j) {
while (mask > 0) {
--mask;
_mstore8(binu, ptr, bytes1(uint8(outi[j] >> (8 * mask))));
ptr++;
}
mask = 4;
}

uint256 dataCLZ = _countLeading(data, 0x31);
for (uint256 msb = dataCLZ; msb < binu.length; ++msb) {
if (_mload8(binu, msb) != 0x00) {
return binu.slice(msb - dataCLZ, ptr);
}
}
return binu.slice(0, ptr);
}
}

function _mload8(bytes memory buffer, uint256 offset) private pure returns (bytes1 value) {
// This is not memory safe in the general case, but all calls to this private function are within bounds.
assembly ("memory-safe") {
value := mload(add(add(buffer, 0x20), offset))
}
}

function _mload8i(bytes memory buffer, uint256 offset) private pure returns (uint8 value) {
// This is not memory safe in the general case, but all calls to this private function are within bounds.
assembly ("memory-safe") {
value := shr(248, mload(add(add(buffer, 0x20), offset)))
}
}

function _mstore8(bytes memory buffer, uint256 offset, bytes1 value) private pure {
// This is not memory safe in the general case, but all calls to this private function are within bounds.
assembly ("memory-safe") {
mstore8(add(add(buffer, 0x20), offset), shr(248, value))
}
}

function _mstore8i(bytes memory buffer, uint256 offset, uint8 value) private pure {
// This is not memory safe in the general case, but all calls to this private function are within bounds.
assembly ("memory-safe") {
mstore8(add(add(buffer, 0x20), offset), value)
}
}

function _countLeading(bytes memory buffer, bytes1 el) private pure returns (uint256) {
uint256 length = buffer.length;
uint256 i = 0;
while (i < length && _mload8(buffer, i) == el) ++i;
return i;
}
}
3 changes: 3 additions & 0 deletions contracts/utils/README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ Miscellaneous contracts and libraries containing utility functions you can use t
* {Create2}: Wrapper around the https://blog.openzeppelin.com/getting-the-most-out-of-create2/[`CREATE2` EVM opcode] for safe use without having to deal with low-level assembly.
* {Address}: Collection of functions for overloading Solidity's https://docs.soliditylang.org/en/latest/types.html#address[`address`] type.
* {Arrays}: Collection of functions that operate on https://docs.soliditylang.org/en/latest/types.html#arrays[`arrays`].
* {Base58}: On-chain base58 encoding and decoding.
* {Base64}: On-chain base64 and base64URL encoding according to https://datatracker.ietf.org/doc/html/rfc4648[RFC-4648].
* {Bytes}: Common operations on bytes objects.
* {Calldata}: Helpers for manipulating calldata.
Expand Down Expand Up @@ -105,6 +106,8 @@ Ethereum contracts have no native concept of an interface, so applications must

{{Arrays}}

{{Base58}}

{{Base64}}

{{Bytes}}
Expand Down
16 changes: 16 additions & 0 deletions test/utils/Base58.t.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import {Test} from "forge-std/Test.sol";
import {Base58} from "@openzeppelin/contracts/utils/Base58.sol";

contract Base58Test is Test {
function testEncodeDecodeEmpty() external pure {
assertEq(Base58.decode(Base58.encode("")), "");
}

function testEncodeDecode(bytes memory input) external pure {
assertEq(Base58.decode(Base58.encode(input)), input);
}
}
26 changes: 26 additions & 0 deletions test/utils/Base58.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
const { ethers } = require('hardhat');
const { expect } = require('chai');
const { loadFixture } = require('@nomicfoundation/hardhat-network-helpers');

async function fixture() {
const mock = await ethers.deployContract('$Base58');
return { mock };
}

describe('Base58', function () {
beforeEach(async function () {
Object.assign(this, await loadFixture(fixture));
});

describe('base58', function () {
for (const length of [0, 1, 2, 3, 4, 32, 42, 128, 384]) // 512 runs out of gas
it(`Encode/Decode buffer of length ${length}`, async function () {
const buffer = ethers.randomBytes(length);
const hex = ethers.hexlify(buffer);
const b58 = ethers.encodeBase58(buffer);

expect(await this.mock.$encode(hex)).to.equal(b58);
expect(await this.mock.$decode(b58)).to.equal(hex);
});
});
});
2 changes: 1 addition & 1 deletion test/utils/Base64.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ async function fixture() {
return { mock };
}

describe('Strings', function () {
describe('Base64', function () {
beforeEach(async function () {
Object.assign(this, await loadFixture(fixture));
});
Expand Down
Loading