openzeppelin-contracts icon indicating copy to clipboard operation
openzeppelin-contracts copied to clipboard

Add new Bytes utility to decode `bytes memory`

Open chiro-hiro opened this issue 2 years ago • 4 comments

🧐 Motivation Decode data which was packed by abi.encodePacked() into a bytes memory

https://github.com/ethereum/solidity/issues/6919

📝 Details

  • Convert bytes memory to bytes32[]
  • Read sub bytes memory of input bytes memeory
  • Read uint256, uint160, uint128, uint64, uint32, uint16 of input bytes memory at a given offset.

Please check #3998 for the detail, the pr is in WIP. I will complete the rest after this discussion is resolved.

chiro-hiro avatar Jan 25 '23 12:01 chiro-hiro

How will this work, given that the encoded type is ambigious?

Are you going to create a library?

uint256 offset = 0;
(uint256  myVar,  uint256 newOffset) =  decodePackedUint256(bytes)

GrantHoffman avatar Jan 25 '23 22:01 GrantHoffman

Here is an example of Bytes.sol, my implementation could be found in #3998

pragma solidity ^0.8.0;
import "./Bytes.sol";

contract EncodingTx {
    using Bytes for bytes;

    function encodeTransaction(address from, address to, uint256 value, uint64 nonce) 
    public pure returns (bytes memory) {
        return abi.encodePacked(from, to, nonce, value);
    }
    
    function decodeTransaction(bytes memory input)
    external pure returns(address from, address to, uint256 value, uint64 nonce){
        uint256 offset;
        uint160 uintAddress;
        (uintAddress, offset) =  input.readUint160(0);
        from = address(uintAddress);
        (uintAddress, offset) =  input.readUint160(offset);
        to = address(uintAddress);
        (nonce, offset) =  input.readUint64(offset);
        (value, offset) =  input.readUint256(offset);
    }
}

chiro-hiro avatar Jan 26 '23 14:01 chiro-hiro

There already exist quite a few Bytes libraries.

The first one that comes to mind is this one.

There is also the RLP reader that is used by polygon's FX Portal.

I'm not sure we want to start yet another library for bytes manipulation. If we do, we'll need serious reasons to do so, and that start by studying the existing alternative. Unless there is something we can do better, I'm not sure why we should dedicate ressources to this.

Amxx avatar Jan 26 '23 15:01 Amxx

This library provide the minimal utility to unpack the data which was packed by abi.encodePacked(). I'm preparing a PR in #3998.

chiro-hiro avatar Feb 21 '23 07:02 chiro-hiro