3

In my solidity game project, I am using this:

if (king == keccak256(abi.encodePacked(player)){
   //continue as king
} else{
  // not king
}

Where player data type is bytes and king is a player address. Does this look good or could it be tricked if player is controlled by user input? I think keccak256 would prevent it, wouldn't it?

4
  • 1
    king is type address? If so, the equality check is weird... Also note that keccak256(abi.encodePacked(player)) will always return the same result for the same playervalue. If the user can control the player value directly, the equality can be controlled too. In general though, abi.encodePacked is perfectly well behaved and can be used in production systems. Commented Oct 27, 2018 at 22:19
  • @ShawnTabrizi, king is of type byte32 . Hm, but let's say even if user knows the value of king even tho it is private variable. Then, still they cannot control a player value in a way that keccak256 returns as same as that. Or do they?
    – Adshead
    Commented Oct 27, 2018 at 22:46
  • 1
    I don't know. You have not provided any details about how the player value is set... Commented Oct 27, 2018 at 22:58
  • It's non-deterministic, It's like first2byteof_contractaddr+<24_digit_hex_seed>+remainingbyteof_contractaddr where contractaddr == generated contract address @ShawnTabrizi
    – Adshead
    Commented Oct 27, 2018 at 23:01

1 Answer 1

6

The function abi.encodePacked() only concatenates its input data in a bytes array in memory it doesn't transform the data in any way. So it is totaly safe to use in production code.

The function keccak256() is a cryptographic hash function. One of its properties is that is computationally hard to find a preimage, ie given king is in practice impossible to find the value of player.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.