functionalfoundry / ethereum-htlc

HTLC for doing cross-chain atomic swaps
MIT License
7 stars 2 forks source link

Change preimage to bytes32 #5

Closed yanivtal closed 6 years ago

yanivtal commented 6 years ago

This is a prerequisite for https://github.com/functionalfoundry/ethereum-htlc/issues/1. Initially I tried just changing the hash on the JS side and EVM side but the images no longer matched.

In Solidity, SHA256 returns a bytes32 so if it's going to do 2 rounds, it really needs to take the same type for both rounds in order to return a predictable result.

This ended up being more challenging than expected. An ascii string looks like secret A hex string looks like 736563726574 A bytes32 string looks like 0x7365637265740000000000000000000000000000000000000000000000000000

Our node SHA256 function accepts an ascii string. The EVM SHA256 accepts a hex string. An image of an ascii string in node matches an image of the corresponding hex string on the EVM. However, switching to byte32 breaks this. In order to make it work I needed to encode the ascii string into a 32 byte hex string, then decode it back to ascii, and then hash it. Even logging the original and transformed ascii strings makes them appear identical. Apparently going through this exercise does change the string's value though and this is the only way to get the hash in JS is to match the hash on the EVM.