Contents:
The time locks allow both parties to refund themselves in case the swap does not succeed as planned. The reason we use time locks for this is to eliminate the possibility that one person ends up with both coins, leaving the other person with nothing. When the locks are put on the HTLC mailboxes, the time locks are set to give each counterparty a chance to redeem the swap without interference.
If the swap never happens, everyone can take back the coins they started with after the time expires. The length of time on each lock is important to ensure that the game can only be played fairly. Broadly speaking this is because Alice knows the hash lock secret and therefore has a major advantage. To illustrate why this is important, consider if the times were reversed. Alice would have all the money and Bob would be broke! Now it's time to turn these "two-lock mailboxes" into actual Bitcoin transactions. For this guide we will describe a very simple method of constructing and executing smart contracts that sacrifice some privacy and potentially some security.
It is not recommended these be used as is in production. For details on how the implementation can be improved, see next steps below. It hashes the secret and checks that it matches a given hash, then it checks the signature against the given public key. To redeem the HTLC this way, we will use the following script in the input of a transaction:.
The time lock will only be checked when if false.
First it executes a Check Sequence Verify routine, which fails if the given relative locktime has not yet passed. Then it simply checks a signature against a given public key like usual.
To redeem the transaction with this path, we will use this input script:. The bcoin and bcash libraries are so similar that we can use the exact same commands to create HTLCs on both chains, and build a working application with wallets. With almost no conditionals, we can make this library completely chain-agnostic.
For example, observe how creating a new object with new Swap 'bcoin', 'testnet' would give us the specific Address module for making Bitcoin addresses. We could create a second object for bcash that would, with the exact same line of code, give us the module for Bitcoin Cash addresses. The next three functions we'll need will compile our Bitcoin scripts from the last section into the actual byte code used in serialized transactions on the network.
To learn more about working with scripts, check out the bcoin. This is required by the mechanics of Pay-To-Script-Hash transactions.
The transaction output we are spending from contains only a hash of the redeem script. The actual redeem script itself is provided by the input scripts at the time the coin is being spent, so they are included here. The laws of the finite universe prevent us from signing a message that already contains its own signature, and the Bitcoin Protocol therefore expects the signatures to be removed from a transaction script during verification.
Eventually we will sign our transactions with these Int 0 's in the scripts, then replace them with the final signatures for broadcasting to the network. This is an easy process. This is where the similarity between libraries is crucial. For both networks, we can generate valid P2SH addresses using the same function:.
On testnet, using two different instances of our Swap class, this function will give us the following example addresses:. Once funds are sent to the P2SH addresses, we can spend them using either the swap or refund input scripts. We have already generated the scripts so we just need to create a transaction and sign it!
Generating the signatures is handled entirely by the TX module in each library:. Ok, here we finally have some divergence between bcoin and bcash. In the tx. Since Bitcoin Cash does not have any SegWit features at all, this parameter is instead used to pass additional SigHash flags used for replay protection at the time of the hard fork. Due to a similar inconsistency, we will need to pass different values for sigHashType depending on which chain we are constructing transactions for.
With those disclaimers behind us, let's build the transaction! The following function puts together all the pieces to complete the swap. For more detail on how these MTX methods work, see the bcoin. Once we've completed and signed the transaction, we can test that it verifies against the network rules:.
Now that we have all the tools, you might be asking yourself "What is the minimum amount of information two parties need to send each other to engage in a swap? It turns out that besides the exchange rate and volume, the only thing the two trading partners need to exchange is:. Using these data and the scripting functions from the last section, both parties can deterministically derive the P2SH addresses for the contracts on both chains.
By watching for transactions in and out of those addresses on both chains, everyone will have everything they need to play the atomic swap game. We can add two simple functions to generate these data, using the bcrypto module as a utility:.
They key exchange method is up to the users on the application layer. They could save a little space by agreeing on a protocol in advance. We can imagine preset, hard-coded locktimes and perhaps a common exchange rate API. Remember, part of the swap protocol involves Alice revealing her secret value to Bob.
That is done on the blockchain, so Bob needs to watch the chain for Alice's redemption transaction and pull the secret value out of it somehow. Since we know the exact structure of Alice's input script we can expect her secret to be the second value in the script. Once we catch Alice's transaction we need to figure out which input is redeeming the swap, then grab the secret. We discover the input by looking for the P2SH address we derived earlier. The last mechanism we need to make a functional atomic swap application is a wallet, or several wallets.
Refer to the bcoin. For brevity, we'll just review the last step in our swap story: Bob extracting the HTLC secret from Alice's Bitcoin Cash sweep-transaction and using it to sweep his own Bitcoin transaction. Keep in mind that by the time the following code is run, Bob has already deposited BTC into the swap address for Alice to sweep.
The code is presented linearly here but in the actual application it is organized a bit differently. Alice will have similar code running on her end. Twitter crosschaingroup Telegram t. We believe that the driving force behind innovation lies in the collaborative efforts of the community. Cross-chain group is a medium that brings the brightest minds in our ecosystem together to accomplish more, in less time.
From summits to whiteboard sessions, we provide private forums for collaboration and discussion. Our members are dedicated to the research and development of cross-chain architecture. We make it a practice to open-source tooling and provide resources that help your business to be more connected. Members of CCG are actively working to remove the barriers between chains, allowing liquidity, users, and value to flow more freely throughout the ecosystem.
Cross-chain Group is on the cutting edge of interoperability and are responsible for much of the cross-chain architecture that exists today. If you have questions, or would like to discuss your ideas, please feel free to reach out to us.