├── .gitignore ├── .trades ├── ongoing │ ├── .gitkeep │ ├── eXQBT0jL3e-client.json │ ├── eXQBT0jL3e-server.json │ ├── vlKFnqips8-client.json │ └── vlKFnqips8-server.json └── success │ └── .gitkeep ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── alice-failed-to-lock-xmr.mp4 ├── client ├── Cargo.toml └── src │ ├── main.rs │ └── recover.rs ├── happy-path.mp4 ├── protocol ├── Cargo.toml └── src │ ├── adaptor_signature.rs │ ├── alice.rs │ ├── blockchain │ └── mod.rs │ ├── bob.rs │ ├── contract │ └── mod.rs │ ├── keys │ ├── bitcoin │ │ ├── address.rs │ │ └── mod.rs │ └── mod.rs │ ├── lib.rs │ ├── persist.rs │ ├── proof │ └── mod.rs │ ├── protocol.rs │ └── utils.rs └── web-server ├── Cargo.toml └── src ├── main.rs ├── trader.rs └── utils.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /test 3 | /.trades/**/*.json 4 | 5 | !/.trades/ongoing/eXQBT0jL3e-client.json 6 | !/.trades/ongoing/eXQBT0jL3e-server.json 7 | !/.trades/ongoing/vlKFnqips8-client.json 8 | !/.trades/ongoing/vlKFnqips8-server.json -------------------------------------------------------------------------------- /.trades/ongoing/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PHCitizen/bch-xmr-swap/4eac4fc3307d351da63b5d6e24521df8a746f94e/.trades/ongoing/.gitkeep -------------------------------------------------------------------------------- /.trades/ongoing/eXQBT0jL3e-client.json: -------------------------------------------------------------------------------- 1 | { 2 | "swap": { 3 | "Alice": { 4 | "state": { 5 | "ValidEncSig": { 6 | "bob_keys": { 7 | "monero_spend": "6733a71549bc12affbffe246e30b410cc39d33571d26be4a62ccfec883fce6a5", 8 | "monero_view": "a5c023dc2ad30048bb4e064005473e283c8d6477c475e00069b4f9e64786bd07", 9 | "ves": "027a7ce6addff4ed215b84fce6fa873fd9e0c0b8f7dc46aa6b45453af2cc4a2450", 10 | "spend_bch": "03afc8ee06e9f87ec88fed0326978864ca6577168b13180b2bfcd9c7a0b9451618" 11 | }, 12 | "bob_bch_recv": "76a9149a6d05e1e725ed4e4254b34b61d3e7760fff986588ac", 13 | "contract_pair": { 14 | "swaplock": { 15 | "mining_fee": 1000, 16 | "success_output": "76a91485bc957e1184eca3f8e3fac3bbec72bc135d8f6788ac", 17 | "pubkey_ves": "027a7ce6addff4ed215b84fce6fa873fd9e0c0b8f7dc46aa6b45453af2cc4a2450", 18 | "timelock": 2, 19 | "failed_output": "a91443265bc939f862ca5c66dc9f8c4379578973b94987", 20 | "bch_network": "Mainnet", 21 | "_private": null 22 | }, 23 | "refund": { 24 | "mining_fee": 1000, 25 | "success_output": "76a9149a6d05e1e725ed4e4254b34b61d3e7760fff986588ac", 26 | "pubkey_ves": "02e2c2953822ec74ed7e2bae2b97de48e81ebfbcb93c8a9d44af6ee80a359a909c", 27 | "timelock": 2, 28 | "failed_output": "76a91485bc957e1184eca3f8e3fac3bbec72bc135d8f6788ac", 29 | "bch_network": "Mainnet", 30 | "_private": null 31 | }, 32 | "alice_receiving": [ 33 | 118, 34 | 169, 35 | 20, 36 | 133, 37 | 188, 38 | 149, 39 | 126, 40 | 17, 41 | 132, 42 | 236, 43 | 163, 44 | 248, 45 | 227, 46 | 250, 47 | 195, 48 | 187, 49 | 236, 50 | 114, 51 | 188, 52 | 19, 53 | 93, 54 | 143, 55 | 103, 56 | 136, 57 | 172 58 | ], 59 | "bob_receiving": [ 60 | 118, 61 | 169, 62 | 20, 63 | 154, 64 | 109, 65 | 5, 66 | 225, 67 | 231, 68 | 37, 69 | 237, 70 | 78, 71 | 66, 72 | 84, 73 | 179, 74 | 75, 75 | 97, 76 | 211, 77 | 231, 78 | 118, 79 | 15, 80 | 255, 81 | 152, 82 | 101, 83 | 136, 84 | 172 85 | ], 86 | "swaplock_in_sats": 10000, 87 | "mining_fee": 1000, 88 | "bch_network": "Mainnet" 89 | }, 90 | "shared_keypair": { 91 | "spend": "3c5d190e218ba990e537f0a3c8d8c2890b3fab4348006f4818a22a843c6725d7", 92 | "view": "026c0b79b05934814d39bcfed5715c9d22b9ceaf6a8f118d86bf12a071aba90f" 93 | }, 94 | "outpoint": "fd32b7b72f8de2b022e12fcb925d83b60d6e9fd121098b72c560b6870a60c86e:0", 95 | "dec_sig": "304402204c837eb43ac0450426e224f4479aafc67520db5063f1d25a9a32b8017ce403aa022062132decb368365c7bcea94b0b763afc1c0b72d57aab4f7e198d6d334da3df1c" 96 | } 97 | }, 98 | "swap": { 99 | "id": "", 100 | "xmr_network": "Mainnet", 101 | "bch_network": "Mainnet", 102 | "keys": { 103 | "monero_spend": "734cac99a977b6bb3490282de2f9f413d4b82f4b1a9ea3e5b26cfd823e05800e", 104 | "monero_view": "5dabe79c8586333992eab5bed02a1e75e62b6a38a619318c1d0b19b92925ec07", 105 | "ves": "KxJ8PZa9rWQ1VbFb7eT5N14Xt8XfAHFEKKNVoCbUPFxhT8dWJeCs" 106 | }, 107 | "bch_recv": "76a91485bc957e1184eca3f8e3fac3bbec72bc135d8f6788ac", 108 | "xmr_amount": 100000, 109 | "bch_amount": 10000, 110 | "timelock1": 2, 111 | "timelock2": 2 112 | } 113 | } 114 | }, 115 | "refund_private_key": "L5T55NZBhH2SuWpuDTUqcXecPcEDYxAPXCCV86RrZbmM1bZYv3AR" 116 | } -------------------------------------------------------------------------------- /.trades/ongoing/eXQBT0jL3e-server.json: -------------------------------------------------------------------------------- 1 | { 2 | "swap": { 3 | "Bob": { 4 | "state": { 5 | "SwapSuccess": [ 6 | { 7 | "spend": "fc476607c1c7c2ac403a88a768cedae510f2a067b69749f91fea485126eca90d", 8 | "view": "026c0b79b05934814d39bcfed5715c9d22b9ceaf6a8f118d86bf12a071aba90f" 9 | }, 10 | "43unSddtX9iREffuDzs8gHPvVsu56Bfb4D4RaHjqFyQYd1PPwyJUWKX2ZmX9dxM3kiDq3Ct6mzeYDH6zsJJWjz6vFamaatk", 11 | 3055289 12 | ] 13 | }, 14 | "swap": { 15 | "id": "eXQBT0jL3e", 16 | "xmr_network": "Mainnet", 17 | "bch_network": "Mainnet", 18 | "keys": { 19 | "monero_spend": "76cfafca31b31e49e246571d65cec4e63c39711c9cf9a5136d7d4bcee7e6290f", 20 | "monero_view": "a5c023dc2ad30048bb4e064005473e283c8d6477c475e00069b4f9e64786bd07", 21 | "ves": "Kxb6U6boipZyJ8TUhsJpd2mrP6VhnWF8KBjKzHxsdMrWUoHqdeW2" 22 | }, 23 | "bch_recv": "76a9149a6d05e1e725ed4e4254b34b61d3e7760fff986588ac", 24 | "xmr_amount": 100000, 25 | "bch_amount": 10000, 26 | "timelock1": 2, 27 | "timelock2": 2 28 | } 29 | } 30 | }, 31 | "refund_private_key": "L1vvrjtKaTXFvjKfT2JX73NHYGRiAcJeLby2Ci1bqiVzfoKfwv9w" 32 | } -------------------------------------------------------------------------------- /.trades/ongoing/vlKFnqips8-client.json: -------------------------------------------------------------------------------- 1 | { 2 | "swap": { 3 | "Alice": { 4 | "state": { 5 | "Refund": [ 6 | "43ksEUrQwL8hpSqyAV498AAqnSntEiEBaPKHz1nrMuPU9U9ZR655TuBCUv71PyeoXnHqbUq5RdHsbbYmntrQzRnwRha7Z9b", 7 | { 8 | "spend": "8579fb63828175100bc71b8f8b3ccbd641482554c2637c1eaae378f422cee10a", 9 | "view": "802ff310ecc831d569aa1e08fbe4e595d8ac3e44c76cf49e98b22cb536787d05" 10 | } 11 | ] 12 | }, 13 | "swap": { 14 | "id": "", 15 | "xmr_network": "Mainnet", 16 | "bch_network": "Mainnet", 17 | "keys": { 18 | "monero_spend": "40623cf7978dc57d9f19817a174a2b4103d6b163865ff2b85ccfa4937d111404", 19 | "monero_view": "6e81a9909227b6c89978da645e47a88838908d58fb7157be458671aecff54808", 20 | "ves": "L33oXLtvALCZK2JiQb3EohTzhQnQdFetNenv3d5Te5Xfkx6PKSBH" 21 | }, 22 | "bch_recv": "76a914317bb579dba88c13faccd9f52910dbe9d68cc8e688ac", 23 | "xmr_amount": 100000, 24 | "bch_amount": 10000, 25 | "timelock1": 2, 26 | "timelock2": 2 27 | } 28 | } 29 | }, 30 | "refund_private_key": "L254GbdXJjx4yiXyKybVRUcDxuxBSEG4pnQaLyMPnbV6YnkSE4m6" 31 | } -------------------------------------------------------------------------------- /.trades/ongoing/vlKFnqips8-server.json: -------------------------------------------------------------------------------- 1 | { 2 | "swap": { 3 | "Bob": { 4 | "state": { 5 | "ProceedRefund": { 6 | "alice_keys": { 7 | "monero_spend": "029cd9ba23acee6e59690a4d21c4f298ec6787a7ef47190ce3a3c45757f4b478", 8 | "monero_view": "6e81a9909227b6c89978da645e47a88838908d58fb7157be458671aecff54808", 9 | "ves": "03533c52b4bb6ce438cf1198efbedd5132e281683b9d7fc5930d877fa189f3f5af", 10 | "spend_bch": "024b57d50e0cc2321c0bcc20157178e953d9e0d3b0d9aaabdd8bba13acd468d536" 11 | }, 12 | "alice_bch_recv": "76a914317bb579dba88c13faccd9f52910dbe9d68cc8e688ac", 13 | "contract_pair": { 14 | "swaplock": { 15 | "mining_fee": 1000, 16 | "success_output": "76a914317bb579dba88c13faccd9f52910dbe9d68cc8e688ac", 17 | "pubkey_ves": "03c5f8469e84c6e33a09925195c572a86f70242f507c28369925671c403a1c112f", 18 | "timelock": 2, 19 | "failed_output": "a914997fe86fccf3167e54e2d0a9c70e703d72bb945287", 20 | "bch_network": "Mainnet", 21 | "_private": null 22 | }, 23 | "refund": { 24 | "mining_fee": 1000, 25 | "success_output": "76a914ba289427bec370b7ef8b690930935ebc35d4c58e88ac", 26 | "pubkey_ves": "03533c52b4bb6ce438cf1198efbedd5132e281683b9d7fc5930d877fa189f3f5af", 27 | "timelock": 2, 28 | "failed_output": "76a914317bb579dba88c13faccd9f52910dbe9d68cc8e688ac", 29 | "bch_network": "Mainnet", 30 | "_private": null 31 | }, 32 | "alice_receiving": [ 33 | 118, 34 | 169, 35 | 20, 36 | 49, 37 | 123, 38 | 181, 39 | 121, 40 | 219, 41 | 168, 42 | 140, 43 | 19, 44 | 250, 45 | 204, 46 | 217, 47 | 245, 48 | 41, 49 | 16, 50 | 219, 51 | 233, 52 | 214, 53 | 140, 54 | 200, 55 | 230, 56 | 136, 57 | 172 58 | ], 59 | "bob_receiving": [ 60 | 118, 61 | 169, 62 | 20, 63 | 186, 64 | 40, 65 | 148, 66 | 39, 67 | 190, 68 | 195, 69 | 112, 70 | 183, 71 | 239, 72 | 139, 73 | 105, 74 | 9, 75 | 48, 76 | 147, 77 | 94, 78 | 188, 79 | 53, 80 | 212, 81 | 197, 82 | 142, 83 | 136, 84 | 172 85 | ], 86 | "swaplock_in_sats": 10000, 87 | "mining_fee": 1000, 88 | "bch_network": "Mainnet" 89 | }, 90 | "shared_keypair": { 91 | "spend": "384e76b1bd34b5f408f87702733e973ad6085672a68711856a3eb5721c7b3732", 92 | "view": "802ff310ecc831d569aa1e08fbe4e595d8ac3e44c76cf49e98b22cb536787d05" 93 | }, 94 | "xmr_restore_height": 3055309, 95 | "dec_sig": "30450221008ee086c8c8953b0f86bd90131ea85d36247734207b52c1a74e4a179f28d34743022073d9f6462d24a8471e3e3e479a85f498bc68651249a5bfaff5a3982d73c0b7ac", 96 | "outpoint": "7390f02f76b9892d151ae71a6490dc4e3876e95bf2241328aff0a07a3501d226:0" 97 | } 98 | }, 99 | "swap": { 100 | "id": "vlKFnqips8", 101 | "xmr_network": "Mainnet", 102 | "bch_network": "Mainnet", 103 | "keys": { 104 | "monero_spend": "4517bf6ceaf3af926bad9a1474f29f953e7273f03b048a654d14d460a5bccd06", 105 | "monero_view": "ff813fdd73048e64a6ce3b467b971c22a01cb1ebcbfa9ce0522cbb066782340d", 106 | "ves": "Kx9Q7MbDSv7PgGWLpjb2TsR3QAyiiYPPepKKWTK72mNTfJNju8jB" 107 | }, 108 | "bch_recv": "76a914ba289427bec370b7ef8b690930935ebc35d4c58e88ac", 109 | "xmr_amount": 100000, 110 | "bch_amount": 10000, 111 | "timelock1": 2, 112 | "timelock2": 2 113 | } 114 | } 115 | }, 116 | "refund_private_key": "KwV1yosenSWeerz2bmCwGs2cJTTaS2WY9JzT1wgf8PTaVfp8T5N2" 117 | } -------------------------------------------------------------------------------- /.trades/success/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PHCitizen/bch-xmr-swap/4eac4fc3307d351da63b5d6e24521df8a746f94e/.trades/success/.gitkeep -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = ["protocol", "web-server", "client"] 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BCH-XMR-SWAP PoC 2 | 3 | 4 | 5 | https://github.com/PHCitizen/bch-xmr-swap/assets/75726261/00596f8d-e98f-4597-8656-d282f12509d5 6 | 7 | 8 | 9 | - SwapLock Contract on video: `bchtest:prf659upqyz96d7l4auuxt567fdrnrr4dyt6ddc8s5` 10 | - SwapLock Tx claim by "Alice": `5d9c13db8c40b2ab29b58a1f480bc90ba0746a7512ed78ceb2467f5084c7193a` 11 | 12 | ### Story 13 | I interested in the bounty thats why i take a look. After some research i found that the contract v3 has some error on the signature part, thats why i contacted @bitcoincashautist. After exchanging idea, he come up with the contract v4. After that i started creating this repo. I was afraid to show it because i dont really know if i can finish it on time. I don't want to give "false hope" or make anyone waits on me (sorry @bitcoincashautist). 14 | 15 | I almost finish it but i get very busy on school stuff. Then i came back again, and thats the time @bitcoincashautist informed me that we are racing for this bounty. So finish some missing part and do the testing. 16 | 17 | - Why @mainnet_pat doing the flipstarter? 18 | - idk if i am able to make it on time, I still need to go in school😅. 19 | - They have much more experience than me 20 | - They are well-known in bch community and built many project. 21 | 22 | > I could help if needed. But i can't commit. 23 | 24 | 25 | ### Development 26 | 27 | Run client and server with auto-reload on save 28 | ``` 29 | cargo watch -c -q -w web-server -w protocol -x "run --bin web-server" 30 | cargo watch -c -q -w client -w protocol -x "run --bin client" 31 | ``` 32 | 33 | Monero cli/rpc version used 34 | ``` 35 | monero-linux-x64-v0.18.3.1.tar.bz2 36 | ``` 37 | 38 | Example regtest for monero development 39 | ``` 40 | monerod --regtest --offline --fixed-difficulty=1 --rpc-bind-ip=0.0.0.0 --confirm-external-bind 41 | 42 | monero-wallet-rpc --disable-rpc-login --log-level=3 --daemon-address=http://localhost:18081 --untrusted-daemon --confirm-external-bind --rpc-bind-ip=0.0.0.0 --rpc-bind-port=8081 --wallet-dir=wallet_dir --allow-mismatched-daemon-version 43 | 44 | monero-wallet-cli --log-level=3 --daemon-address=http://localhost:18081 --untrusted-daemon --allow-mismatched-daemon-version 45 | ``` 46 | 47 | ### Mainnet Transactions 48 | 49 | > Video are provided at the root of this repository ending it .mp4 50 | > File is >10mb so i cant embed it. You can just download it. 51 | 52 | #### Happy Path 53 | - SwapLock -> Alice: 91b9ab4ec54d22b46330c6ba9e5bb07a104513d7d132c2b6b7c48c76c921f40b 54 | - Sweep Alice private key: 76d98630bc1ddd68d42905de1eaa41ae2e024dc75aa0622e1423de130caf0e71 55 | - XMR Shared Address: 43unSddtX9iREffuDzs8gHPvVsu56Bfb4D4RaHjqFyQYd1PPwyJUWKX2ZmX9dxM3kiDq3Ct6mzeYDH6zsJJWjz6vFamaatk 56 | - Alice Keys `.trades/ongoing/eXQBT0jL3e-client.json` TradeId: eXQBT0jL3e 57 | - Bob Keys `.trades/ongoing/eXQBT0jL3e-server.json` TradeId: eXQBT0jL3e 58 | 59 | #### Alice Failed to lock XMR 60 | - SwapLock Contract: bitcoincash:pzavf0mxs2kfec8xsj7u8s6pquussw9dgs7mnmknl4 61 | - SwapLock -> Refund: 1604dc533f241c643ad66aa8e64910298c39367dbf8bce1159bdbc5f5bb25e58 62 | - Refund -> Bob Output: 2746ec141696a5b4dafc13eb8ce98ab3d4c4451967480d6d5af4996515241eeb 63 | - Bob Spend: 8482981fd76ce8e8d82c2d299828941070fedebfdc1193edf70c704af5b01922 64 | - Alice Keys `.trades/ongoing/vlKFnqips8-client.json` TradeId: eXQBT0jL3e 65 | - Bob Keys `.trades/ongoing/vlKFnqips8-server.json` TradeId: eXQBT0jL3e 66 | 67 | 68 | ### Credits 69 | - The adaptor signature are base in https://github.com/comit-network/xmr-btc-swap 70 | - The contract use are created by @bitcoincashautist https://gitlab.com/0353F40E/cross-chain-swap-ves/-/tree/master 71 | - Discussions: 72 | - https://bitcoincashresearch.org/t/monero-bch-atomic-swaps/545 73 | - https://bounties.monero.social/posts/37/18-421m-bch-xmr-atomic-swaps 74 | 75 | 76 | # Bounty Address 77 | https://bounties.monero.social/posts/37/18-921m-bch-xmr-atomic-swaps 78 | 79 | monero address: 41pehjm4dYjeHNFKBfu3KJVE7zg5B6G3Cim54SbbMruyAo5M1yF84TVAAerVUVUbfN7qTFqhQioGMHJsextkVao36eyae4Z 80 | 81 | bch address: bitcoincash:qph2r7qg026pqtpgz8lp4t8nwhw3wlnxcch2apefdc 82 | -------------------------------------------------------------------------------- /alice-failed-to-lock-xmr.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PHCitizen/bch-xmr-swap/4eac4fc3307d351da63b5d6e24521df8a746f94e/alice-failed-to-lock-xmr.mp4 -------------------------------------------------------------------------------- /client/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "client" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | [[bin]] 8 | name = "recover" 9 | path = "src/recover.rs" 10 | 11 | [[bin]] 12 | name = "client" 13 | path = "src/main.rs" 14 | 15 | [dependencies] 16 | anyhow = "1.0.75" 17 | hex = "0.4.3" 18 | protocol = { path = "../protocol" } 19 | reqwest = { version = "0.11.22", features = ["json"] } 20 | serde = { version = "1.0.188", features = ["derive"] } 21 | serde_json = "1.0.107" 22 | tokio = { version = "1.32.0", features = ["full"] } 23 | -------------------------------------------------------------------------------- /client/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::{sync::Arc, time::Duration}; 2 | 3 | use anyhow::bail; 4 | use reqwest::StatusCode; 5 | use serde_json::json; 6 | 7 | use protocol::{ 8 | alice, 9 | bitcoincash::{self}, 10 | blockchain::{self}, 11 | keys::{ 12 | bitcoin::{self, random_private_key}, 13 | KeyPrivate, 14 | }, 15 | monero::{self}, 16 | persist::{Config, TradePersist}, 17 | protocol::Swap, 18 | protocol::{SwapEvents, SwapWrapper, Transition}, 19 | }; 20 | use tokio::{fs, io::AsyncWriteExt, net::TcpStream, time::sleep}; 21 | 22 | const BASE_URL: &str = "http://localhost:8080"; 23 | 24 | async fn create_new_trade( 25 | client: &reqwest::Client, 26 | timelock1: u32, 27 | timelock2: u32, 28 | bch_amount: bitcoincash::Amount, 29 | xmr_amount: monero::Amount, 30 | ) -> anyhow::Result { 31 | let response = client 32 | .post(format!("{BASE_URL}/trader")) 33 | .json(&json!({ 34 | "path": "xmr->bch", 35 | "timelock1": timelock1, 36 | "timelock2": timelock2, 37 | "bch_amount": bch_amount.to_sat(), 38 | "xmr_amount": xmr_amount.as_pico() 39 | })) 40 | .send() 41 | .await?; 42 | 43 | match response.status() { 44 | StatusCode::OK => { 45 | let body = response.json::().await?; 46 | return Ok(body["trade_id"].as_str().unwrap().to_string()); 47 | } 48 | code => { 49 | let body = response.text().await?; 50 | bail!("[ERROR]: {code} - {body}"); 51 | } 52 | } 53 | } 54 | 55 | async fn get_server_transition( 56 | client: &reqwest::Client, 57 | trade_id: &str, 58 | ) -> anyhow::Result> { 59 | let response = client 60 | .get(format!("{BASE_URL}/trader/{trade_id}")) 61 | .send() 62 | .await?; 63 | 64 | match response.status() { 65 | StatusCode::OK => Ok(response.json::>().await?), 66 | code => { 67 | let body = response.text().await?; 68 | bail!("[ERROR]: {code} - {body}"); 69 | } 70 | } 71 | } 72 | 73 | async fn send_transition( 74 | client: &reqwest::Client, 75 | trade_id: &str, 76 | transition: &Transition, 77 | ) -> anyhow::Result<()> { 78 | let response = client 79 | .patch(format!("{BASE_URL}/trader/{trade_id}")) 80 | .json(transition) 81 | .send() 82 | .await?; 83 | 84 | match response.status() { 85 | StatusCode::OK => Ok(()), 86 | code => { 87 | let body = response.text().await?; 88 | bail!("[ERROR] {code} - {body}"); 89 | } 90 | } 91 | } 92 | 93 | pub fn get_file_path(trade_id: &str) -> String { 94 | format!("./.trades/ongoing/{trade_id}-client.json") 95 | } 96 | 97 | #[tokio::main] 98 | async fn main() -> anyhow::Result<()> { 99 | let bch_min_confirmation = 1; 100 | 101 | let fullcrum_tcp = "localhost:50001"; 102 | let monero_network = monero::Network::Mainnet; 103 | let bch_network = bitcoin::Network::Regtest; 104 | 105 | // =================================================== 106 | 107 | let req_client = reqwest::Client::new(); 108 | let socket = TcpStream::connect(fullcrum_tcp).await?; 109 | let bch_server = Arc::new(blockchain::TcpElectrum::new(socket)); 110 | 111 | println!("Subscribing for new block"); 112 | let _ = bch_server 113 | .send("blockchain.headers.subscribe", json!([])) 114 | .await?; 115 | println!("========================================"); 116 | 117 | println!("Generating new keys..."); 118 | let recv_privkey = random_private_key(bch_network); 119 | let secp = bitcoincash::secp256k1::Secp256k1::signing_only(); 120 | let recv_pub = recv_privkey.public_key(&secp); 121 | let recv_addr = recv_pub.pubkey_hash(); 122 | let recv_script = bitcoincash::Script::new_p2pkh(&recv_addr); 123 | 124 | let timelock1 = 20; 125 | let timelock2 = 20; 126 | 127 | let bch_amount = bitcoincash::Amount::from_sat(100000); 128 | let xmr_amount = monero::Amount::from_pico(100000); 129 | 130 | let swap = alice::Alice { 131 | state: alice::State::Init, 132 | swap: Swap { 133 | id: "".to_owned(), 134 | keys: KeyPrivate::random(bch_network), 135 | 136 | bch_amount, 137 | xmr_amount, 138 | 139 | xmr_network: monero_network, 140 | bch_network, 141 | 142 | bch_recv: recv_script, 143 | 144 | timelock1, 145 | timelock2, 146 | }, 147 | }; 148 | 149 | let string_json = serde_json::to_string_pretty(&swap.swap.keys).unwrap(); 150 | println!("Private Keys: {string_json}"); 151 | println!("Bch recv private key: {}", recv_privkey); 152 | 153 | let swap = SwapWrapper::Alice(swap); 154 | 155 | println!("========================================"); 156 | 157 | println!("Creating new trade..."); 158 | let trade_id = 159 | create_new_trade(&req_client, timelock1, timelock2, bch_amount, xmr_amount).await?; 160 | println!("Trade id: {trade_id}"); 161 | 162 | tokio::spawn({ 163 | // process subscription 164 | let bch_server = bch_server.clone(); 165 | let trade_id = trade_id.clone(); 166 | 167 | async move { 168 | let mut receiver = bch_server.subscribe(); 169 | 170 | loop { 171 | let data = receiver.recv().await.unwrap(); 172 | let data = serde_json::from_str::(&data).unwrap(); 173 | 174 | let method = data["method"].as_str().unwrap(); 175 | if method != "blockchain.headers.subscribe" { 176 | eprintln!("Unknown method: {method}"); 177 | continue; 178 | } 179 | 180 | println!("New block found. Rescanning addresses"); 181 | 182 | let mut trade = TradePersist::restore(get_file_path(&trade_id)) 183 | .await 184 | .unwrap(); 185 | match trade.config.swap { 186 | SwapWrapper::Bob(_) => {} 187 | SwapWrapper::Alice(alice) => { 188 | let mut runner = alice::Runner { 189 | inner: alice, 190 | bch: &bch_server, 191 | min_bch_conf: bch_min_confirmation, 192 | }; 193 | let _ = runner.check_bch().await; 194 | trade.config.swap = SwapWrapper::Alice(runner.inner); 195 | trade.save().await; 196 | } 197 | }; 198 | } 199 | } 200 | }); 201 | 202 | let serialized = serde_json::to_vec_pretty(&Config { 203 | swap, 204 | refund_private_key: recv_privkey, 205 | })?; 206 | fs::OpenOptions::new() 207 | .create_new(true) 208 | .write(true) 209 | .open(get_file_path(&trade_id)) 210 | .await? 211 | .write(&serialized) 212 | .await?; 213 | 214 | println!("========================================"); 215 | 216 | loop { 217 | let trade = TradePersist::restore(get_file_path(&trade_id)) 218 | .await 219 | .unwrap(); 220 | match &trade.config.swap { 221 | SwapWrapper::Bob(_) => {} 222 | SwapWrapper::Alice(inner) => { 223 | let transition = inner.get_transition(); 224 | drop(trade); 225 | 226 | if let Some(transition) = transition { 227 | if let Err(e) = send_transition(&req_client, &trade_id, &transition).await { 228 | println!("{:?}", e); 229 | sleep(Duration::from_secs(10)).await; 230 | } 231 | } 232 | } 233 | }; 234 | 235 | match get_server_transition(&req_client, &trade_id).await { 236 | Err(e) => println!("============= {:?}", e), 237 | Ok(transition) => match transition { 238 | None => { 239 | sleep(Duration::from_secs(5)).await; 240 | } 241 | Some(transition) => { 242 | let mut trade = TradePersist::restore(get_file_path(&trade_id)) 243 | .await 244 | .unwrap(); 245 | match trade.config.swap { 246 | SwapWrapper::Alice(alice) => { 247 | let mut runner = alice::Runner { 248 | inner: alice, 249 | min_bch_conf: bch_min_confirmation, 250 | bch: &bch_server, 251 | }; 252 | runner.pub_transition(transition).await?; 253 | trade.config.swap = SwapWrapper::Alice(runner.inner); 254 | trade.save().await; 255 | } 256 | SwapWrapper::Bob(_) => {} 257 | } 258 | } 259 | }, 260 | }; 261 | 262 | sleep(Duration::from_secs(5)).await; 263 | } 264 | } 265 | -------------------------------------------------------------------------------- /client/src/recover.rs: -------------------------------------------------------------------------------- 1 | use std::{env, sync::Arc}; 2 | 3 | use protocol::{alice, blockchain, persist::TradePersist, protocol::SwapWrapper}; 4 | use tokio::net::TcpStream; 5 | 6 | pub fn get_file_path(trade_id: &str) -> String { 7 | format!("./.trades/ongoing/{trade_id}-client.json") 8 | } 9 | 10 | #[tokio::main] 11 | async fn main() -> anyhow::Result<()> { 12 | let trade_id = env::args().nth(1).expect("Trade id required"); 13 | 14 | let fullcrum_tcp = "localhost:50001"; 15 | let socket = TcpStream::connect(fullcrum_tcp).await?; 16 | let bch_server = Arc::new(blockchain::TcpElectrum::new(socket)); 17 | 18 | let mut trade = TradePersist::restore(get_file_path(&trade_id)) 19 | .await 20 | .unwrap(); 21 | match trade.config.swap { 22 | SwapWrapper::Bob(_) => {} 23 | SwapWrapper::Alice(inner) => { 24 | let mut runner = alice::Runner { 25 | inner, 26 | bch: &bch_server, 27 | min_bch_conf: 0, 28 | }; 29 | let _ = runner.check_bch().await; 30 | trade.config.swap = SwapWrapper::Alice(runner.inner); 31 | trade.save().await; 32 | } 33 | }; 34 | 35 | Ok(()) 36 | } 37 | -------------------------------------------------------------------------------- /happy-path.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PHCitizen/bch-xmr-swap/4eac4fc3307d351da63b5d6e24521df8a746f94e/happy-path.mp4 -------------------------------------------------------------------------------- /protocol/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "protocol" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | 9 | [dependencies] 10 | async-trait = "0.1.74" 11 | conquer-once = "0.4.0" 12 | fs4 = { version = "0.7", features = ["tokio"] } 13 | hex = { version = "0.4.3", features = ["serde"] } 14 | ecdsa_fun = { version = "0.9.0", default-features = false, features = [ 15 | "adaptor", 16 | "serde", 17 | ] } 18 | sha2 = "0.10" 19 | sigma_fun = { version = "0.6.0", default-features = false, features = [ 20 | "ed25519", 21 | "serde", 22 | "secp256k1", 23 | "alloc", 24 | ] } 25 | rand = "0.8" 26 | rand_chacha = "0.3" 27 | serde = { version = "1.0.188", features = ["derive"] } 28 | serde_json = "1.0.107" 29 | tokio = { version = "1.32.0", features = ["full"] } 30 | monero = { version = "0.19.0", features = ["full", "serde"] } 31 | bitcoin_hashes = "0.13.0" 32 | bitcoincash = { version = "0.29.2", features = ["serde"] } 33 | bech32 = "0.9.1" 34 | hex-literal = "0.4.1" 35 | monero-rpc = "0.4.0" 36 | anyhow = "1.0.75" 37 | -------------------------------------------------------------------------------- /protocol/src/adaptor_signature.rs: -------------------------------------------------------------------------------- 1 | use ecdsa_fun::{ 2 | adaptor::Adaptor, 3 | fun::{ 4 | self, 5 | marker::{NonZero, Secret}, 6 | Point, 7 | }, 8 | nonce::Deterministic, 9 | }; 10 | use sha2::Sha256; 11 | use sigma_fun::ed25519::curve25519_dalek::scalar::Scalar as ScalarDalek; 12 | use sigma_fun::HashTranscript; 13 | 14 | pub use ecdsa_fun::{adaptor::EncryptedSignature, Signature}; 15 | 16 | type Transcript = HashTranscript; 17 | type NonceGen = Deterministic; 18 | 19 | pub struct AdaptorSignature; 20 | 21 | impl AdaptorSignature { 22 | pub fn verify(signer: bitcoincash::PublicKey, message: &[u8; 32], sig: &Signature) -> bool { 23 | let ecdsa: ecdsa_fun::ECDSA> = ecdsa_fun::ECDSA::default(); 24 | 25 | let s_monero_bch = Point::from_bytes(signer.inner.serialize()).unwrap(); 26 | ecdsa.verify(&s_monero_bch, &message, &sig) 27 | } 28 | 29 | pub fn encrypted_sign( 30 | signer: &bitcoincash::PrivateKey, 31 | encryption_key: &bitcoincash::PublicKey, 32 | message: &[u8; 32], 33 | ) -> EncryptedSignature { 34 | let adaptor: Adaptor = Adaptor::default(); 35 | let signer = ecdsa_fun::fun::Scalar::from_bytes(signer.inner.secret_bytes()) 36 | .expect("failed to convert PrivateKey -> Scalar") 37 | .non_zero() 38 | .expect("failed to convert PrivateKey -> Scalar. non-zero"); 39 | 40 | let encryption_key = fun::Point::from_bytes(encryption_key.inner.serialize()) 41 | .expect("failed to convert PublicKey -> Point"); 42 | 43 | adaptor.encrypted_sign(&signer, &encryption_key, &message) 44 | } 45 | 46 | pub fn decrypt_signature( 47 | decryption_key: &monero::PrivateKey, 48 | encrypted_sig: EncryptedSignature, 49 | ) -> Signature { 50 | let adaptor: Adaptor = Adaptor::default(); 51 | 52 | let decryption_key = ScalarDalek::from_bytes_mod_order(decryption_key.to_bytes()); 53 | let decryption_key = scalardalek_to_scalarfun(&decryption_key); 54 | 55 | adaptor.decrypt_signature(&decryption_key, encrypted_sig) 56 | } 57 | 58 | pub fn recover_decryption_key( 59 | pubkey: bitcoincash::PublicKey, 60 | sig: Signature, 61 | enc_sig: EncryptedSignature, 62 | ) -> monero::PrivateKey { 63 | let adaptor: Adaptor = Adaptor::default(); 64 | let pubkey: Point = fun::Point::from_bytes(pubkey.inner.serialize()) 65 | .expect("failed to convert PublicKey -> Point"); 66 | 67 | let key_reversed = adaptor 68 | .recover_decryption_key(&pubkey, &sig, &enc_sig) 69 | .unwrap(); 70 | 71 | let mut big_edian: [u8; 32] = key_reversed.to_bytes(); 72 | big_edian.reverse(); 73 | let little_edian = big_edian; 74 | monero::PrivateKey::from_slice(&little_edian).unwrap() 75 | } 76 | } 77 | 78 | fn scalardalek_to_scalarfun(scalar: &ScalarDalek) -> ecdsa_fun::fun::Scalar { 79 | let mut little_endian_bytes = scalar.to_bytes(); 80 | 81 | little_endian_bytes.reverse(); 82 | let big_endian_bytes = little_endian_bytes; 83 | 84 | ecdsa_fun::fun::Scalar::from_bytes(big_endian_bytes) 85 | .expect("valid scalar") 86 | .non_zero() 87 | .expect("non-zero scalar") 88 | } 89 | 90 | #[cfg(test)] 91 | mod test { 92 | use super::AdaptorSignature; 93 | use crate::keys; 94 | 95 | #[test] 96 | fn test() { 97 | let bob = keys::KeyPrivate::random(keys::bitcoin::Network::Testnet); 98 | let bobpub = keys::KeyPublic::from(bob.clone()); 99 | let alice = keys::KeyPrivate::random(keys::bitcoin::Network::Testnet); 100 | let alicepub = keys::KeyPublic::from(alice.clone()); 101 | let message = [0u8; 32]; 102 | 103 | // bob signed alice output 104 | let enc_sig = AdaptorSignature::encrypted_sign(&bob.ves, &alicepub.spend_bch, &message); 105 | dbg!(&enc_sig); 106 | 107 | // alice decrypt the enc_sig 108 | let dec_sig = AdaptorSignature::decrypt_signature(&alice.monero_spend, enc_sig.clone()); 109 | dbg!(&dec_sig); 110 | 111 | // alice check if dec_sig can unlock swaplock 112 | let valid = AdaptorSignature::verify(bobpub.ves.clone(), &message, &dec_sig.clone()); 113 | assert!(valid); 114 | 115 | // bob get the decsig on bch tx, and recover alice priv_spend 116 | let alice_spend_recovered = 117 | AdaptorSignature::recover_decryption_key(alicepub.spend_bch, dec_sig, enc_sig); 118 | 119 | assert_eq!( 120 | alice_spend_recovered.to_string(), 121 | alice.monero_spend.to_string() 122 | ) 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /protocol/src/alice.rs: -------------------------------------------------------------------------------- 1 | use std::fmt; 2 | 3 | use anyhow::bail; 4 | use bitcoin_hashes::{sha256::Hash as sha256, Hash}; 5 | use bitcoincash::{ 6 | consensus::Encodable, OutPoint, PackedLockTime, Script, Sequence, Transaction, TxIn, TxOut, 7 | }; 8 | use ecdsa_fun::adaptor::EncryptedSignature; 9 | use hex::ToHex; 10 | use serde::{Deserialize, Serialize}; 11 | use serde_json::json; 12 | 13 | use crate::{ 14 | adaptor_signature::AdaptorSignature, 15 | bitcoincash::secp256k1::ecdsa, 16 | blockchain::{scan_address_conf_tx, TcpElectrum}, 17 | contract::{ContractPair, TransactionType}, 18 | keys::{KeyPublic, KeyPublicWithoutProof}, 19 | proof, 20 | protocol::{Action, Error, Swap, SwapEvents, Transition}, 21 | utils::{get_signature, monero_key_pair, monero_view_pair}, 22 | }; 23 | 24 | #[derive(Debug, Clone, Serialize, Deserialize)] 25 | pub struct Value0 { 26 | bob_keys: KeyPublicWithoutProof, 27 | #[serde(with = "hex")] 28 | bob_bch_recv: Vec, 29 | contract_pair: ContractPair, 30 | 31 | #[serde(with = "monero_view_pair")] 32 | shared_keypair: monero::ViewPair, 33 | } 34 | 35 | #[derive(Debug, Clone, Serialize, Deserialize)] 36 | pub struct Value1 { 37 | bob_keys: KeyPublicWithoutProof, 38 | #[serde(with = "hex")] 39 | bob_bch_recv: Vec, 40 | contract_pair: ContractPair, 41 | #[serde(with = "monero_view_pair")] 42 | shared_keypair: monero::ViewPair, 43 | 44 | outpoint: OutPoint, 45 | } 46 | 47 | #[derive(Debug, Clone, Serialize, Deserialize)] 48 | #[allow(dead_code)] 49 | pub struct Value2 { 50 | bob_keys: KeyPublicWithoutProof, 51 | #[serde(with = "hex")] 52 | bob_bch_recv: Vec, 53 | contract_pair: ContractPair, 54 | #[serde(with = "monero_view_pair")] 55 | shared_keypair: monero::ViewPair, 56 | outpoint: OutPoint, 57 | 58 | dec_sig: ecdsa::Signature, 59 | } 60 | 61 | #[derive(Debug, Clone, Serialize, Deserialize)] 62 | pub enum State { 63 | Init, 64 | WithBobKeys(Value0), 65 | ContractMatch(Value0), 66 | BchLocked(Value1), 67 | ValidEncSig(Value2), 68 | Refund( 69 | monero::Address, 70 | #[serde(with = "monero_key_pair")] monero::KeyPair, 71 | ), 72 | } 73 | 74 | impl fmt::Display for State { 75 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 76 | match self { 77 | State::Init => write!(f, "AliceState:Init"), 78 | State::WithBobKeys(_) => write!(f, "AliceState:WithBobKeys"), 79 | State::ContractMatch(_) => write!(f, "AliceState:ContractMatch"), 80 | State::BchLocked(_) => write!(f, "AliceState:BchLocked"), 81 | State::ValidEncSig(_) => write!(f, "AliceState:ValidEncSig"), 82 | State::Refund(_, _) => write!(f, "AliceState:Refund"), 83 | } 84 | } 85 | } 86 | 87 | #[derive(Debug, Clone, Serialize, Deserialize)] 88 | pub struct Alice { 89 | pub state: State, 90 | pub swap: Swap, 91 | } 92 | 93 | impl Alice { 94 | pub fn get_public_keys(&self) -> KeyPublic { 95 | KeyPublic::from(self.swap.keys.clone()) 96 | } 97 | 98 | pub fn get_contract(&self) -> Option<(String, monero::Address)> { 99 | if let State::WithBobKeys(props) = &self.state { 100 | return Some(( 101 | props.contract_pair.swaplock.cash_address(), 102 | monero::Address::from_viewpair(self.swap.xmr_network, &props.shared_keypair), 103 | )); 104 | } 105 | 106 | return None; 107 | } 108 | 109 | pub fn get_refunc_enc_sig(&self) -> Option { 110 | let (spend, recv) = match &self.state { 111 | State::ContractMatch(props) => (props.bob_keys.spend_bch, &props.bob_bch_recv), 112 | State::BchLocked(props) => (props.bob_keys.spend_bch, &props.bob_bch_recv), 113 | _ => return None, 114 | }; 115 | 116 | let hash = sha256::hash(recv).to_byte_array(); 117 | let hash = sha256::hash(&hash).to_byte_array(); 118 | let enc_sig = AdaptorSignature::encrypted_sign(&self.swap.keys.ves, &spend, &hash); 119 | return Some(enc_sig); 120 | } 121 | 122 | pub fn get_contract_pair(&self) -> Option { 123 | match self.state.clone() { 124 | State::WithBobKeys(v) => Some(v.contract_pair), 125 | State::ContractMatch(v) => Some(v.contract_pair), 126 | State::BchLocked(v) => Some(v.contract_pair), 127 | State::ValidEncSig(v) => Some(v.contract_pair), 128 | _ => None, 129 | } 130 | } 131 | 132 | pub fn get_unlock_normal_tx(&self) -> Option { 133 | if let State::ValidEncSig(props) = &self.state { 134 | let unlocker = props 135 | .contract_pair 136 | .swaplock 137 | .unlocking_script(&props.dec_sig.serialize_der()); 138 | 139 | let mining_fee = props.contract_pair.swaplock.mining_fee; 140 | let transaction = Transaction { 141 | version: 2, 142 | lock_time: PackedLockTime(0), // TODO: Should we use current time? 143 | input: vec![TxIn { 144 | sequence: Sequence(0), 145 | previous_output: props.outpoint, 146 | script_sig: Script::from(unlocker), 147 | ..Default::default() 148 | }], 149 | output: vec![TxOut { 150 | value: self.swap.bch_amount.to_sat() - mining_fee, 151 | script_pubkey: self.swap.bch_recv.clone(), 152 | token: None, 153 | }], 154 | }; 155 | 156 | return Some(transaction); 157 | } 158 | 159 | None 160 | } 161 | } 162 | 163 | #[async_trait::async_trait] 164 | impl SwapEvents for Alice { 165 | type State = Alice; 166 | 167 | fn transition(mut self, transition: Transition) -> (Self::State, Vec, Option) { 168 | println!("{} - {}", &self.state, &transition); 169 | 170 | let current_state = self.state.clone(); 171 | match (current_state, transition) { 172 | (State::Init, Transition::Msg0 { keys, receiving }) => { 173 | let is_valid_keys = proof::verify(&keys.proof, keys.spend_bch, keys.monero_spend); 174 | if !is_valid_keys { 175 | return (self, vec![Action::SafeDelete], Some(Error::InvalidProof)); 176 | } 177 | 178 | let secp = bitcoincash::secp256k1::Secp256k1::signing_only(); 179 | let contract = ContractPair::create( 180 | 1000, 181 | receiving.clone().into_bytes(), 182 | keys.ves.clone(), 183 | self.swap.bch_recv.to_bytes().clone(), 184 | self.swap.keys.ves.public_key(&secp), 185 | self.swap.timelock1, 186 | self.swap.timelock2, 187 | self.swap.bch_network, 188 | self.swap.bch_amount, 189 | ); 190 | 191 | match contract { 192 | None => return (self, vec![Action::SafeDelete], Some(Error::InvalidTimelock)), 193 | Some(contract) => { 194 | self.state = State::WithBobKeys(Value0 { 195 | bob_bch_recv: receiving.into_bytes(), 196 | contract_pair: contract, 197 | shared_keypair: monero::ViewPair { 198 | view: self.swap.keys.monero_view + keys.monero_view, 199 | spend: monero::PublicKey::from_private_key( 200 | &self.swap.keys.monero_spend, 201 | ) + keys.monero_spend, 202 | }, 203 | bob_keys: keys.into(), 204 | }); 205 | 206 | return (self, vec![], None); 207 | } 208 | } 209 | } 210 | ( 211 | State::WithBobKeys(props), 212 | Transition::Contract { 213 | bch_address, 214 | xmr_address, 215 | }, 216 | ) => { 217 | if props.contract_pair.swaplock.cash_address() != bch_address { 218 | return (self, vec![], Some(Error::InvalidBchAddress)); 219 | } 220 | 221 | let xmr_derived = 222 | monero::Address::from_viewpair(self.swap.xmr_network, &props.shared_keypair); 223 | if xmr_address != xmr_derived { 224 | return (self, vec![], Some(Error::InvalidXmrAddress)); 225 | } 226 | 227 | let refund = props.contract_pair.refund.cash_address(); 228 | self.state = State::ContractMatch(props); 229 | return ( 230 | self, 231 | vec![Action::WatchBchAddress { 232 | swaplock: bch_address, 233 | refund, 234 | }], 235 | None, 236 | ); 237 | } 238 | 239 | (State::ContractMatch(props), Transition::BchConfirmedTx(transaction, _)) => { 240 | match props.contract_pair.analyze_tx(&transaction) { 241 | Some((outpoint, TransactionType::ToSwapLock)) => { 242 | self.state = State::BchLocked(Value1 { 243 | bob_keys: props.bob_keys, 244 | bob_bch_recv: props.bob_bch_recv, 245 | contract_pair: props.contract_pair, 246 | shared_keypair: props.shared_keypair, 247 | 248 | outpoint, 249 | }); 250 | 251 | let xmr_amount = self.swap.xmr_amount; 252 | let address = monero::Address::from_viewpair( 253 | self.swap.xmr_network, 254 | &props.shared_keypair, 255 | ); 256 | return (self, vec![Action::LockXmr(xmr_amount, address)], None); 257 | } 258 | _ => return (self, vec![], Some(Error::InvalidTransaction)), 259 | } 260 | } 261 | 262 | (State::BchLocked(props), Transition::BchConfirmedTx(transaction, _)) => { 263 | if let Some((_, TransactionType::ToBob)) = 264 | props.contract_pair.analyze_tx(&transaction) 265 | { 266 | let script = transaction.input[0].script_sig.clone(); 267 | let decsig = match get_signature(script) { 268 | Some(sig) => { 269 | match ecdsa_fun::Signature::from_bytes(sig.serialize_compact()) { 270 | Some(v) => v, 271 | None => return (self, vec![], Some(Error::InvalidTransaction)), 272 | } 273 | } 274 | _ => return (self, vec![], Some(Error::InvalidTransaction)), 275 | }; 276 | 277 | let bob_spend = AdaptorSignature::recover_decryption_key( 278 | props.bob_keys.spend_bch, 279 | decsig, 280 | self.get_refunc_enc_sig() 281 | .expect("Enc sig should be open at State::BchLocked"), 282 | ); 283 | 284 | let key_pair = monero::KeyPair { 285 | view: props.shared_keypair.view, 286 | spend: self.swap.keys.monero_spend + bob_spend, 287 | }; 288 | 289 | self.state = State::Refund( 290 | monero::Address::from_keypair(self.swap.xmr_network, &key_pair), 291 | key_pair, 292 | ); 293 | 294 | return (self, vec![], None); 295 | } 296 | 297 | return (self, vec![], None); 298 | } 299 | 300 | (State::ValidEncSig(_), Transition::EncSig(_)) => { 301 | return (self, vec![], None); 302 | } 303 | 304 | (State::BchLocked(props), Transition::EncSig(encsig)) => { 305 | let dec_sig = AdaptorSignature::decrypt_signature( 306 | &self.swap.keys.monero_spend, 307 | encsig.clone(), 308 | ); 309 | 310 | { 311 | // ? Check if the message by bob can unlock the swaplock contract 312 | let recv_hash = sha256::hash(&self.swap.bch_recv.to_bytes()).to_byte_array(); 313 | let recv_hash = sha256::hash(&recv_hash).to_byte_array(); 314 | let signer = props.bob_keys.ves.clone(); 315 | 316 | if !AdaptorSignature::verify(signer, &recv_hash, &dec_sig) { 317 | return (self, vec![Action::Refund], Some(Error::InvalidSignature)); 318 | // Todo: procceed to refund 319 | } 320 | } 321 | 322 | let dec_sig = match ecdsa::Signature::from_compact(&dec_sig.to_bytes()) { 323 | Ok(v) => v, 324 | Err(_) => return (self, vec![Action::Refund], Some(Error::InvalidSignature)), 325 | }; 326 | 327 | self.state = State::ValidEncSig(Value2 { 328 | bob_keys: props.bob_keys, 329 | bob_bch_recv: props.bob_bch_recv, 330 | contract_pair: props.contract_pair, 331 | shared_keypair: props.shared_keypair, 332 | outpoint: props.outpoint, 333 | dec_sig, 334 | }); 335 | return (self, vec![Action::UnlockBchNormal], None); 336 | } 337 | (_, _) => return (self, vec![], Some(Error::InvalidStateTransition)), 338 | } 339 | } 340 | 341 | fn get_transition(&self) -> Option { 342 | match &self.state { 343 | State::Init => { 344 | let keys = self.get_public_keys(); 345 | let receiving = self.swap.bch_recv.clone(); 346 | Some(Transition::Msg0 { keys, receiving }) 347 | } 348 | State::WithBobKeys(_) => { 349 | let (bch_address, xmr_address) = self.get_contract().unwrap(); 350 | Some(Transition::Contract { 351 | bch_address, 352 | xmr_address, 353 | }) 354 | } 355 | State::ContractMatch(_) => { 356 | let enc_sig = self.get_refunc_enc_sig().unwrap(); 357 | Some(Transition::EncSig(enc_sig)) 358 | } 359 | _ => None, 360 | } 361 | } 362 | } 363 | 364 | pub struct Runner<'a> { 365 | pub inner: Alice, 366 | pub bch: &'a TcpElectrum, 367 | // pub monerod: &'a monero_rpc::DaemonJsonRpcClient, 368 | // pub monero_wallet: &'a Mutex, 369 | pub min_bch_conf: u32, 370 | } 371 | 372 | impl Runner<'_> { 373 | pub async fn check_bch(&mut self) -> anyhow::Result<()> { 374 | let contract = self.inner.get_contract_pair(); 375 | if let Some(contract) = contract { 376 | let swaplock = contract.swaplock.cash_address(); 377 | let refund = contract.refund.cash_address(); 378 | for address in [swaplock, refund].into_iter() { 379 | let txs = scan_address_conf_tx(&self.bch, &address, self.min_bch_conf).await; 380 | println!("{}txs address {}", txs.len(), address); 381 | for (tx, conf) in txs { 382 | let _ = self 383 | .priv_transition(Transition::BchConfirmedTx(tx, conf)) 384 | .await; 385 | } 386 | } 387 | } 388 | 389 | Ok(()) 390 | } 391 | 392 | pub async fn pub_transition(&mut self, transition: Transition) -> anyhow::Result<()> { 393 | match &transition { 394 | Transition::Msg0 { .. } => {} 395 | Transition::Contract { .. } => {} 396 | Transition::EncSig(_) => {} 397 | _ => bail!("priv transition"), 398 | } 399 | 400 | self.priv_transition(transition).await 401 | } 402 | 403 | pub async fn priv_transition(&mut self, transition: Transition) -> anyhow::Result<()> { 404 | let (new_state, actions, error) = self.inner.clone().transition(transition); 405 | if let Some(err) = error { 406 | bail!(err); 407 | } 408 | 409 | for action in actions { 410 | match action { 411 | Action::LockXmr(amount, addr) => { 412 | let msg = format!(" Send {} to {} ", amount, addr.to_string()); 413 | println!("|{:=^width$}|", "", width = msg.len()); 414 | println!("|{msg}|"); 415 | println!("|{:=^width$}|", "", width = msg.len()); 416 | } 417 | Action::UnlockBchNormal => { 418 | let mut buffer = Vec::new(); 419 | let transaction = new_state.get_unlock_normal_tx().unwrap(); 420 | transaction.consensus_encode(&mut buffer).unwrap(); 421 | let tx_hex: String = buffer.encode_hex(); 422 | 423 | println!("Broadcasting tx. Expected txid: {}", transaction.txid()); 424 | println!("Hex: {}", tx_hex); 425 | let transaction_resp = self 426 | .bch 427 | .send("blockchain.transaction.broadcast", json!([tx_hex])) 428 | .await 429 | .unwrap(); 430 | dbg!(transaction_resp); 431 | } 432 | _ => {} 433 | } 434 | } 435 | 436 | self.inner = new_state; 437 | Ok(()) 438 | } 439 | } 440 | -------------------------------------------------------------------------------- /protocol/src/blockchain/mod.rs: -------------------------------------------------------------------------------- 1 | use std::{collections::HashMap, sync::Arc, time::Duration}; 2 | 3 | use bitcoincash::Transaction; 4 | use serde::Deserialize; 5 | use serde_json::json; 6 | use tokio::{ 7 | io::{self, AsyncBufReadExt, AsyncWriteExt, BufReader}, 8 | net::{ 9 | tcp::{OwnedReadHalf, OwnedWriteHalf}, 10 | TcpStream, 11 | }, 12 | sync::{broadcast, oneshot, Mutex}, 13 | time::sleep, 14 | }; 15 | 16 | #[derive(Deserialize)] 17 | struct HasId { 18 | id: u64, 19 | } 20 | 21 | pub struct TcpElectrum { 22 | futures: Arc>>>, 23 | producer: broadcast::Sender, 24 | 25 | id: Arc>, 26 | stream_write: Arc>, 27 | } 28 | 29 | #[derive(Debug)] 30 | pub enum TcpElectrumError { 31 | IoError(io::Error), 32 | RecvError(oneshot::error::RecvError), 33 | } 34 | 35 | impl std::fmt::Display for TcpElectrumError { 36 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 37 | match self { 38 | Self::IoError(e) => write!(f, "IoError {e}"), 39 | Self::RecvError(e) => write!(f, "RecvError {e}"), 40 | } 41 | } 42 | } 43 | 44 | impl std::error::Error for TcpElectrumError {} 45 | 46 | impl TcpElectrum { 47 | pub fn new(stream: TcpStream) -> Self { 48 | let (producer, _) = broadcast::channel(10); 49 | let (stream_read, stream_write) = stream.into_split(); 50 | 51 | let id = Arc::new(Mutex::new(0)); 52 | let futures = Arc::new(Mutex::new(HashMap::new())); 53 | let stream_write = Arc::new(Mutex::new(stream_write)); 54 | 55 | tokio::spawn({ 56 | let producer = producer.clone(); 57 | let futures = futures.clone(); 58 | async move { 59 | let stream_read = BufReader::new(stream_read); 60 | TcpElectrum::process_reads(stream_read, producer, futures).await; 61 | } 62 | }); 63 | 64 | let server = TcpElectrum { 65 | id, 66 | futures, 67 | producer, 68 | stream_write, 69 | }; 70 | 71 | tokio::spawn({ 72 | let server = server.clone(); 73 | async move { 74 | loop { 75 | let _ = server.send("server.ping", json!([])).await; 76 | sleep(Duration::from_secs(5)).await; 77 | } 78 | } 79 | }); 80 | 81 | server 82 | } 83 | 84 | async fn process_reads( 85 | mut reader: BufReader, 86 | producer: broadcast::Sender, 87 | futures: Arc>>>, 88 | ) { 89 | loop { 90 | let mut buf = String::new(); 91 | let _ = reader.read_line(&mut buf).await.unwrap(); 92 | if buf == "" { 93 | break; 94 | } 95 | 96 | match serde_json::from_str::(&buf) { 97 | Err(_) => { 98 | let _ = producer.send(buf); 99 | } 100 | Ok(HasId { id }) => { 101 | if let Some(recv) = futures.lock().await.remove(&id) { 102 | let _ = recv.send(buf); 103 | } 104 | } 105 | } 106 | } 107 | } 108 | 109 | pub fn subscribe(&self) -> broadcast::Receiver { 110 | self.producer.subscribe() 111 | } 112 | 113 | pub async fn send( 114 | &self, 115 | method: &str, 116 | params: serde_json::Value, 117 | ) -> Result { 118 | let mut guard = self.id.lock().await; 119 | let id = guard.clone(); 120 | *guard += 1; 121 | drop(guard); 122 | 123 | let payload = json!({"id": id, "method": method, "params": params}); 124 | let mut payload = serde_json::to_vec(&payload).unwrap(); 125 | payload.push(b'\n'); 126 | 127 | let (sender, recv) = oneshot::channel(); 128 | let mut guard = self.futures.lock().await; 129 | let _ = guard.insert(id, sender); 130 | drop(guard); 131 | 132 | let mut guard = self.stream_write.lock().await; 133 | let _ = guard 134 | .write(&payload) 135 | .await 136 | .map_err(|e| TcpElectrumError::IoError(e))?; 137 | drop(guard); 138 | 139 | let result = recv.await.map_err(|e| TcpElectrumError::RecvError(e))?; 140 | Ok(result) 141 | } 142 | } 143 | 144 | impl Clone for TcpElectrum { 145 | fn clone(&self) -> Self { 146 | TcpElectrum { 147 | id: self.id.clone(), 148 | futures: self.futures.clone(), 149 | producer: self.producer.clone(), 150 | stream_write: self.stream_write.clone(), 151 | } 152 | } 153 | } 154 | 155 | #[derive(Deserialize)] 156 | pub struct TxInfo0 { 157 | confirmations: u32, 158 | #[serde(with = "hex")] 159 | hex: Vec, 160 | } 161 | 162 | #[derive(Deserialize)] 163 | pub struct TxInfo { 164 | result: TxInfo0, 165 | } 166 | 167 | pub async fn scan_address_conf_tx( 168 | bch_server: &TcpElectrum, 169 | address: &str, 170 | min_conf: u32, 171 | ) -> Vec<(Transaction, u32)> { 172 | let response = bch_server 173 | .send("blockchain.address.get_history", json!([address, true])) 174 | .await 175 | .unwrap(); 176 | 177 | let tx_hashes = serde_json::from_str::(&response).unwrap()["result"] 178 | .as_array() 179 | .unwrap() 180 | .to_owned(); 181 | 182 | let mut txs = Vec::new(); 183 | for tx in tx_hashes { 184 | // in mempool 185 | if tx["height"].as_u64().unwrap() == 0 { 186 | continue; 187 | } 188 | 189 | let tx_hash = tx["tx_hash"].as_str().unwrap(); 190 | let tx_info = bch_server 191 | .send("blockchain.transaction.get", json!([tx_hash, true])) 192 | .await 193 | .unwrap(); 194 | 195 | let tx_info = serde_json::from_str::(&tx_info).unwrap().result; 196 | if tx_info.confirmations < min_conf { 197 | continue; 198 | } 199 | 200 | txs.push(( 201 | bitcoincash::consensus::deserialize::(&tx_info.hex).unwrap(), 202 | tx_info.confirmations, 203 | )); 204 | } 205 | 206 | txs 207 | } 208 | -------------------------------------------------------------------------------- /protocol/src/bob.rs: -------------------------------------------------------------------------------- 1 | use std::{fmt, time::Duration}; 2 | 3 | use anyhow::bail; 4 | use bitcoin_hashes::{sha256::Hash as sha256, Hash}; 5 | use bitcoincash::{ 6 | consensus::Encodable, PackedLockTime, Script, Sequence, Transaction, TxIn, TxOut, 7 | }; 8 | use ecdsa_fun::adaptor::EncryptedSignature; 9 | use hex::ToHex; 10 | use serde::{Deserialize, Serialize}; 11 | use serde_json::json; 12 | use tokio::{sync::Mutex, time::sleep}; 13 | 14 | use crate::{ 15 | adaptor_signature::AdaptorSignature, 16 | bitcoincash::{secp256k1::ecdsa, OutPoint}, 17 | blockchain::{scan_address_conf_tx, TcpElectrum}, 18 | contract::{ContractPair, TransactionType}, 19 | keys::{KeyPublic, KeyPublicWithoutProof}, 20 | proof, 21 | protocol::{Action, Error, Swap, SwapEvents, Transition}, 22 | utils::{get_signature, monero_key_pair, monero_view_pair}, 23 | }; 24 | 25 | #[derive(Debug, Clone, Serialize, Deserialize)] 26 | pub struct Value0 { 27 | alice_keys: KeyPublicWithoutProof, 28 | #[serde(with = "hex")] 29 | alice_bch_recv: Vec, 30 | contract_pair: ContractPair, 31 | #[serde(with = "monero_view_pair")] 32 | pub shared_keypair: monero::ViewPair, 33 | xmr_restore_height: u64, 34 | } 35 | 36 | #[derive(Debug, Clone, Serialize, Deserialize)] 37 | pub struct Value1 { 38 | alice_keys: KeyPublicWithoutProof, 39 | #[serde(with = "hex")] 40 | alice_bch_recv: Vec, 41 | contract_pair: ContractPair, 42 | #[serde(with = "monero_view_pair")] 43 | pub shared_keypair: monero::ViewPair, 44 | xmr_restore_height: u64, 45 | dec_sig: ecdsa::Signature, 46 | } 47 | 48 | #[derive(Debug, Clone, Serialize, Deserialize)] 49 | pub struct Value2 { 50 | alice_keys: KeyPublicWithoutProof, 51 | #[serde(with = "hex")] 52 | alice_bch_recv: Vec, 53 | contract_pair: ContractPair, 54 | #[serde(with = "monero_view_pair")] 55 | shared_keypair: monero::ViewPair, 56 | xmr_restore_height: u64, 57 | dec_sig: ecdsa::Signature, 58 | } 59 | 60 | #[derive(Debug, Clone, Serialize, Deserialize)] 61 | pub struct Value3 { 62 | alice_keys: KeyPublicWithoutProof, 63 | #[serde(with = "hex")] 64 | alice_bch_recv: Vec, 65 | contract_pair: ContractPair, 66 | #[serde(with = "monero_view_pair")] 67 | pub shared_keypair: monero::ViewPair, 68 | xmr_restore_height: u64, 69 | dec_sig: ecdsa::Signature, 70 | outpoint: OutPoint, 71 | } 72 | 73 | #[derive(Debug, Clone, Serialize, Deserialize)] 74 | pub enum State { 75 | Init, 76 | WithAliceKey(Value0), 77 | ContractMatch(Value0), 78 | VerifiedEncSig(Value1), 79 | MoneroLocked(Value2), 80 | ProceedRefund(Value3), 81 | SwapSuccess( 82 | #[serde(with = "monero_key_pair")] monero::KeyPair, 83 | monero::Address, 84 | u64, 85 | ), 86 | } 87 | 88 | impl fmt::Display for State { 89 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 90 | match self { 91 | State::Init => write!(f, "BobState::Init"), 92 | State::WithAliceKey(_) => write!(f, "BobState::WithAliceKey"), 93 | State::ContractMatch(_) => write!(f, "BobState::ContractMatch"), 94 | State::VerifiedEncSig(_) => write!(f, "BobState::VerifiedEncSig"), 95 | State::MoneroLocked(_) => write!(f, "BobState::MoneroLocked"), 96 | State::SwapSuccess(_, _, _) => write!(f, "BobState::SwapSuccess"), 97 | State::ProceedRefund(_) => write!(f, "BobState::ProceedRefund"), 98 | } 99 | } 100 | } 101 | 102 | #[derive(Debug, Clone, Serialize, Deserialize)] 103 | pub struct Bob { 104 | pub state: State, 105 | pub swap: Swap, 106 | } 107 | 108 | impl Bob { 109 | pub fn new(swap: Swap) -> Self { 110 | Bob { 111 | state: State::Init, 112 | swap, 113 | } 114 | } 115 | 116 | pub fn get_public_keys(&self) -> KeyPublic { 117 | KeyPublic::from(self.swap.keys.clone()) 118 | } 119 | 120 | pub fn get_contract(&self) -> Option<(String, monero::Address)> { 121 | let props = match &self.state { 122 | State::WithAliceKey(props) => props, 123 | State::ContractMatch(props) => props, 124 | _ => return None, 125 | }; 126 | 127 | Some(( 128 | props.contract_pair.swaplock.cash_address(), 129 | monero::Address::from_viewpair(self.swap.xmr_network, &props.shared_keypair), 130 | )) 131 | } 132 | 133 | pub fn get_swaplock_enc_sig(&self) -> Option { 134 | if let State::MoneroLocked(props) = &self.state { 135 | let hash = sha256::hash(&props.alice_bch_recv).to_byte_array(); 136 | let hash = sha256::hash(&hash).to_byte_array(); 137 | let enc_sig = AdaptorSignature::encrypted_sign( 138 | &self.swap.keys.ves, 139 | &props.alice_keys.spend_bch, 140 | &hash, 141 | ); 142 | 143 | return Some(enc_sig); 144 | } 145 | 146 | return None; 147 | } 148 | 149 | pub fn get_contract_pair(&self) -> Option { 150 | match self.state.clone() { 151 | State::WithAliceKey(v) => Some(v.contract_pair), 152 | State::ContractMatch(v) => Some(v.contract_pair), 153 | State::VerifiedEncSig(v) => Some(v.contract_pair), 154 | State::MoneroLocked(v) => Some(v.contract_pair), 155 | _ => None, 156 | } 157 | } 158 | 159 | pub fn refund(&self) -> Option<(Transaction, Transaction)> { 160 | if let State::ProceedRefund(props) = &self.state { 161 | let mining_fee = props.contract_pair.mining_fee; 162 | 163 | let tx1 = { 164 | let unlocker = props.contract_pair.swaplock.unlocking_script(&[]); 165 | Transaction { 166 | version: 2, 167 | lock_time: PackedLockTime(0), // TODO: Should we use current time? 168 | input: vec![TxIn { 169 | sequence: Sequence(props.contract_pair.swaplock.timelock), 170 | previous_output: props.outpoint, 171 | script_sig: Script::from(unlocker), 172 | ..Default::default() 173 | }], 174 | output: vec![TxOut { 175 | value: self.swap.bch_amount.to_sat() - mining_fee, 176 | script_pubkey: Script::from(props.contract_pair.refund.locking_script()), 177 | token: None, 178 | }], 179 | } 180 | }; 181 | 182 | let tx2 = { 183 | let unlocker = props 184 | .contract_pair 185 | .refund 186 | .unlocking_script(&props.dec_sig.serialize_der()); 187 | Transaction { 188 | version: 2, 189 | lock_time: PackedLockTime(0), // TODO: Should we use current time? 190 | input: vec![TxIn { 191 | sequence: Sequence(0), 192 | previous_output: OutPoint::new(tx1.txid(), 0), 193 | script_sig: Script::from(unlocker), 194 | ..Default::default() 195 | }], 196 | output: vec![TxOut { 197 | value: self.swap.bch_amount.to_sat() - (mining_fee * 2), 198 | script_pubkey: self.swap.bch_recv.clone(), 199 | token: None, 200 | }], 201 | } 202 | }; 203 | 204 | return Some((tx1, tx2)); 205 | } 206 | 207 | None 208 | } 209 | } 210 | 211 | #[async_trait::async_trait] 212 | impl SwapEvents for Bob { 213 | type State = Bob; 214 | fn transition(mut self, transition: Transition) -> (Self::State, Vec, Option) { 215 | println!("{} - {}", &self.state, &transition); 216 | 217 | if let Transition::SetXmrRestoreHeight(height) = transition { 218 | match &mut self.state { 219 | State::WithAliceKey(ref mut v) => v.xmr_restore_height = height, 220 | State::ContractMatch(ref mut v) => v.xmr_restore_height = height, 221 | State::VerifiedEncSig(ref mut v) => v.xmr_restore_height = height, 222 | State::MoneroLocked(ref mut v) => v.xmr_restore_height = height, 223 | _ => {} 224 | } 225 | return (self, vec![], None); 226 | } 227 | 228 | match (self.state.clone(), transition) { 229 | (State::Init, Transition::Msg0 { keys, receiving }) => { 230 | let is_valid_keys = proof::verify(&keys.proof, keys.spend_bch, keys.monero_spend); 231 | 232 | if !is_valid_keys { 233 | return (self, vec![Action::SafeDelete], Some(Error::InvalidProof)); 234 | } 235 | 236 | let secp = bitcoincash::secp256k1::Secp256k1::signing_only(); 237 | let contract_pair = ContractPair::create( 238 | 1000, 239 | self.swap.bch_recv.clone().into_bytes(), 240 | self.swap.keys.ves.public_key(&secp), 241 | receiving.clone().into_bytes(), 242 | keys.ves.clone(), 243 | self.swap.timelock1, 244 | self.swap.timelock2, 245 | self.swap.bch_network, 246 | self.swap.bch_amount, 247 | ); 248 | 249 | match contract_pair { 250 | None => return (self, vec![Action::SafeDelete], Some(Error::InvalidTimelock)), 251 | Some(contract_pair) => { 252 | let shared_keypair = monero::ViewPair { 253 | view: self.swap.keys.monero_view + keys.monero_view, 254 | spend: monero::PublicKey::from_private_key( 255 | &self.swap.keys.monero_spend, 256 | ) + keys.monero_spend, 257 | }; 258 | 259 | self.state = State::WithAliceKey(Value0 { 260 | alice_bch_recv: receiving.into_bytes(), 261 | contract_pair, 262 | 263 | shared_keypair, 264 | alice_keys: keys.into(), 265 | xmr_restore_height: 0, 266 | }); 267 | 268 | return (self, vec![Action::CreateXmrView(shared_keypair)], None); 269 | } 270 | } 271 | } 272 | ( 273 | State::WithAliceKey(props), 274 | Transition::Contract { 275 | bch_address, 276 | xmr_address, 277 | }, 278 | ) => { 279 | if props.contract_pair.swaplock.cash_address() != bch_address { 280 | return (self, vec![], Some(Error::InvalidBchAddress)); 281 | } 282 | 283 | let xmr_derived = 284 | monero::Address::from_viewpair(self.swap.xmr_network, &props.shared_keypair); 285 | if xmr_address != xmr_derived { 286 | return (self, vec![], Some(Error::InvalidXmrAddress)); 287 | } 288 | 289 | self.state = State::ContractMatch(props); 290 | return (self, vec![], None); 291 | } 292 | 293 | (State::ContractMatch(props), Transition::EncSig(enc_sig)) => { 294 | // check if decrypted sig can unlock Refund.cash contract 295 | let bob_receiving_hash = 296 | sha256::hash(self.swap.bch_recv.as_bytes()).to_byte_array(); 297 | let bob_receiving_hash = sha256::hash(&bob_receiving_hash).to_byte_array(); 298 | let dec_sig = 299 | AdaptorSignature::decrypt_signature(&self.swap.keys.monero_spend, enc_sig); 300 | 301 | let is_valid = AdaptorSignature::verify( 302 | props.alice_keys.ves.clone(), 303 | &bob_receiving_hash, 304 | &dec_sig, 305 | ); 306 | 307 | if !is_valid { 308 | return ( 309 | self, 310 | vec![Action::SafeDelete], 311 | Some(Error::InvalidSignature), 312 | ); 313 | } 314 | 315 | let dec_sig = match ecdsa::Signature::from_compact(&dec_sig.to_bytes()) { 316 | Ok(v) => v, 317 | Err(_) => { 318 | return ( 319 | self, 320 | vec![Action::SafeDelete], 321 | Some(Error::InvalidSignature), 322 | ) 323 | } 324 | }; 325 | 326 | let (bch_address, xmr_address) = self.get_contract().unwrap(); 327 | 328 | self.state = State::VerifiedEncSig(Value1 { 329 | alice_bch_recv: props.alice_bch_recv, 330 | contract_pair: props.contract_pair, 331 | shared_keypair: props.shared_keypair, 332 | alice_keys: props.alice_keys, 333 | xmr_restore_height: props.xmr_restore_height, 334 | 335 | dec_sig, 336 | }); 337 | let bch_amount = self.swap.bch_amount; 338 | return ( 339 | self, 340 | vec![ 341 | Action::LockBch(bch_amount, bch_address), 342 | Action::WatchXmr(xmr_address), 343 | ], 344 | None, 345 | ); 346 | } 347 | 348 | (State::VerifiedEncSig(props), Transition::XmrLockVerified(amount)) => { 349 | if amount != self.swap.xmr_amount { 350 | return (self, vec![], Some(Error::InvalidXmrAmount)); 351 | } 352 | 353 | self.state = State::MoneroLocked(Value2 { 354 | alice_keys: props.alice_keys, 355 | alice_bch_recv: props.alice_bch_recv, 356 | contract_pair: props.contract_pair, 357 | shared_keypair: props.shared_keypair, 358 | dec_sig: props.dec_sig, 359 | xmr_restore_height: props.xmr_restore_height, 360 | }); 361 | return (self, vec![], None); 362 | } 363 | 364 | (State::VerifiedEncSig(props), Transition::BchConfirmedTx(transaction, conf)) => { 365 | // The runner are still giving prev transaction while alice havent lock xmr 366 | // we use it to track if tx sent to swaplock has enough age for refund 367 | 368 | match props.contract_pair.analyze_tx(&transaction) { 369 | // When timelock1 expire 370 | Some((outpoint, TransactionType::ToSwapLock)) => { 371 | if conf < self.swap.timelock1 { 372 | return (self, vec![], None); 373 | } 374 | 375 | self.state = State::ProceedRefund(Value3 { 376 | alice_keys: props.alice_keys, 377 | alice_bch_recv: props.alice_bch_recv, 378 | contract_pair: props.contract_pair, 379 | shared_keypair: props.shared_keypair, 380 | dec_sig: props.dec_sig, 381 | xmr_restore_height: props.xmr_restore_height, 382 | outpoint, 383 | }); 384 | 385 | return (self, vec![Action::UnlockBchFallback], None); 386 | } 387 | // when tx send to refund 388 | Some((outpoint, TransactionType::ToRefund)) => { 389 | self.state = State::ProceedRefund(Value3 { 390 | alice_keys: props.alice_keys, 391 | alice_bch_recv: props.alice_bch_recv, 392 | contract_pair: props.contract_pair, 393 | shared_keypair: props.shared_keypair, 394 | dec_sig: props.dec_sig, 395 | xmr_restore_height: props.xmr_restore_height, 396 | outpoint, 397 | }); 398 | return (self, vec![Action::UnlockBchFallback], None); 399 | } 400 | _ => return (self, vec![], None), 401 | } 402 | } 403 | 404 | (State::MoneroLocked(props), Transition::BchConfirmedTx(transaction, _)) => { 405 | let scriptsig = match props.contract_pair.analyze_tx(&transaction) { 406 | Some((_, TransactionType::SwapLockToAlice)) => { 407 | transaction.input[0].script_sig.clone() 408 | } 409 | _ => return (self, vec![], Some(Error::InvalidTransaction)), 410 | }; 411 | 412 | let decsig = match get_signature(scriptsig) { 413 | Some(sig) => sig, 414 | None => return (self, vec![], Some(Error::InvalidTransaction)), 415 | }; 416 | 417 | let decsig = match ecdsa_fun::Signature::from_bytes(decsig.serialize_compact()) { 418 | Some(v) => v, 419 | None => return (self, vec![], Some(Error::InvalidTransaction)), 420 | }; 421 | 422 | let alice_spend = AdaptorSignature::recover_decryption_key( 423 | props.alice_keys.spend_bch, 424 | decsig, 425 | self.get_swaplock_enc_sig() 426 | .expect("Enc sig should be open at current state"), 427 | ); 428 | 429 | let key_pair = monero::KeyPair { 430 | view: props.shared_keypair.view, 431 | spend: self.swap.keys.monero_spend + alice_spend, 432 | }; 433 | 434 | self.state = State::SwapSuccess( 435 | key_pair, 436 | monero::Address::from_keypair(self.swap.xmr_network, &key_pair), 437 | props.xmr_restore_height, 438 | ); 439 | 440 | return (self, vec![Action::TradeSuccess], None); 441 | } 442 | 443 | (_, _) => return (self, vec![], Some(Error::InvalidStateTransition)), 444 | } 445 | } 446 | 447 | fn get_transition(&self) -> Option { 448 | match &self.state { 449 | State::Init => None, 450 | State::WithAliceKey(_) => { 451 | let keys = self.get_public_keys(); 452 | let receiving = self.swap.bch_recv.clone(); 453 | Some(Transition::Msg0 { keys, receiving }) 454 | } 455 | State::ContractMatch(_) => { 456 | let (bch_address, xmr_address) = self.get_contract().unwrap(); 457 | Some(Transition::Contract { 458 | bch_address, 459 | xmr_address, 460 | }) 461 | } 462 | State::MoneroLocked(_) => { 463 | let enc_sig = self.get_swaplock_enc_sig().unwrap(); 464 | Some(Transition::EncSig(enc_sig)) 465 | } 466 | _ => None, 467 | } 468 | } 469 | } 470 | 471 | pub struct Runner<'a> { 472 | pub inner: Bob, 473 | pub trade_id: String, 474 | pub bch: &'a TcpElectrum, 475 | pub monerod: &'a monero_rpc::DaemonJsonRpcClient, 476 | pub monero_wallet: &'a Mutex, 477 | pub min_bch_conf: u32, 478 | } 479 | 480 | impl Runner<'_> { 481 | pub async fn check_xmr(&mut self) -> anyhow::Result<()> { 482 | let monero_wallet = self.monero_wallet.lock().await; 483 | monero_wallet 484 | .open_wallet(format!("{}_view", self.trade_id), Some("".to_owned())) 485 | .await?; 486 | 487 | let balance = monero_wallet.get_balance(0, None).await?; 488 | drop(monero_wallet); 489 | 490 | println!( 491 | "[{}]: Balance: {} Unlocked: {} Expected: {}", 492 | self.trade_id, balance.balance, balance.unlocked_balance, self.inner.swap.xmr_amount 493 | ); 494 | 495 | let balance = match self.inner.swap.xmr_network { 496 | monero::Network::Mainnet => balance.unlocked_balance, 497 | _ => balance.balance, 498 | }; 499 | 500 | if balance != self.inner.swap.xmr_amount { 501 | return Ok(()); 502 | } 503 | 504 | let _ = self 505 | .priv_transition(Transition::XmrLockVerified(balance)) 506 | .await; 507 | Ok(()) 508 | } 509 | 510 | pub async fn check_bch(&mut self) -> anyhow::Result<()> { 511 | let contract = self.inner.get_contract_pair(); 512 | if let Some(contract) = contract { 513 | let swaplock = contract.swaplock.cash_address(); 514 | let refund = contract.refund.cash_address(); 515 | for address in [swaplock, refund].into_iter() { 516 | let txs = scan_address_conf_tx(&self.bch, &address, self.min_bch_conf).await; 517 | println!("[{}]: {}txs address {}", self.trade_id, txs.len(), address); 518 | for (tx, conf) in txs { 519 | let check_bch = self 520 | .priv_transition(Transition::BchConfirmedTx(tx, conf)) 521 | .await; 522 | if let Err(check_bch_err) = check_bch { 523 | dbg!(check_bch_err); 524 | } 525 | } 526 | } 527 | } 528 | 529 | Ok(()) 530 | } 531 | 532 | pub async fn pub_transition(&mut self, transition: Transition) -> anyhow::Result<()> { 533 | match &transition { 534 | Transition::Msg0 { .. } => {} 535 | Transition::Contract { .. } => {} 536 | Transition::EncSig(_) => {} 537 | _ => bail!("priv transition"), 538 | } 539 | 540 | self.priv_transition(transition).await 541 | } 542 | 543 | pub async fn priv_transition(&mut self, transition: Transition) -> anyhow::Result<()> { 544 | let (mut new_state, actions, error) = self.inner.clone().transition(transition); 545 | if let Some(err) = error { 546 | bail!(err); 547 | } 548 | 549 | for action in actions { 550 | match action { 551 | Action::CreateXmrView(keypair) => { 552 | let address = 553 | monero::Address::from_viewpair(self.inner.swap.xmr_network, &keypair); 554 | let height = self.monerod.get_block_count().await?.get(); 555 | 556 | let monero_wallet = self.monero_wallet.lock().await; 557 | let _ = monero_wallet 558 | .generate_from_keys(monero_rpc::GenerateFromKeysArgs { 559 | address, 560 | restore_height: Some(height), 561 | autosave_current: Some(true), 562 | filename: format!("{}_view", self.trade_id), 563 | password: "".to_owned(), 564 | spendkey: None, 565 | viewkey: keypair.view, 566 | }) 567 | .await?; 568 | monero_wallet.close_wallet().await?; 569 | new_state = new_state 570 | .transition(Transition::SetXmrRestoreHeight(height)) 571 | .0; 572 | } 573 | Action::LockBch(amount, addr) => { 574 | let msg = format!(" Send {} to {} ", amount, addr); 575 | println!("|{:=^width$}|", "", width = msg.len()); 576 | println!("|{msg}|"); 577 | println!("|{:=^width$}|", "", width = msg.len()); 578 | } 579 | Action::UnlockBchFallback => { 580 | let (tx1, tx2) = new_state.refund().unwrap(); 581 | 582 | let mut buffer = Vec::new(); 583 | tx1.consensus_encode(&mut buffer).unwrap(); 584 | let tx_hex: String = buffer.encode_hex(); 585 | 586 | println!("Broadcasting tx. SwapLock -> Refund: {}", tx1.txid()); 587 | let transaction_resp = self 588 | .bch 589 | .send("blockchain.transaction.broadcast", json!([tx_hex])) 590 | .await 591 | .unwrap(); 592 | dbg!(transaction_resp); 593 | 594 | sleep(Duration::from_secs(5)).await; 595 | 596 | let mut buffer = Vec::new(); 597 | tx2.consensus_encode(&mut buffer).unwrap(); 598 | let tx_hex: String = buffer.encode_hex(); 599 | 600 | println!("Broadcasting tx. Refund -> Bob Output: {}", tx2.txid()); 601 | let transaction_resp = self 602 | .bch 603 | .send("blockchain.transaction.broadcast", json!([tx_hex])) 604 | .await 605 | .unwrap(); 606 | dbg!(transaction_resp); 607 | } 608 | _ => {} 609 | } 610 | } 611 | 612 | self.inner = new_state; 613 | Ok(()) 614 | } 615 | } 616 | -------------------------------------------------------------------------------- /protocol/src/contract/mod.rs: -------------------------------------------------------------------------------- 1 | use bitcoin_hashes::{hash160, Hash}; 2 | use bitcoincash::{ 3 | blockdata::{ 4 | opcodes, 5 | script::{Builder, Instruction}, 6 | }, 7 | hashes::Hash as BHash, 8 | Script, ScriptHash, Transaction, 9 | }; 10 | use serde::{Deserialize, Serialize}; 11 | 12 | use crate::keys::bitcoin::{address, Network}; 13 | 14 | const CONTRACT_BYTECODE: [u8; 47] = hex_literal::hex!("c3519dc4519d00c600cc949d00cb009c6300cd7888547978a85379bb675279b27500cd54798854790088686d6d7551"); 15 | const SEQUENCE_LOCKTIME_MASK: u32 = 0x0000ffff; // bip68 16 | 17 | #[derive(Debug)] 18 | pub enum TransactionType { 19 | ToSwapLock, 20 | ToRefund, 21 | ToBob, 22 | SwapLockToAlice, 23 | RefundToAlice, 24 | } 25 | 26 | #[derive(Debug, Clone, Serialize, Deserialize)] 27 | pub struct Contract { 28 | pub mining_fee: u64, 29 | #[serde(with = "hex")] 30 | pub success_output: Vec, 31 | pub pubkey_ves: bitcoincash::PublicKey, 32 | pub timelock: u32, 33 | #[serde(with = "hex")] 34 | pub failed_output: Vec, 35 | 36 | pub bch_network: Network, 37 | 38 | // allow others to read struct field, but not creation 39 | // We need to check given timelock. SEQUENCE_LOCKTIME_MASK 40 | _private: (), 41 | } 42 | 43 | impl Contract { 44 | pub fn script(&self) -> Vec { 45 | let mut contract = Builder::new() 46 | .push_slice(&self.failed_output) 47 | .push_int(self.timelock as i64) 48 | .push_key(&self.pubkey_ves) 49 | .push_slice(&self.success_output) 50 | .push_int(self.mining_fee as i64) 51 | .into_script() 52 | .to_bytes(); 53 | 54 | contract.extend_from_slice(&CONTRACT_BYTECODE); 55 | contract 56 | } 57 | 58 | #[inline] 59 | pub fn script_hash(&self) -> [u8; 20] { 60 | hash160::Hash::hash(&self.script()).to_byte_array() 61 | } 62 | 63 | // ? Idk returning raw script becomes error for caller, 64 | // ? we need to convert to bytes, then caller need to convert back to script 65 | pub fn locking_script(&self) -> Vec { 66 | let hash = self.script_hash(); 67 | Builder::new() 68 | .push_opcode(opcodes::all::OP_HASH160) 69 | .push_slice(&hash) 70 | .push_opcode(opcodes::all::OP_EQUAL) 71 | .into_script() 72 | .to_bytes() 73 | } 74 | 75 | // ? Idk returning raw script becomes error for caller, 76 | // ?we need to convert to bytes, then caller need to convert back to script 77 | pub fn unlocking_script(&self, unlocker: &[u8]) -> Vec { 78 | let locking = self.script(); 79 | 80 | Builder::new() 81 | .push_slice(unlocker) 82 | .push_slice(&locking) 83 | .into_script() 84 | .to_bytes() 85 | } 86 | 87 | pub fn cash_address(&self) -> String { 88 | let hash = self.script_hash(); 89 | match self.bch_network { 90 | Network::Mainnet => address::encode(&hash, "bitcoincash", 8), 91 | Network::Testnet => address::encode(&hash, "bchtest", 8), 92 | Network::Regtest => address::encode(&hash, "bchreg", 8), 93 | } 94 | } 95 | } 96 | 97 | #[derive(Debug, Clone, Serialize, Deserialize)] 98 | pub struct ContractPair { 99 | pub swaplock: Contract, 100 | pub refund: Contract, 101 | alice_receiving: Vec, 102 | bob_receiving: Vec, 103 | swaplock_in_sats: u64, 104 | pub mining_fee: u64, 105 | bch_network: Network, 106 | } 107 | 108 | impl ContractPair { 109 | // None variant is timelock > SEQUENCE_LOCKTIME_MASK 110 | pub fn create( 111 | mining_fee: u64, 112 | bob_receiving: Vec, 113 | bob_pubkey_ves: bitcoincash::PublicKey, 114 | alice_receiving: Vec, 115 | alice_pubkey_ves: bitcoincash::PublicKey, 116 | timelock0: u32, 117 | timelock1: u32, 118 | bch_network: Network, 119 | swaplock_in: bitcoincash::Amount, 120 | ) -> Option { 121 | if timelock0 > SEQUENCE_LOCKTIME_MASK || timelock1 > SEQUENCE_LOCKTIME_MASK { 122 | return None; 123 | } 124 | 125 | let refund = Contract { 126 | mining_fee, 127 | success_output: bob_receiving.clone(), 128 | pubkey_ves: alice_pubkey_ves, 129 | timelock: timelock1, 130 | failed_output: alice_receiving.clone(), 131 | bch_network, 132 | _private: (), 133 | }; 134 | 135 | let swaplock = Contract { 136 | mining_fee, 137 | success_output: alice_receiving.clone(), 138 | pubkey_ves: bob_pubkey_ves, 139 | timelock: timelock0, 140 | failed_output: refund.locking_script(), 141 | bch_network, 142 | _private: (), 143 | }; 144 | 145 | Some(ContractPair { 146 | swaplock, 147 | refund, 148 | alice_receiving, 149 | bob_receiving, 150 | swaplock_in_sats: swaplock_in.to_sat(), 151 | mining_fee, 152 | bch_network, 153 | }) 154 | } 155 | 156 | pub fn analyze_tx( 157 | &self, 158 | transaction: &Transaction, 159 | ) -> Option<(bitcoincash::OutPoint, TransactionType)> { 160 | let swaplock = self.swaplock.locking_script(); 161 | let refund = self.refund.locking_script(); 162 | 163 | if transaction.input.len() == 1 && transaction.output.len() == 1 { 164 | let outpoint = bitcoincash::OutPoint::new(transaction.txid(), 0); 165 | let input = &transaction.input[0]; 166 | 167 | let output = &transaction.output[0]; 168 | let output_bytes = output.script_pubkey.to_bytes(); 169 | 170 | let input_bytes = { 171 | match input.script_sig.clone().instructions().last() { 172 | Some(Ok(Instruction::PushBytes(bytes))) => { 173 | let script_hash = ScriptHash::hash(&bytes); 174 | Script::new_p2sh(&script_hash).to_bytes() 175 | } 176 | _ => input.script_sig.to_p2sh().to_bytes(), 177 | } 178 | }; 179 | 180 | // check for dummy tx 181 | if input_bytes == swaplock && output.value == self.swaplock_in_sats - self.mining_fee { 182 | if output_bytes == self.alice_receiving { 183 | return Some((outpoint, TransactionType::SwapLockToAlice)); 184 | } else if output_bytes == refund { 185 | return Some((outpoint, TransactionType::ToRefund)); 186 | } 187 | } 188 | 189 | if input_bytes == refund 190 | && output.value == self.swaplock_in_sats - (self.mining_fee * 2) 191 | { 192 | if output_bytes == self.bob_receiving { 193 | return Some((outpoint, TransactionType::ToBob)); 194 | } else if output_bytes == self.alice_receiving { 195 | return Some((outpoint, TransactionType::RefundToAlice)); 196 | } 197 | } 198 | } 199 | 200 | for (vout, out) in transaction.output.iter().enumerate() { 201 | if out.script_pubkey.to_bytes() == swaplock && out.value == self.swaplock_in_sats { 202 | return Some(( 203 | bitcoincash::OutPoint::new(transaction.txid(), vout as u32), 204 | TransactionType::ToSwapLock, 205 | )); 206 | } 207 | } 208 | 209 | return None; 210 | } 211 | } 212 | 213 | #[cfg(test)] 214 | mod test { 215 | use std::str::FromStr; 216 | 217 | use crate::contract::Contract; 218 | 219 | #[test] 220 | fn should_have_correct_address() { 221 | let pubkey_ves = bitcoincash::PublicKey::from_str( 222 | "02ee2cbe75e3d2a9b5049ac73122c229627a49bd289f71e05075b2c60090766128", 223 | ) 224 | .unwrap(); 225 | let output = hex::decode("76a91447fe8a0ca161ebc0090c9d46f81582c579c594a788ac").unwrap(); 226 | 227 | let refund = Contract { 228 | mining_fee: 1000, 229 | success_output: output.clone(), 230 | pubkey_ves, 231 | timelock: 1000, 232 | failed_output: output, 233 | bch_network: crate::keys::bitcoin::Network::Testnet, 234 | _private: (), 235 | }; 236 | 237 | assert_eq!( 238 | refund.cash_address(), 239 | "bitcoincash:prmnwxmmaq58h22jt7qrjmutnkrmrfm4j57zy4cf45" 240 | ); 241 | } 242 | } 243 | -------------------------------------------------------------------------------- /protocol/src/keys/bitcoin/address.rs: -------------------------------------------------------------------------------- 1 | pub fn encode(hash: &[u8], prefix: &str, version_bit: u8) -> String { 2 | let mut payload: Vec = vec![version_bit]; 3 | payload.extend_from_slice(hash); 4 | 5 | let mut payload = bech32::convert_bits(&payload, 8, 5, true).unwrap(); 6 | let checksum = calculate_checksum(&prefix, &payload); 7 | payload.extend_from_slice(&checksum); 8 | 9 | format!("{}:{}", prefix, b32encode(&payload)) 10 | } 11 | 12 | fn polymod(v: &[u8]) -> u64 { 13 | let mut c: u64 = 1; 14 | 15 | for &d in v { 16 | let c0: u8 = (c >> 35) as u8; 17 | c = ((c & 0x07ffffffff) << 5) ^ u64::from(d); 18 | 19 | if (c0 & 0x01) != 0 { 20 | c ^= 0x98f2bc8e61; 21 | } 22 | if (c0 & 0x02) != 0 { 23 | c ^= 0x79b76d99e2; 24 | } 25 | if (c0 & 0x04) != 0 { 26 | c ^= 0xf33e5fb3c4; 27 | } 28 | if (c0 & 0x08) != 0 { 29 | c ^= 0xae2eabe2a8; 30 | } 31 | if (c0 & 0x10) != 0 { 32 | c ^= 0x1e4f43e470; 33 | } 34 | } 35 | 36 | return c ^ 1; 37 | // c 38 | } 39 | 40 | fn prefix_expand(prefix: &str) -> Vec { 41 | let mut expanded_prefix: Vec = prefix.bytes().map(|x| (x & 0x1F) as u8).collect(); 42 | expanded_prefix.push(0); 43 | 44 | expanded_prefix 45 | } 46 | 47 | fn calculate_checksum(prefix: &str, payload: &[u8]) -> Vec { 48 | let mut combined_data = prefix_expand(&prefix); 49 | combined_data.extend_from_slice(&payload); 50 | combined_data.extend_from_slice(&[0, 0, 0, 0, 0, 0, 0, 0]); 51 | 52 | let poly = polymod(&combined_data); 53 | 54 | let mut out = Vec::new(); 55 | for i in 0..8 { 56 | // out.push(((poly >> (5 * i)) & 0x1F) as u8); 57 | out.push(((poly >> 5 * (7 - i)) & 0x1F) as u8); 58 | } 59 | 60 | out 61 | } 62 | 63 | const CHARSET: [char; 32] = [ 64 | 'q', 'p', 'z', 'r', 'y', '9', 'x', '8', // +0 65 | 'g', 'f', '2', 't', 'v', 'd', 'w', '0', // +8 66 | 's', '3', 'j', 'n', '5', '4', 'k', 'h', // +16 67 | 'c', 'e', '6', 'm', 'u', 'a', '7', 'l', // +24 68 | ]; 69 | 70 | fn b32encode(inputs: &[u8]) -> String { 71 | let mut out = String::new(); 72 | 73 | for &char_code in inputs { 74 | out.push(CHARSET[char_code as usize]); 75 | } 76 | 77 | out 78 | } 79 | -------------------------------------------------------------------------------- /protocol/src/keys/bitcoin/mod.rs: -------------------------------------------------------------------------------- 1 | use ecdsa_fun::fun::Scalar; 2 | use serde::{Deserialize, Serialize}; 3 | 4 | pub mod address; 5 | 6 | #[derive(Debug, Clone, Copy, Serialize, Deserialize)] 7 | pub enum Network { 8 | Mainnet, 9 | Testnet, 10 | Regtest, 11 | } 12 | 13 | pub fn random_private_key(network: Network) -> bitcoincash::PrivateKey { 14 | let mut rng = rand::thread_rng(); 15 | let scalar = Scalar::random(&mut rng); 16 | 17 | let network = match network { 18 | Network::Mainnet => bitcoincash::Network::Bitcoin, 19 | Network::Testnet => bitcoincash::Network::Testnet, 20 | Network::Regtest => bitcoincash::Network::Regtest, 21 | }; 22 | bitcoincash::PrivateKey::from_slice(&scalar.to_bytes(), network).unwrap() 23 | } 24 | 25 | -------------------------------------------------------------------------------- /protocol/src/keys/mod.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::Debug; 2 | 3 | use serde::{Deserialize, Serialize}; 4 | use sigma_fun::{ 5 | ed25519::curve25519_dalek::scalar::Scalar, ext::dl_secp256k1_ed25519_eq::CrossCurveDLEQProof, 6 | }; 7 | 8 | use self::bitcoin::random_private_key; 9 | use crate::{ 10 | proof, 11 | utils::{monero_private_key, monero_public_key}, 12 | }; 13 | 14 | pub mod bitcoin; 15 | 16 | #[derive(Debug, Clone, Serialize, Deserialize)] 17 | pub struct KeyPrivate { 18 | #[serde(with = "monero_private_key")] 19 | pub monero_spend: monero::PrivateKey, 20 | #[serde(with = "monero_private_key")] 21 | pub monero_view: monero::PrivateKey, 22 | pub ves: bitcoincash::PrivateKey, 23 | } 24 | 25 | impl KeyPrivate { 26 | pub fn random(network: bitcoin::Network) -> KeyPrivate { 27 | let mut rng = rand::thread_rng(); 28 | let monero_spend = Scalar::random(&mut rng); 29 | let monero_view = Scalar::random(&mut rng); 30 | Self { 31 | monero_spend: monero::PrivateKey::from_slice(monero_spend.as_bytes()).unwrap(), 32 | monero_view: monero::PrivateKey::from_slice(monero_view.as_bytes()).unwrap(), 33 | ves: random_private_key(network), 34 | } 35 | } 36 | } 37 | 38 | #[derive(Clone, Serialize, Deserialize)] 39 | pub struct KeyPublic { 40 | #[serde(with = "monero_public_key")] 41 | pub monero_spend: monero::PublicKey, 42 | #[serde(with = "monero_private_key")] 43 | pub monero_view: monero::PrivateKey, 44 | pub ves: bitcoincash::PublicKey, 45 | 46 | pub spend_bch: bitcoincash::PublicKey, 47 | pub proof: CrossCurveDLEQProof, 48 | } 49 | 50 | impl From for KeyPublic { 51 | fn from(value: KeyPrivate) -> Self { 52 | let (proof, (spend_bch, _)) = proof::prove(&value.monero_spend); 53 | let secp = bitcoincash::secp256k1::Secp256k1::signing_only(); 54 | KeyPublic { 55 | monero_spend: monero::PublicKey::from_private_key(&value.monero_spend), 56 | monero_view: value.monero_view, 57 | ves: value.ves.public_key(&secp), 58 | spend_bch, 59 | proof, 60 | } 61 | } 62 | } 63 | 64 | impl Debug for KeyPublic { 65 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 66 | write!( 67 | f, 68 | "KeyPublic {{\n\ 69 | \tmonero_spend: monero::PublicKey({}),\n\ 70 | \tmonero_view: monero::PrivateKey({}),\n\ 71 | \tves: bitcoincash::PublicKey({}),\n\ 72 | \tspend_bch: bitcoincash::PublicKey({}),\n\ 73 | }} \n\ 74 | ", 75 | self.monero_spend, self.monero_view, self.ves, self.spend_bch 76 | ) 77 | } 78 | } 79 | 80 | #[derive(Debug, Clone, Serialize, Deserialize)] 81 | pub struct KeyPublicWithoutProof { 82 | #[serde(with = "monero_public_key")] 83 | pub monero_spend: monero::PublicKey, 84 | #[serde(with = "monero_private_key")] 85 | pub monero_view: monero::PrivateKey, 86 | pub ves: bitcoincash::PublicKey, 87 | 88 | pub spend_bch: bitcoincash::PublicKey, 89 | } 90 | 91 | impl From for KeyPublicWithoutProof { 92 | fn from(value: KeyPublic) -> Self { 93 | KeyPublicWithoutProof { 94 | monero_spend: value.monero_spend, 95 | monero_view: value.monero_view, 96 | ves: value.ves, 97 | spend_bch: value.spend_bch, 98 | } 99 | } 100 | } 101 | 102 | #[cfg(test)] 103 | mod test { 104 | use monero::ViewPair; 105 | 106 | /// Our assumption on monero keys: 107 | /// 108 | /// alice_public + bob_public = shared_public 109 | /// alice_private + bob_private = shared_private 110 | /// monero::PublicKey::from_private_key(shared_private) == shared_public 111 | 112 | #[test] 113 | fn test() { 114 | let bob = { 115 | use sigma_fun::ed25519::curve25519_dalek::scalar::Scalar; 116 | 117 | let mut rng = rand::thread_rng(); 118 | let priv_spend = Scalar::random(&mut rng); 119 | let p_spend = monero::PrivateKey::from_slice(&priv_spend.to_bytes()).unwrap(); 120 | let p_view = monero::PrivateKey::from_slice(&priv_spend.to_bytes()).unwrap(); 121 | 122 | let address = monero::Address::from_viewpair( 123 | monero::Network::Stagenet, 124 | &ViewPair { 125 | spend: monero::PublicKey::from_private_key(&p_spend), 126 | view: p_view, 127 | }, 128 | ); 129 | 130 | (p_spend, p_view, address) 131 | }; 132 | 133 | let alice = { 134 | use sigma_fun::ed25519::curve25519_dalek::scalar::Scalar; 135 | 136 | let mut rng = rand::thread_rng(); 137 | let priv_spend = Scalar::random(&mut rng); 138 | let p_spend = monero::PrivateKey::from_slice(&priv_spend.to_bytes()).unwrap(); 139 | let p_view = monero::PrivateKey::from_slice(&priv_spend.to_bytes()).unwrap(); 140 | 141 | let address = monero::Address::from_viewpair( 142 | monero::Network::Stagenet, 143 | &ViewPair { 144 | spend: monero::PublicKey::from_private_key(&p_spend), 145 | view: p_view, 146 | }, 147 | ); 148 | 149 | (p_spend, p_view, address) 150 | }; 151 | 152 | let add_priv_spend = bob.0 + alice.0; 153 | let add_priv_spend_pub = monero::PublicKey::from_private_key(&add_priv_spend); 154 | 155 | let add_pub_spend = monero::PublicKey::from_private_key(&bob.0) 156 | + monero::PublicKey::from_private_key(&alice.0); 157 | 158 | assert_eq!(add_priv_spend_pub, add_pub_spend); 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /protocol/src/lib.rs: -------------------------------------------------------------------------------- 1 | // #![allow(dead_code, unused_imports, unused_variables)] 2 | 3 | pub mod adaptor_signature; 4 | pub mod alice; 5 | pub mod blockchain; 6 | pub mod bob; 7 | pub mod contract; 8 | pub mod keys; 9 | pub mod persist; 10 | pub mod proof; 11 | pub mod protocol; 12 | pub(crate) mod utils; 13 | 14 | pub use bitcoincash; 15 | pub use monero; 16 | pub use monero_rpc; 17 | pub use rand; 18 | -------------------------------------------------------------------------------- /protocol/src/persist.rs: -------------------------------------------------------------------------------- 1 | use std::io::ErrorKind; 2 | 3 | use fs4::tokio::AsyncFileExt; 4 | use serde::{Deserialize, Serialize}; 5 | use tokio::{ 6 | fs::{self, File}, 7 | io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt}, 8 | }; 9 | 10 | use crate::protocol::SwapWrapper; 11 | 12 | #[derive(Debug)] 13 | pub enum Error { 14 | NotFound, 15 | Unknown(String), 16 | } 17 | 18 | impl From for Error { 19 | fn from(value: T) -> Self { 20 | Error::Unknown(value.to_string()) 21 | } 22 | } 23 | 24 | #[derive(Serialize, Deserialize)] 25 | pub struct Config { 26 | pub swap: SwapWrapper, 27 | pub refund_private_key: bitcoincash::PrivateKey, 28 | } 29 | 30 | pub struct TradePersist { 31 | file: File, 32 | file_path: String, 33 | pub config: Config, 34 | } 35 | 36 | impl TradePersist { 37 | pub async fn restore(file_path: String) -> Result { 38 | match fs::OpenOptions::new() 39 | .write(true) 40 | .read(true) 41 | .open(file_path.clone()) 42 | .await 43 | { 44 | Err(e) => match e.kind() { 45 | ErrorKind::NotFound => return Err(Error::NotFound), 46 | _ => return Err(Error::from(e.to_string())), 47 | }, 48 | Ok(mut file) => { 49 | file.lock_exclusive()?; 50 | let mut buf = Vec::new(); 51 | let _ = file.read_to_end(&mut buf).await?; 52 | 53 | Ok(TradePersist { 54 | file, 55 | config: serde_json::from_slice(&buf)?, 56 | file_path, 57 | }) 58 | } 59 | } 60 | } 61 | 62 | pub async fn delete(self) { 63 | if let Err(err) = fs::remove_file(&self.file_path).await { 64 | eprintln!("Error deleting file: {}", err); 65 | } else { 66 | println!("File deleted successfully"); 67 | } 68 | } 69 | 70 | pub async fn save(&mut self) { 71 | let serialized = serde_json::to_vec_pretty(&self.config).unwrap(); 72 | self.file.set_len(0).await.unwrap(); 73 | self.file.rewind().await.unwrap(); 74 | let _ = self.file.write(&serialized).await.unwrap(); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /protocol/src/proof/mod.rs: -------------------------------------------------------------------------------- 1 | use ::conquer_once::Lazy; 2 | use sha2::Sha256; 3 | use sigma_fun::{ 4 | ed25519::{ 5 | curve25519_dalek, 6 | curve25519_dalek::{edwards::CompressedEdwardsY, scalar::Scalar as ScalarDalek}, 7 | }, 8 | ext::dl_secp256k1_ed25519_eq::{CrossCurveDLEQ, CrossCurveDLEQProof}, 9 | secp256k1::fun::Point as PointP, 10 | HashTranscript, 11 | }; 12 | 13 | pub static CROSS_CURVE_PROOF_SYSTEM: Lazy< 14 | CrossCurveDLEQ>, 15 | > = Lazy::new(|| { 16 | CrossCurveDLEQ::>::new( 17 | sigma_fun::secp256k1::fun::G.normalize().normalize(), 18 | curve25519_dalek::constants::ED25519_BASEPOINT_POINT, 19 | ) 20 | }); 21 | 22 | pub fn prove( 23 | privkey: &monero::PrivateKey, 24 | ) -> ( 25 | CrossCurveDLEQProof, 26 | (bitcoincash::PublicKey, monero::PublicKey), 27 | ) { 28 | let mut rng = rand::thread_rng(); 29 | let scalar = ScalarDalek::from_bytes_mod_order(privkey.to_bytes()); 30 | let (proof, (point, ed_point)) = 31 | CrossCurveDLEQ::prove(&CROSS_CURVE_PROOF_SYSTEM, &scalar, &mut rng); 32 | 33 | ( 34 | proof, 35 | ( 36 | bitcoincash::PublicKey::from_slice(&point.to_bytes()).unwrap(), 37 | monero::PublicKey::from_slice(ed_point.compress().as_bytes()).unwrap(), 38 | ), 39 | ) 40 | } 41 | 42 | pub fn verify( 43 | proof: &CrossCurveDLEQProof, 44 | bch: bitcoincash::PublicKey, 45 | xmr_pubkey: monero::PublicKey, 46 | ) -> bool { 47 | let point = PointP::from_bytes(bch.inner.serialize()).unwrap(); 48 | let edward_point = CompressedEdwardsY::from_slice(xmr_pubkey.as_bytes()) 49 | .decompress() 50 | .unwrap(); 51 | 52 | CrossCurveDLEQ::verify(&CROSS_CURVE_PROOF_SYSTEM, proof, (point, edward_point)) 53 | } 54 | -------------------------------------------------------------------------------- /protocol/src/protocol.rs: -------------------------------------------------------------------------------- 1 | use std::fmt::{self, Debug, Display}; 2 | 3 | use ecdsa_fun::{adaptor::EncryptedSignature, Signature}; 4 | use monero::Address; 5 | use serde::{Deserialize, Serialize}; 6 | 7 | use crate::{ 8 | alice::Alice, 9 | bob::Bob, 10 | keys::{bitcoin, KeyPublic}, 11 | utils::{bch_amount, monero_amount, monero_network}, 12 | }; 13 | 14 | #[derive(Debug)] 15 | pub enum Error { 16 | InvalidProof, 17 | InvalidStateTransition, 18 | InvalidTransaction, 19 | InvalidBchAddress, 20 | InvalidXmrAddress, 21 | InvalidSignature, 22 | InvalidXmrAmount, 23 | InvalidTimelock, 24 | } 25 | 26 | impl fmt::Display for Error { 27 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 28 | Debug::fmt(self, f) 29 | } 30 | } 31 | 32 | #[derive(Debug)] 33 | pub enum Action { 34 | SafeDelete, 35 | /// No further transition needed 36 | TradeSuccess, 37 | /// The server must watch address for send/receive tx 38 | /// and make Transition::BchTx(Transaction) 39 | WatchBchAddress { 40 | swaplock: String, 41 | refund: String, 42 | }, 43 | Refund, 44 | 45 | LockBch(bitcoincash::Amount, String), 46 | LockXmr(monero::Amount, monero::Address), 47 | 48 | WatchXmr(monero::Address), 49 | CreateXmrView(monero::ViewPair), 50 | 51 | UnlockBchNormal, 52 | UnlockBchFallback, 53 | } 54 | 55 | #[derive(Debug, Serialize, Deserialize)] 56 | pub enum Transition { 57 | Msg0 { 58 | keys: KeyPublic, 59 | receiving: bitcoincash::Script, 60 | }, 61 | Contract { 62 | bch_address: String, 63 | xmr_address: Address, 64 | }, 65 | 66 | EncSig(EncryptedSignature), 67 | DecSig(Signature), 68 | 69 | /// You are responsible to only use on confirmed tx 70 | #[serde(skip)] 71 | BchConfirmedTx(bitcoincash::Transaction, u32), // TODO: u32==confirmation. is it really u32? 72 | XmrLockVerified(#[serde(with = "monero_amount")] monero::Amount), 73 | 74 | SetXmrRestoreHeight(u64), 75 | } 76 | 77 | impl Display for Transition { 78 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 79 | match self { 80 | Transition::Msg0 { .. } => write!(f, "Transition::Msg0"), 81 | Transition::Contract { .. } => write!(f, "Transition::Contract"), 82 | Transition::EncSig(_) => write!(f, "Transition::EncSig"), 83 | Transition::DecSig(_) => write!(f, "Transition::DecSig"), 84 | Transition::BchConfirmedTx(_, _) => write!(f, "Transition::BchConfirmedTx"), 85 | Transition::XmrLockVerified(_) => write!(f, "Transition::XmrLockVerified"), 86 | Transition::SetXmrRestoreHeight(_) => write!(f, "Transition::SetXmrRestoreHeight"), 87 | } 88 | } 89 | } 90 | 91 | #[derive(Clone, Deserialize, Serialize)] 92 | pub struct Swap { 93 | pub id: String, 94 | #[serde(with = "monero_network")] 95 | pub xmr_network: monero::Network, 96 | pub bch_network: bitcoin::Network, 97 | 98 | pub keys: crate::keys::KeyPrivate, 99 | pub bch_recv: bitcoincash::Script, 100 | 101 | #[serde(with = "monero_amount")] 102 | pub xmr_amount: monero::Amount, 103 | #[serde(with = "bch_amount")] 104 | pub bch_amount: bitcoincash::Amount, 105 | 106 | pub timelock1: u32, 107 | pub timelock2: u32, 108 | } 109 | 110 | impl Debug for Swap { 111 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 112 | write!( 113 | f, 114 | "Swap {{\n\ 115 | \tid: {:?},\n\ 116 | \txmr_network: {:?},\n\ 117 | \tbch_network: {:?},\n\ 118 | \tkeys: KeyPrivate {{\n\ 119 | \t\tmonero_spend: monero::PrivateKey({}),\n\ 120 | \t\tmonero_view: monero::PrivateKey({}),\n\ 121 | \t\tves: bitcoincash::PrivateKey({}),\n\ 122 | \t}},\n\ 123 | \tbch_recv: {:?},\n\ 124 | \txmr_amount: {:?},\n\ 125 | \tbch_amount: {:?},\n\ 126 | }}\n\ 127 | ", 128 | self.id, 129 | self.xmr_network, 130 | self.bch_network, 131 | self.keys.monero_spend, 132 | self.keys.monero_view, 133 | self.keys.ves, 134 | self.bch_recv, 135 | self.xmr_amount, 136 | self.bch_amount, 137 | ) 138 | } 139 | } 140 | 141 | pub trait SwapEvents { 142 | type State; 143 | /// Most of the time only one from the return type are `not None` 144 | /// but there are special case that we both error and action 145 | /// 146 | /// Example: (Action::TradeFailed, Error::InvalidProof) 147 | /// : this means that we must stop the trade because other give invalid proof 148 | fn transition(self, transition: Transition) -> (Self::State, Vec, Option); 149 | fn get_transition(&self) -> Option; 150 | } 151 | 152 | #[derive(Debug, Deserialize, Serialize)] 153 | pub enum SwapWrapper { 154 | Alice(Alice), 155 | Bob(Bob), 156 | } 157 | -------------------------------------------------------------------------------- /protocol/src/utils.rs: -------------------------------------------------------------------------------- 1 | // #[serde(with = "path")] 2 | 3 | use bitcoincash::{secp256k1::ecdsa::Signature, Script}; 4 | 5 | pub mod monero_private_key { 6 | use serde::{de::Error, Deserialize, Deserializer, Serializer}; 7 | use std::str::FromStr; 8 | 9 | type Type = monero::PrivateKey; 10 | 11 | pub fn serialize(privkey: &Type, s: S) -> Result 12 | where 13 | S: Serializer, 14 | { 15 | s.serialize_str(&privkey.to_string()) 16 | } 17 | 18 | pub fn deserialize<'de, D>(deserializer: D) -> Result 19 | where 20 | D: Deserializer<'de>, 21 | { 22 | let string = String::deserialize(deserializer)?; 23 | monero::PrivateKey::from_str(&string).map_err(|err| Error::custom(err.to_string())) 24 | } 25 | } 26 | 27 | pub mod monero_view_pair { 28 | use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer}; 29 | use std::str::FromStr; 30 | 31 | type Type = monero::ViewPair; 32 | 33 | #[derive(Deserialize, Serialize)] 34 | struct MoneroViewPair { 35 | spend: String, 36 | view: String, 37 | } 38 | 39 | pub fn serialize(key: &Type, s: S) -> Result 40 | where 41 | S: Serializer, 42 | { 43 | MoneroViewPair { 44 | spend: key.spend.to_string(), 45 | view: key.view.to_string(), 46 | } 47 | .serialize(s) 48 | } 49 | 50 | pub fn deserialize<'de, D>(deserializer: D) -> Result 51 | where 52 | D: Deserializer<'de>, 53 | { 54 | let string = MoneroViewPair::deserialize(deserializer)?; 55 | Ok(monero::ViewPair { 56 | spend: monero::PublicKey::from_str(&string.spend) 57 | .map_err(|err| Error::custom(err.to_string()))?, 58 | view: monero::PrivateKey::from_str(&string.view) 59 | .map_err(|err| Error::custom(err.to_string()))?, 60 | }) 61 | } 62 | } 63 | 64 | pub mod monero_key_pair { 65 | use std::str::FromStr; 66 | 67 | use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer}; 68 | 69 | type Type = monero::KeyPair; 70 | 71 | #[derive(Deserialize, Serialize)] 72 | struct MoneroKeyPair { 73 | spend: String, 74 | view: String, 75 | } 76 | 77 | pub fn serialize(key: &Type, s: S) -> Result 78 | where 79 | S: Serializer, 80 | { 81 | MoneroKeyPair { 82 | spend: key.spend.to_string(), 83 | view: key.view.to_string(), 84 | } 85 | .serialize(s) 86 | } 87 | 88 | pub fn deserialize<'de, D>(deserializer: D) -> Result 89 | where 90 | D: Deserializer<'de>, 91 | { 92 | let string = MoneroKeyPair::deserialize(deserializer)?; 93 | Ok(monero::KeyPair { 94 | spend: monero::PrivateKey::from_str(&string.spend) 95 | .map_err(|err| Error::custom(err.to_string()))?, 96 | view: monero::PrivateKey::from_str(&string.view) 97 | .map_err(|err| Error::custom(err.to_string()))?, 98 | }) 99 | } 100 | } 101 | 102 | pub mod monero_network { 103 | use serde::{de, Deserialize, Deserializer, Serializer}; 104 | 105 | type Type = monero::Network; 106 | 107 | pub fn serialize(key: &Type, s: S) -> Result 108 | where 109 | S: Serializer, 110 | { 111 | let string = match *key { 112 | monero::Network::Mainnet => "Mainnet", 113 | monero::Network::Testnet => "Testnet", 114 | monero::Network::Stagenet => "Stagenet", 115 | }; 116 | s.serialize_str(string) 117 | } 118 | 119 | pub fn deserialize<'de, D>(deserializer: D) -> Result 120 | where 121 | D: Deserializer<'de>, 122 | { 123 | let network = match String::deserialize(deserializer)?.as_str() { 124 | "Mainnet" => monero::Network::Mainnet, 125 | "Testnet" => monero::Network::Testnet, 126 | "Stagenet" => monero::Network::Stagenet, 127 | _ => return Err(de::Error::custom("Invalid monero network")), 128 | }; 129 | Ok(network) 130 | } 131 | } 132 | 133 | pub mod monero_amount { 134 | use serde::{Deserialize, Deserializer, Serializer}; 135 | 136 | type Type = monero::Amount; 137 | 138 | pub fn serialize(key: &Type, s: S) -> Result 139 | where 140 | S: Serializer, 141 | { 142 | s.serialize_u64(key.as_pico()) 143 | } 144 | 145 | pub fn deserialize<'de, D>(deserializer: D) -> Result 146 | where 147 | D: Deserializer<'de>, 148 | { 149 | let amount = u64::deserialize(deserializer)?; 150 | Ok(monero::Amount::from_pico(amount)) 151 | } 152 | } 153 | 154 | pub mod bch_amount { 155 | use serde::{Deserialize, Deserializer, Serializer}; 156 | 157 | type Type = bitcoincash::Amount; 158 | 159 | pub fn serialize(key: &Type, s: S) -> Result 160 | where 161 | S: Serializer, 162 | { 163 | s.serialize_u64(key.to_sat()) 164 | } 165 | 166 | pub fn deserialize<'de, D>(deserializer: D) -> Result 167 | where 168 | D: Deserializer<'de>, 169 | { 170 | let amount = u64::deserialize(deserializer)?; 171 | Ok(bitcoincash::Amount::from_sat(amount)) 172 | } 173 | } 174 | 175 | pub mod monero_public_key { 176 | use std::str::FromStr; 177 | 178 | use serde::{de::Error, Deserialize, Deserializer, Serializer}; 179 | 180 | type Type = monero::PublicKey; 181 | 182 | pub fn serialize(key: &Type, s: S) -> Result 183 | where 184 | S: Serializer, 185 | { 186 | s.serialize_str(&key.to_string()) 187 | } 188 | 189 | pub fn deserialize<'de, D>(deserializer: D) -> Result 190 | where 191 | D: Deserializer<'de>, 192 | { 193 | let amount = String::deserialize(deserializer)?; 194 | Ok(monero::PublicKey::from_str(&amount).map_err(|e| Error::custom(e.to_string()))?) 195 | } 196 | } 197 | 198 | pub fn get_signature(script: Script) -> Option { 199 | for instruction in script.instructions_minimal() { 200 | match instruction { 201 | Ok(bitcoincash::blockdata::script::Instruction::PushBytes(bytes)) => { 202 | match bitcoincash::secp256k1::ecdsa::Signature::from_der(bytes) { 203 | Ok(sig) => return Some(sig), 204 | _ => {} 205 | } 206 | } 207 | _ => {} 208 | } 209 | } 210 | return None; 211 | } 212 | -------------------------------------------------------------------------------- /web-server/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "web-server" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | axum = "0.7.2" 10 | fs4 = { version = "0.7", features = ["tokio"] } 11 | hex = { version = "0.4.3", features = ["serde"] } 12 | protocol = { path = "../protocol" } 13 | reqwest = { version = "0.11.22", features = ["json"] } 14 | serde = { version = "1.0.193", features = ["derive"] } 15 | serde_json = "1.0.108" 16 | tokio = { version = "1.35.0", features = ["full"] } 17 | -------------------------------------------------------------------------------- /web-server/src/main.rs: -------------------------------------------------------------------------------- 1 | // #![allow(unused_variables, unused_imports, dead_code)] 2 | use std::{env, net::SocketAddr, sync::Arc, time::Duration}; 3 | 4 | use axum::Router; 5 | use protocol::{ 6 | alice, 7 | blockchain::{self, TcpElectrum}, 8 | bob, 9 | keys::bitcoin::Network, 10 | monero, monero_rpc, 11 | persist::TradePersist, 12 | protocol::SwapWrapper, 13 | }; 14 | use serde_json::json; 15 | use tokio::{fs, net::TcpStream, sync::Mutex, time::sleep}; 16 | 17 | use trader::get_file_path; 18 | 19 | mod trader; 20 | pub mod utils; 21 | 22 | pub struct AppState { 23 | bch_server: TcpElectrum, 24 | monerod: monero_rpc::DaemonJsonRpcClient, 25 | monero_wallet: Mutex, 26 | bch_min_conf: u32, 27 | monero_network: monero::Network, 28 | bch_network: Network, 29 | 30 | timelock1: u32, 31 | timelock2: u32, 32 | } 33 | 34 | type TAppState = Arc; 35 | 36 | async fn check_xmr_wallets(state: &TAppState) { 37 | let base_path = "./.trades/ongoing/"; 38 | let mut entries = fs::read_dir(base_path).await.unwrap(); 39 | while let Some(entry) = entries.next_entry().await.unwrap() { 40 | if !entry.path().is_file() { 41 | continue; 42 | } 43 | let filename = entry.file_name().into_string().unwrap(); 44 | if !filename.ends_with("-server.json") { 45 | continue; 46 | } 47 | 48 | let trade_id = filename.split("-").next().unwrap().to_string(); 49 | let mut trade = TradePersist::restore(get_file_path(&trade_id)) 50 | .await 51 | .unwrap(); 52 | match trade.config.swap { 53 | SwapWrapper::Bob(inner) => { 54 | let mut runner = bob::Runner { 55 | inner, 56 | trade_id, 57 | bch: &state.bch_server, 58 | monero_wallet: &state.monero_wallet, 59 | monerod: &state.monerod, 60 | min_bch_conf: state.bch_min_conf, 61 | }; 62 | let _ = runner.check_xmr().await; 63 | trade.config.swap = SwapWrapper::Bob(runner.inner); 64 | } 65 | _ => {} 66 | } 67 | trade.save().await; 68 | } 69 | } 70 | 71 | async fn check_bch_wallets(state: &TAppState) { 72 | let base_path = "./.trades/ongoing/"; 73 | let mut entries = fs::read_dir(base_path).await.unwrap(); 74 | while let Some(entry) = entries.next_entry().await.unwrap() { 75 | if !entry.path().is_file() { 76 | continue; 77 | } 78 | let filename = entry.file_name().into_string().unwrap(); 79 | if !filename.ends_with("-server.json") { 80 | continue; 81 | } 82 | 83 | let trade_id = filename.split("-").next().unwrap().to_string(); 84 | let mut trade = TradePersist::restore(get_file_path(&trade_id)) 85 | .await 86 | .unwrap(); 87 | 88 | match trade.config.swap { 89 | SwapWrapper::Bob(bob) => { 90 | let mut runner = bob::Runner { 91 | trade_id, 92 | inner: bob, 93 | bch: &state.bch_server, 94 | min_bch_conf: state.bch_min_conf, 95 | monerod: &state.monerod, 96 | monero_wallet: &state.monero_wallet, 97 | }; 98 | let _ = runner.check_bch().await; 99 | trade.config.swap = SwapWrapper::Bob(runner.inner); 100 | } 101 | SwapWrapper::Alice(alice) => { 102 | let mut runner = alice::Runner { 103 | inner: alice, 104 | bch: &state.bch_server, 105 | min_bch_conf: state.bch_min_conf, 106 | }; 107 | let _ = runner.check_bch().await; 108 | trade.config.swap = SwapWrapper::Alice(runner.inner); 109 | } 110 | } 111 | trade.save().await; 112 | } 113 | } 114 | 115 | #[tokio::main] 116 | async fn main() { 117 | let bch_min_conf = 1; 118 | 119 | let monerod_addr = "http://localhost:18081"; 120 | let monero_wallet_addr = "http://localhost:8081"; 121 | let fullcrum_tcp = "localhost:50001"; 122 | 123 | let monero_network = monero::Network::Mainnet; 124 | let bch_network = Network::Regtest; 125 | 126 | let timelock1 = 2; 127 | let timelock2 = 2; 128 | 129 | // =================================================== 130 | 131 | let monerod = monero_rpc::RpcClientBuilder::new() 132 | .build(monerod_addr) 133 | .unwrap() 134 | .daemon(); 135 | let monero_wallet = Mutex::new( 136 | monero_rpc::RpcClientBuilder::new() 137 | .build(monero_wallet_addr) 138 | .unwrap() 139 | .wallet(), 140 | ); 141 | 142 | let socket = TcpStream::connect(fullcrum_tcp).await.unwrap(); 143 | let bch_server = blockchain::TcpElectrum::new(socket); 144 | 145 | let state = Arc::new(AppState { 146 | bch_server: bch_server.clone(), 147 | monerod, 148 | monero_wallet, 149 | bch_min_conf, 150 | monero_network, 151 | bch_network, 152 | timelock1, 153 | timelock2, 154 | }); 155 | 156 | tokio::spawn({ 157 | let state = state.clone(); 158 | async move { 159 | loop { 160 | println!("Checking Wallet XMR..."); 161 | check_xmr_wallets(&state).await; 162 | sleep(Duration::from_secs(20)).await; 163 | } 164 | } 165 | }); 166 | 167 | tokio::spawn({ 168 | let state = state.clone(); 169 | let mut receiver = state.bch_server.subscribe(); 170 | let _ = state 171 | .bch_server 172 | .send("blockchain.headers.subscribe", json!([])) 173 | .await 174 | .unwrap(); 175 | 176 | async move { 177 | loop { 178 | let data = receiver.recv().await.unwrap(); 179 | let data: serde_json::Value = serde_json::from_str(&data).unwrap(); 180 | 181 | if data["method"].as_str().unwrap() != "blockchain.headers.subscribe" { 182 | continue; 183 | } 184 | 185 | println!("New block found. Rescanning addresses"); 186 | check_bch_wallets(&state).await 187 | } 188 | } 189 | }); 190 | 191 | let app = Router::new().nest("/trader", trader::trader(state)); 192 | 193 | let port = env::var("PORT").unwrap_or("8080".to_owned()); 194 | let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{port}")) 195 | .await 196 | .unwrap(); 197 | 198 | println!("listening on http://{}", listener.local_addr().unwrap()); 199 | axum::serve( 200 | listener, 201 | app.into_make_service_with_connect_info::(), 202 | ) 203 | .await 204 | .unwrap(); 205 | } 206 | -------------------------------------------------------------------------------- /web-server/src/trader.rs: -------------------------------------------------------------------------------- 1 | use std::{fs, io::Write, net::SocketAddr}; 2 | 3 | use axum::{ 4 | extract::{ConnectInfo, Path, State}, 5 | http::StatusCode, 6 | routing::{patch, post}, 7 | Json, Router, 8 | }; 9 | use protocol::{ 10 | bitcoincash, 11 | bob::{self, Bob}, 12 | keys::{bitcoin::random_private_key, KeyPrivate}, 13 | monero, 14 | persist::{Config, Error as PersistError, TradePersist}, 15 | protocol::{Swap, SwapEvents, SwapWrapper, Transition}, 16 | }; 17 | use serde::{Deserialize, Serialize}; 18 | 19 | use crate::{ 20 | utils::{random_str, ApiResult, Error, JsonRej}, 21 | TAppState, 22 | }; 23 | 24 | pub fn trader(state: TAppState) -> Router { 25 | Router::new() 26 | .route("/", post(create)) 27 | .route("/:trade_id", patch(transition).get(get_transition)) 28 | .with_state(state) 29 | } 30 | 31 | #[inline] 32 | pub fn get_file_path(trade_id: &str) -> String { 33 | format!("./.trades/ongoing/{trade_id}-server.json") 34 | } 35 | 36 | // ========================================== 37 | // SECTION: Create Trade 38 | // ========================================== 39 | 40 | #[derive(Deserialize)] 41 | struct CreateRequest { 42 | path: String, 43 | #[serde(with = "bitcoincash::util::amount::serde::as_sat")] 44 | bch_amount: bitcoincash::Amount, 45 | #[serde(with = "monero::util::amount::serde::as_pico")] 46 | xmr_amount: monero::Amount, 47 | timelock1: u32, 48 | timelock2: u32, 49 | } 50 | 51 | #[derive(Debug, Serialize)] 52 | struct CreateResponse { 53 | trade_id: String, 54 | } 55 | 56 | async fn create( 57 | State(state): State, 58 | ConnectInfo(addr): ConnectInfo, 59 | JsonRej(request): JsonRej, 60 | ) -> ApiResult> { 61 | if request.bch_amount.to_sat() != 100000 || request.xmr_amount.as_pico() != 100000 { 62 | return Err(Error::new(StatusCode::FORBIDDEN, "Invalid amount")); 63 | } 64 | 65 | if request.timelock1 != state.timelock1 || request.timelock2 != state.timelock2 { 66 | return Err(Error::new(StatusCode::FORBIDDEN, "Invalid timelock")); 67 | } 68 | 69 | let trade_id = random_str(10); 70 | 71 | let (refund_priv, refund_script) = { 72 | let refund_priv = random_private_key(state.bch_network); 73 | let secp = bitcoincash::secp256k1::Secp256k1::signing_only(); 74 | let refund_pkh = refund_priv.public_key(&secp).pubkey_hash(); 75 | let script = bitcoincash::Script::new_p2pkh(&refund_pkh); 76 | (refund_priv, script) 77 | }; 78 | 79 | let swap = Swap { 80 | id: trade_id.clone(), 81 | keys: KeyPrivate::random(state.bch_network), 82 | bch_amount: request.bch_amount, 83 | xmr_amount: request.xmr_amount, 84 | xmr_network: state.monero_network, 85 | bch_network: state.bch_network, 86 | bch_recv: refund_script, 87 | timelock1: request.timelock1, 88 | timelock2: request.timelock2, 89 | }; 90 | 91 | let swap = match request.path.as_str() { 92 | // TODO: 93 | // "bch->xmr" => SwapWrapper::Alice(Alice { 94 | // state: alice::State::Init, 95 | // swap, 96 | // }), 97 | "xmr->bch" => SwapWrapper::Bob(Bob::new(swap)), 98 | _ => { 99 | return Err(Error::new( 100 | StatusCode::NOT_IMPLEMENTED, 101 | "Pair not available", 102 | )) 103 | } 104 | }; 105 | 106 | let serialized = serde_json::to_vec_pretty(&Config { 107 | swap, 108 | refund_private_key: refund_priv, 109 | })?; 110 | 111 | fs::OpenOptions::new() 112 | .create_new(true) 113 | .write(true) 114 | .open(get_file_path(&trade_id))? 115 | .write(&serialized)?; 116 | 117 | println!("[INFO] New Trade: {trade_id}"); 118 | println!(" Client IP: {addr}"); 119 | 120 | Ok(Json(CreateResponse { trade_id })) 121 | } 122 | 123 | // ========================================== 124 | // SECTION: Transition 125 | // ========================================== 126 | 127 | #[derive(Serialize)] 128 | struct TransitionResponse { 129 | error: bool, 130 | } 131 | 132 | async fn transition( 133 | State(state): State, 134 | Path(trade_id): Path, 135 | JsonRej(request): JsonRej, 136 | ) -> ApiResult> { 137 | // ! we always open the file even on private transition 138 | // ! we can put a matcher here to reduce file opening 139 | 140 | let mut trade = match TradePersist::restore(get_file_path(&trade_id)).await { 141 | Ok(v) => v, 142 | Err(e) => match e { 143 | PersistError::NotFound => { 144 | return Err(Error::new(StatusCode::NOT_FOUND, "Trade id not found")) 145 | } 146 | PersistError::Unknown(e) => return Err(Error::from(e.to_string())), 147 | }, 148 | }; 149 | 150 | match trade.config.swap { 151 | SwapWrapper::Bob(inner) => { 152 | let mut bob = bob::Runner { 153 | inner, 154 | trade_id, 155 | bch: &state.bch_server, 156 | monero_wallet: &state.monero_wallet, 157 | monerod: &state.monerod, 158 | min_bch_conf: state.bch_min_conf, 159 | }; 160 | bob.pub_transition(request).await?; 161 | 162 | trade.config.swap = SwapWrapper::Bob(bob.inner); 163 | trade.save().await; 164 | } 165 | SwapWrapper::Alice(_) => {} 166 | } 167 | 168 | Ok(Json(TransitionResponse { error: false })) 169 | } 170 | 171 | // ========================================== 172 | // SECTION: Get Transition 173 | // ========================================== 174 | 175 | async fn get_transition(Path(trade_id): Path) -> ApiResult>> { 176 | match TradePersist::restore(get_file_path(&trade_id)).await { 177 | Ok(value) => match value.config.swap { 178 | SwapWrapper::Alice(alice) => Ok(Json(alice.get_transition())), 179 | SwapWrapper::Bob(bob) => Ok(Json(bob.get_transition())), 180 | }, 181 | Err(e) => match e { 182 | PersistError::NotFound => { 183 | return Err(Error::new(StatusCode::NOT_FOUND, "Trade id not found")) 184 | } 185 | PersistError::Unknown(e) => return Err(Error::from(e.to_string())), 186 | }, 187 | } 188 | } 189 | -------------------------------------------------------------------------------- /web-server/src/utils.rs: -------------------------------------------------------------------------------- 1 | use axum::{ 2 | async_trait, 3 | extract::{rejection::JsonRejection, FromRequest, Request}, 4 | http::StatusCode, 5 | response::IntoResponse, 6 | Json, 7 | }; 8 | use protocol::rand::{self, distributions::Alphanumeric, Rng}; 9 | use serde_json::json; 10 | 11 | pub struct Error { 12 | pub code: StatusCode, 13 | pub message: String, 14 | } 15 | 16 | pub type ApiResult = Result; 17 | 18 | impl Error { 19 | pub fn new(code: StatusCode, message: impl Into) -> Self { 20 | Self { 21 | code, 22 | message: message.into(), 23 | } 24 | } 25 | } 26 | 27 | impl From for Error { 28 | fn from(value: T) -> Self { 29 | eprintln!("Unhandled Error: {}", value.to_string()); 30 | 31 | Error { 32 | code: StatusCode::INTERNAL_SERVER_ERROR, 33 | message: "Internal server error".to_owned(), 34 | } 35 | } 36 | } 37 | 38 | impl IntoResponse for Error { 39 | fn into_response(self) -> axum::response::Response { 40 | ( 41 | self.code, 42 | Json(json!({ "error": true, "message": self.message })), 43 | ) 44 | .into_response() 45 | } 46 | } 47 | 48 | pub struct JsonRej(pub T); 49 | 50 | #[async_trait] 51 | impl FromRequest for JsonRej 52 | where 53 | Json: FromRequest, 54 | S: Send + Sync, 55 | { 56 | type Rejection = (StatusCode, Json); 57 | 58 | async fn from_request(req: Request, state: &S) -> Result { 59 | let (parts, body) = req.into_parts(); 60 | let req = Request::from_parts(parts, body); 61 | 62 | match Json::::from_request(req, state).await { 63 | Ok(value) => Ok(Self(value.0)), 64 | Err(rejection) => { 65 | let payload = json!({ 66 | "error": true, 67 | "message": rejection.body_text(), 68 | }); 69 | Err((rejection.status(), Json(payload))) 70 | } 71 | } 72 | } 73 | } 74 | 75 | pub fn random_str(len: usize) -> String { 76 | rand::thread_rng() 77 | .sample_iter(&Alphanumeric) 78 | .take(len) 79 | .map(char::from) 80 | .collect() 81 | } 82 | --------------------------------------------------------------------------------