Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
52 commits
Select commit Hold shift + click to select a range
5a400eb
Add Bytes.splice, an inplace variant of Buffer.slice
Amxx Jun 10, 2025
65292d5
Add Base58 library
Amxx Jun 20, 2025
99a1835
docs
Amxx Jun 20, 2025
bddf4f6
Merge branch 'feature/Bytes-splice' into feature/base58
Amxx Jun 21, 2025
88c03e7
Add Bytes.countConsecutive and Bytes.countLeading
Amxx Jun 21, 2025
a3c4667
fix
Amxx Jun 21, 2025
41b586b
efficient decoding
Amxx Jun 21, 2025
c6d6bdd
coverage
Amxx Jun 21, 2025
48bf13b
Update thirty-pugs-pick.md
Amxx Jun 21, 2025
eebd51e
docs
Amxx Jun 21, 2025
296a87e
pragma
Amxx Jun 21, 2025
8c94acc
pragma
Amxx Jun 21, 2025
d09ebfa
coverage
Amxx Jun 21, 2025
a25bd11
rewrite _encode in assembly
Amxx Jun 22, 2025
a4ce8c8
more inline documentation
Amxx Jun 22, 2025
7474f2a
test vectors
Amxx Jun 22, 2025
bef2e4f
document
Amxx Jun 22, 2025
ce1c5ad
remove auxiliary utils
Amxx Jun 22, 2025
c33e933
mload is actually cheaper than jump
Amxx Jun 23, 2025
855a1c6
up
Amxx Jun 23, 2025
ec641c7
Update contracts/utils/Base58.sol
Amxx Jun 25, 2025
7429bcc
up
Amxx Jun 26, 2025
45edb76
do base58 arithmetics in chunks of 248 bits
Amxx Jun 26, 2025
20f3611
update
Amxx Jun 26, 2025
8e60a99
codespell
Amxx Jun 26, 2025
dd8e895
decode assembly
Amxx Jun 26, 2025
45f04b4
char valdity filter
Amxx Jun 26, 2025
da84743
slither
Amxx Jun 26, 2025
c80f693
slither
Amxx Jun 27, 2025
f7ac27d
fix custom error name + testing
Amxx Aug 22, 2025
2696cd8
Apply suggestions from code review
Amxx Aug 27, 2025
1736f38
optimize zero limbs accounting
Amxx Aug 27, 2025
8652d20
Update contracts/utils/Base58.sol
Amxx Aug 27, 2025
8098fb2
Update test/utils/Base58.t.sol
Amxx Aug 27, 2025
d0ece81
Apply suggestions from code review
Amxx Sep 4, 2025
3974f6d
Merge branch 'master' into feature/base58
Amxx Sep 4, 2025
59b2866
fix compilation and update custom error name
Amxx Sep 4, 2025
66ef584
minify change by removing unecessary feature in Bytes.sol
Amxx Sep 4, 2025
8b1ae97
Apply suggestions from code review
Amxx Sep 12, 2025
bb3aaf3
Update contracts/utils/Base58.sol
Amxx Sep 12, 2025
ac75789
clarify
Amxx Sep 15, 2025
930a03f
update estimation to always overestimate
Amxx Sep 15, 2025
c3a4e76
closer approximation
Amxx Sep 15, 2025
f372c20
Update Base58.sol
Amxx Sep 16, 2025
377ec53
Enhance comments
ernestognw Sep 25, 2025
aeaa73c
fraction values
Amxx Sep 25, 2025
107328f
Update contracts/utils/Base58.sol
ernestognw Sep 25, 2025
e3268cf
Update contracts/utils/Base58.sol
ernestognw Sep 25, 2025
fe288ea
Enhance _decode comments
ernestognw Sep 25, 2025
8e32c79
Add custom error changes section in changelog
ernestognw Sep 25, 2025
0c488da
Apply suggestions from code review
Amxx Sep 26, 2025
23221e1
Update CHANGELOG.md
ernestognw Sep 26, 2025
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