1

I wanna compute sha256 in Solidity Assembly for hash of getting bytes slice.

k06a
  • 3,016
  • 2
  • 21
  • 35

1 Answers1

1

Sha256 is one of a few precompiled smart contracts:

function subSha256(bytes memory data, uint256 offset, uint256 length) public view returns(bytes32) {
    bytes32[1] memory result;
    assembly {
        pop(staticcall(gas, 0x02, add(add(data, 32), offset), length, result, 32))
    }
    return result[0];
}
k06a
  • 3,016
  • 2
  • 21
  • 35
  • I'm pretty sure that in solc 0.5.x onward, you can simply use staticcall at the Solidity level, and get (bool success, bytes memory result) returned to you. – goodvibration May 26 '20 at 16:54
  • @goodvibration core feature of this code is getting hash for a slice of an array without copying it into separate bytes array. – k06a May 26 '20 at 17:48