Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/tired-ghosts-obey.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'openzeppelin-solidity': minor
---

`AbiDecode`: Added a library for decoding abi-encoded buffers in a way were decoding errors can be processed safely.
1 change: 1 addition & 0 deletions contracts/mocks/Stateless.sol
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ pragma solidity ^0.8.26;

// We keep these imports and a dummy contract just to we can run the test suite after transpilation.

import {AbiDecode} from "../utils/AbiDecode.sol";
import {Accumulators} from "../utils/structs/Accumulators.sol";
import {Address} from "../utils/Address.sol";
import {Arrays} from "../utils/Arrays.sol";
Expand Down
63 changes: 63 additions & 0 deletions contracts/utils/AbiDecode.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.24;

import {Calldata} from "./Calldata.sol";
import {Memory} from "./Memory.sol";

/// @dev Utilities to decode ABI-encoded data without reverting.
library AbiDecode {
using Memory for *;

/**
* @dev Attempts to decode a `bytes` value from a bytes input (in memory). Returns a boolean indicating success
* and a slice pointing to the decoded buffer. If decoding fails, returns an empty slice.
*/
function tryDecodeBytes(bytes memory input) internal pure returns (bool success, Memory.Slice output) {
return tryDecodeBytes(input.asSlice());
}

/**
* @dev Attempts to decode a `bytes` value from a Memory.Slice input. Returns a boolean indicating success and a
* slice pointing to the decoded buffer. If decoding fails, returns an empty slice.
*/
function tryDecodeBytes(Memory.Slice input) internal pure returns (bool success, Memory.Slice output) {
unchecked {
uint256 inputLength = input.length();
if (inputLength < 0x20) {
return (false, Memory.emptySlice());
}
uint256 offset = uint256(input.load(0));
if (inputLength - 0x20 < offset) {
return (false, Memory.emptySlice());
}
uint256 length = uint256(input.load(offset));
if (inputLength - 0x20 - offset < length) {
return (false, Memory.emptySlice());
}
return (true, input.slice(0x20 + offset, length));
}
}

/**
* @dev Attempts to decode a `bytes` value from a bytes input (in calldata). Returns a boolean indicating success
* and a slice pointing to the decoded buffer. If decoding fails, returns an empty slice.
*/
function tryDecodeBytesCalldata(bytes calldata input) internal pure returns (bool success, bytes calldata output) {
unchecked {
uint256 inputLength = input.length;
if (inputLength < 0x20) {
return (false, Calldata.emptyBytes());
}
uint256 offset = uint256(bytes32(input[0x00:0x20]));
if (inputLength - 0x20 < offset) {
return (false, Calldata.emptyBytes());
}
uint256 length = uint256(bytes32(input[offset:offset + 0x20]));
if (inputLength - 0x20 - offset < length) {
return (false, Calldata.emptyBytes());
}
return (true, input[0x20 + offset:0x20 + offset + length]);
}
}
}
5 changes: 5 additions & 0 deletions contracts/utils/Memory.sol
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,11 @@ library Memory {

type Slice is bytes32;

/// @dev Empty slice
function emptySlice() internal pure returns (Slice) {
return Slice.wrap(0);
}

/// @dev Get a slice representation of a bytes object in memory
function asSlice(bytes memory self) internal pure returns (Slice result) {
assembly ("memory-safe") {
Expand Down
1 change: 1 addition & 0 deletions contracts/utils/README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ Miscellaneous contracts and libraries containing utility functions you can use t
* {EnumerableSet}: Like {EnumerableMap}, but for https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets]. Can be used to store privileged accounts, issued IDs, etc.
* {Heap}: A library that implements a https://en.wikipedia.org/wiki/Binary_heap[binary heap] in storage.
* {MerkleTree}: A library with https://wikipedia.org/wiki/Merkle_Tree[Merkle Tree] data structures and helper functions.
* {AbiDecode}: Collection of function to decode abi-encoded buffers in a way were decoding errors can be processed safely.
* {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.
Expand Down
84 changes: 84 additions & 0 deletions test/utils/AbiDecode.t.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.24;

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

contract AbiDecodeTest is Test {
using AbiDecode for *;
using Memory for *;

function testDecode(bytes memory buffer) public pure {
(bool success, Memory.Slice output) = abi.encode(buffer).tryDecodeBytes();
assertTrue(success);
assertEq(output.toBytes(), buffer);
}

function testDecodeNoRevert(bytes memory buffer) public pure {
(bool success, Memory.Slice output) = buffer.tryDecodeBytes();
if (success) {
assertEq(output.toBytes(), abi.decode(buffer, (bytes)));
} else {
assertEq(output.toBytes(), new bytes(0));
}
}

function testDecodeCalldata(bytes memory buffer) public view {
(bool success, bytes memory output) = this.__tryDecodeBytesCalldata(abi.encode(buffer));
assertTrue(success);
assertEq(output, buffer);
}

function testDecodeCalldataNoRevert(bytes calldata buffer) public pure {
(bool success, bytes calldata output) = buffer.tryDecodeBytesCalldata();
if (success) {
assertEq(output, abi.decode(buffer, (bytes)));
} else {
assertEq(output, new bytes(0));
}
}

function testDecodeDegenerateCase() public view {
bytes memory buffer = abi.encodePacked(uint256(0x00)); // offset to itself + length = 0

(bool success, Memory.Slice output) = buffer.tryDecodeBytes();
assertTrue(success);
assertEq(output.toBytes(), new bytes(0));

(bool successCalldata, bytes memory outputCalldata) = this.__tryDecodeBytesCalldata(buffer);
assertTrue(successCalldata);
assertEq(outputCalldata, new bytes(0));
}

function testDecodeOutOfBoundOffset() public view {
bytes memory buffer = abi.encodePacked(uint256(0x20));

(bool success, Memory.Slice output) = buffer.tryDecodeBytes();
assertFalse(success);
assertEq(output.toBytes(), new bytes(0));

(bool successCalldata, bytes memory outputCalldata) = this.__tryDecodeBytesCalldata(buffer);
assertFalse(successCalldata);
assertEq(outputCalldata, new bytes(0));
}

function testDecodeLengthExceedsBuffer() public view {
bytes memory buffer = abi.encodePacked(uint256(0x20), uint256(0x40));

(bool success, Memory.Slice output) = buffer.tryDecodeBytes();
assertFalse(success);
assertEq(output.toBytes(), new bytes(0));

(bool successCalldata, bytes memory outputCalldata) = this.__tryDecodeBytesCalldata(buffer);
assertFalse(successCalldata);
assertEq(outputCalldata, new bytes(0));
}

function __tryDecodeBytesCalldata(
bytes calldata buffer
) external pure returns (bool success, bytes calldata output) {
return buffer.tryDecodeBytesCalldata();
}
}