q9f / eth.rb

a straightforward library to build, sign, and broadcast ethereum transactions anywhere you can run ruby.
https://q9f.github.io/eth.rb
Apache License 2.0
200 stars 86 forks source link

Personal signatures differ from metamask signatures #231

Closed yelodia closed 1 year ago

yelodia commented 1 year ago

Hi. Is it possible to make a personal signature with multiple parameters like in web3 library (not typed_data sign)

hash1 = Web3.utils.soliditySha3({t: 'string', v: 'test'}, {t: 'uint256', v: 60});
const signature = await ethereum.request({ method: 'personal_sign', params: [ message, account ] });
q9f commented 1 year ago

Web3.utils.solditySha3 implements packed ABI encoding which is not supported by the ruby gem, see #103

You can use normal ABI encoding though:

encoded = Eth::Abi.encode(["string", "uint256"], ["test", 60])
# => "\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000@\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000<\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0004test\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000"
hashed = Eth::Util.keccak256 encoded
# => "\xF0[\x8D,|f\xF3\x93}\xDF\xDAp\x16=\xF3oPn\xC9I*\xD8\xC6\x99\xF1\x14\xC5\xF2Jp#\xB0"
account = Eth::Key.new
# => #<Eth::Key:0x0000556e3e147d08
 @private_key=#<Secp256k1::PrivateKey:0x0000556e3e147ad8>,
 @public_key=#<Secp256k1::PublicKey:0x0000556e3e147ab0>>
signed = account.personal_sign hashed
# => "d0cafb1f024fe513bfc1f24dc087f09f9a1a8be5275ed54361b4b1217d78fca86fee3ed8a7cc40bb8158d6c84dc3f55f73a8d9a75129e77c5f45a6d70bfab4bb1c"