├── .gitignore ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── cmd ├── batch.go ├── config.go ├── generate.go ├── handlers │ ├── batch.go │ ├── config.go │ ├── config_test.go │ └── generate.go ├── root.go └── start.go ├── configs └── example.toml ├── go.mod ├── go.sum ├── internal ├── app │ └── relayer │ │ ├── app.go │ │ ├── domain │ │ ├── README.md │ │ ├── cache_file_write.go │ │ ├── cache_file_write_test.go │ │ └── context.go │ │ ├── repostitory │ │ ├── README.md │ │ ├── bsc │ │ │ ├── bsc_client.go │ │ │ ├── bsc_client_test.go │ │ │ ├── config.go │ │ │ └── contracts │ │ │ │ ├── client.go │ │ │ │ └── packet.go │ │ ├── eth │ │ │ ├── config.go │ │ │ ├── contracts │ │ │ │ ├── client.go │ │ │ │ └── packet.go │ │ │ ├── eth_client.go │ │ │ └── eth_client_test.go │ │ ├── ethermint │ │ │ ├── config.go │ │ │ ├── contract.go │ │ │ ├── contracts │ │ │ │ ├── client.go │ │ │ │ └── packet.go │ │ │ ├── eth.go │ │ │ └── tendermint.go │ │ ├── exported.go │ │ ├── tendermint_client.go │ │ └── types │ │ │ ├── keys.go │ │ │ └── types.go │ │ └── services │ │ ├── README.md │ │ ├── channels │ │ ├── channel.go │ │ ├── mertic_mw.go │ │ └── writer_mw.go │ │ └── listener.go └── pkg │ ├── configs │ └── configs.go │ ├── initialization │ ├── bsc.go │ ├── channel.go │ ├── eth.go │ ├── ethermint.go │ ├── logger.go │ └── tendermint.go │ └── types │ ├── cache │ └── cache.go │ ├── constant │ └── const.go │ ├── errors │ └── error.go │ └── mertics │ └── metric.go ├── main.go └── tools ├── global.go ├── keys.go └── paths.go /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | .vscode/ 3 | .DS_Store 4 | *.log 5 | build/ 6 | .tibc-relayer/ -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Build image: docker build -t relayers/fabric . 2 | FROM golang:1.15-alpine3.12 as builder 3 | 4 | # Set up dependencies 5 | ENV PACKAGES make git libc-dev bash gcc 6 | WORKDIR $GOPATH/src 7 | COPY . . 8 | # Install minimum necessary dependencies, build binary 9 | RUN apk add --no-cache $PACKAGES && make install 10 | 11 | FROM alpine:3.12 12 | COPY --from=builder /go/bin/relayer /usr/local/bin/relayer 13 | 14 | CMD ["relayer"] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2021 Shanghai Bianjie Technology Ltd. 上海边界智能科技有限公司 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | #!/usr/bin/make -f 2 | 3 | build: 4 | ifeq ($(OS),Windows_NT) 5 | go build -o build/relayer.exe . 6 | else 7 | go build -o build/relayer . 8 | endif 9 | 10 | build-linux: go.sum 11 | LEDGER_ENABLED=false GOOS=linux GOARCH=amd64 $(MAKE) build 12 | 13 | go.sum: go.mod 14 | @echo "--> Ensure dependencies have not been modified" 15 | @go mod verify 16 | 17 | install: 18 | go build -o relayer && mv relayer $(GOPATH)/bin 19 | 20 | format: 21 | find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" | xargs gofmt -w -s 22 | find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" | xargs misspell -w 23 | find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./lite/*/statik.go" -not -path "*.pb.go" | xargs goimports -w -local github.com/bianjieai/tibc-relayer-go 24 | 25 | 26 | setup: build-linux 27 | @docker build -t relayer . 28 | @rm -rf ./build 29 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # tibc-relayer-go 2 | 3 | ## Introduction 4 | 5 | Golang Relayer for Terse IBC 6 | 7 | ## Support 8 | 9 | - Tendermint and Tendermint (done) 10 | - Tendermint and ETH (done) 11 | - Tendermint and BSC (done) 12 | 13 | ## Configs 14 | 15 | ### Tendermint and Tendermint example 16 | 17 | ```toml 18 | [app] 19 | 20 | env = "dev" 21 | log_level = "debug" 22 | metric_addr = "0.0.0.0:8084" 23 | channel_types = ["tendermint_and_tendermint"] 24 | 25 | 26 | # wenchangchain -> bsn 27 | 28 | # bsn 29 | 30 | [chain] 31 | 32 | [chain.dest] 33 | 34 | chain_type = "tendermint" 35 | enabled = true # Whether to enable relay 36 | 37 | [chain.dest.cache] 38 | filename = "dest-chain.json" 39 | start_height = 5 40 | 41 | [chain.dest.tendermint] 42 | chain_id = "dest-testnet" 43 | chain_name = "dest-testnet-mainnet" 44 | gas = 100000000 45 | grpc_addr = "dest_chain_host:9090" # eg. 127.0.0.1:9090 46 | rpc_addr = "http://dest_chain_host:26657" # eg. http://127.0.0.1:26657 47 | update_client_frequency = 1 # update client frequency, unit hour 48 | request_timeout = 60 49 | clean_packet_enabled = false 50 | 51 | [chain.dest.tendermint.fee] 52 | denom = "uiris" 53 | amount = 100 54 | 55 | [chain.dest.tendermint.key] 56 | name = "your_dest_chain_relayer_name" 57 | password = "your_dest_chain_relayer_pwd" 58 | priv_key_armor = "your_dest_chain_relayer_priv_key" 59 | 60 | 61 | # iris-hub 62 | 63 | [chain.source] 64 | 65 | chain_type = "tendermint" 66 | enabled = true # Whether to enable relay 67 | 68 | [chain.source.cache] 69 | filename = "source_chain.json" 70 | start_height = 5 71 | 72 | [chain.source.tendermint] 73 | chain_id = "source-testnet" 74 | chain_name = "source-testnet-mainnet" 75 | gas = 100000000 76 | grpc_addr = "source_chain_host:9090" # eg. 127.0.0.1:9090 77 | rpc_addr = "http://source_chain_host:26657" # eg. http://127.0.0.1:26657 78 | update_client_frequency = 1 # update client frequency, unit hour 79 | request_timeout = 60 80 | clean_packet_enabled = false 81 | algo = "sm2" # If there is no special annotation, use secp256k1 82 | 83 | [chain.source.tendermint.fee] 84 | denom = "uirita" 85 | amount = 100 86 | 87 | [chain.source.tendermint.key] 88 | name = "your_source_chain_relayer_name" 89 | password = "your_source_chain_relayer_pwd" 90 | priv_key_armor = "your_source_chain_relayer_priv_key" 91 | 92 | ``` 93 | 94 | ### Tendermint and ETH example 95 | 96 | ```toml 97 | [app] 98 | 99 | env = "prod" 100 | log_level = "info" 101 | metric_addr = "0.0.0.0:8083" 102 | channel_types = ["tendermint_and_eth"] 103 | 104 | [chain] 105 | 106 | [chain.dest] 107 | chain_type = "bsc" 108 | enabled = false 109 | 110 | [chain.dest.cache] 111 | filename = "dest_chain.json" 112 | start_height = 17206800 113 | 114 | [chain.dest.eth] 115 | chain_id = 97 116 | chain_name = "eth-mainnet" # The name registered when deploying the contract 117 | update_client_frequency = 2 118 | uri = "" 119 | gas_limit = 2000000 120 | max_gas_price = 150000000000 121 | comment_slot = 104 122 | tip_coefficient = 0.1 123 | 124 | [chain.dest.eth.eth_contracts] 125 | 126 | [chain.dest.eth.eth_contracts.packet] 127 | addr = "" # packet contract addr 128 | topic = "PacketSent((uint64,string,string,string,string,bytes))" 129 | opt_priv_key = "" # eth relayer priv key 130 | 131 | [chain.dest.eth.eth_contracts.ack_packet] 132 | addr = "" # packet contract addr 133 | topic = "AckWritten((uint64,string,string,string,string,bytes),bytes)" 134 | opt_priv_key = "" # eth relayer priv key 135 | 136 | [chain.dest.eth.eth_contracts.clean_packet] 137 | addr = "" # packet contract addr地址 138 | topic = "CleanPacketSent((uint64,string,string,string))" 139 | opt_priv_key = "" # eth relayer priv key 140 | 141 | [chain.dest.eth.eth_contracts.client] 142 | addr = "" # client manager contract addr 143 | topic = "" 144 | opt_priv_key = "" # eth relayer priv key 145 | 146 | 147 | 148 | # iris-hub 149 | 150 | [chain.source] 151 | 152 | chain_type = "tendermint" 153 | enabled = true # Whether to enable relay 154 | 155 | [chain.source.cache] 156 | filename = "source_chain.json" 157 | start_height = 5 158 | 159 | [chain.source.tendermint] 160 | chain_id = "source-testnet" 161 | chain_name = "source-testnet-mainnet" 162 | gas = 100000000 163 | grpc_addr = "source_chain_host:9090" # eg. 127.0.0.1:9090 164 | rpc_addr = "http://source_chain_host:26657" # eg. http://127.0.0.1:26657 165 | update_client_frequency = 1 # update client frequency, unit hour 166 | request_timeout = 60 167 | clean_packet_enabled = false 168 | algo = "sm2" # chain user algo 169 | 170 | [chain.source.tendermint.fee] 171 | denom = "uirita" 172 | amount = 100 173 | 174 | [chain.source.tendermint.key] 175 | name = "your_source_chain_relayer_name" 176 | password = "your_source_chain_relayer_pwd" 177 | priv_key_armor = "your_source_chain_relayer_priv_key" 178 | 179 | ``` 180 | 181 | 182 | ### Tendermint and BSC example 183 | 184 | ```toml 185 | [app] 186 | 187 | env = "prod" 188 | log_level = "info" 189 | metric_addr = "0.0.0.0:8083" 190 | channel_types = ["tendermint_and_bsc"] 191 | 192 | [chain] 193 | 194 | [chain.dest] 195 | chain_type = "bsc" 196 | enabled = false 197 | 198 | [chain.dest.cache] 199 | filename = "dest_chain.json" 200 | start_height = 17206800 201 | 202 | [chain.dest.bsc] 203 | chain_id = 97 204 | chain_name = "bsc-mainnet" # The name registered when deploying the contract 205 | update_client_frequency = 2 206 | uri = "https://data-seed-prebsc-1-s1.binance.org:8545" 207 | gas_limit = 2000000 208 | max_gas_price = 150000000000 209 | comment_slot = 104 210 | tip_coefficient = 0.1 211 | 212 | [chain.dest.bsc.eth_contracts] 213 | 214 | [chain.dest.bsc.eth_contracts.packet] 215 | addr = "" # packet contract addr 216 | topic = "PacketSent((uint64,string,string,string,string,bytes))" 217 | opt_priv_key = "" # eth relayer priv key 218 | 219 | [chain.dest.bsc.eth_contracts.ack_packet] 220 | addr = "" # packet contract addr 221 | topic = "AckWritten((uint64,string,string,string,string,bytes),bytes)" 222 | opt_priv_key = "" # eth relayer priv key 223 | 224 | [chain.dest.bsc.eth_contracts.clean_packet] 225 | addr = "" # packet contract addr地址 226 | topic = "CleanPacketSent((uint64,string,string,string))" 227 | opt_priv_key = "" # eth relayer priv key 228 | 229 | [chain.dest.bsc.eth_contracts.client] 230 | addr = "" # client manager contract addr 231 | topic = "" 232 | opt_priv_key = "" # eth relayer priv key 233 | 234 | # iris-hub 235 | 236 | [chain.source] 237 | 238 | chain_type = "tendermint" 239 | enabled = true # Whether to enable relay 240 | 241 | [chain.source.cache] 242 | filename = "source_chain.json" 243 | start_height = 5 244 | 245 | [chain.source.tendermint] 246 | chain_id = "source-testnet" 247 | chain_name = "source-testnet-mainnet" 248 | gas = 100000000 249 | grpc_addr = "source_chain_host:9090" # eg. 127.0.0.1:9090 250 | rpc_addr = "http://source_chain_host:26657" # eg. http://127.0.0.1:26657 251 | update_client_frequency = 1 # update client frequency, unit hour 252 | request_timeout = 60 253 | clean_packet_enabled = false 254 | algo = "sm2" # chain user algo 255 | 256 | [chain.source.tendermint.fee] 257 | denom = "uirita" 258 | amount = 100 259 | 260 | [chain.source.tendermint.key] 261 | name = "your_source_chain_relayer_name" 262 | password = "your_source_chain_relayer_pwd" 263 | priv_key_armor = "your_source_chain_relayer_priv_key" 264 | 265 | ``` 266 | 267 | ### Tendermint and Ethermint example 268 | 269 | ```toml 270 | [app] 271 | 272 | env = "dev" 273 | log_level = "info" 274 | metric_addr = "0.0.0.0:8083" 275 | channel_types = ["tendermint_and_ethermint"] 276 | 277 | [chain] 278 | 279 | [chain.dest] 280 | chain_type = "ethermint" 281 | enabled = true 282 | 283 | [chain.dest.cache] 284 | filename = "irita-b-evm-dest.json" 285 | start_height = 100 286 | 287 | [chain.dest.ethermint] 288 | # comment 289 | chain_name = "irita-b-evm-testnet" 290 | 291 | # eth 292 | eth_chain_id = 1223 293 | update_client_frequency = 2 294 | uri = "http://localhost:8545" 295 | gas_limit = 2000000 296 | max_gas_price = 150000000000 297 | comment_slot = 104 298 | tip_coefficient = 0.1 299 | 300 | # tendermint 301 | tendermint_chain_id = "irita-b-testnet" 302 | gas = 300000 303 | grpc_addr = "127.0.0.1:9090" 304 | rpc_addr = "http://127.0.0.1:26657" 305 | request_timeout = 60 306 | 307 | [chain.dest.ethermint.eth_contracts] 308 | 309 | [chain.dest.ethermint.eth_contracts.packet] 310 | addr = "" # packet 合约 311 | topic = "PacketSent((uint64,string,string,string,string,bytes))" 312 | opt_priv_key = "" # eth relayer 私钥 313 | 314 | [chain.dest.ethermint.eth_contracts.ack_packet] 315 | addr = "" # packet 合约 316 | topic = "AckWritten((uint64,string,string,string,string,bytes),bytes)" 317 | opt_priv_key = "" # eth relayer 私钥 318 | 319 | [chain.dest.ethermint.eth_contracts.clean_packet] 320 | addr = "" # packet 合约 321 | topic = "CleanPacketSent((uint64,string,string,string))" 322 | opt_priv_key = "" # eth relayer 私钥 323 | 324 | [chain.dest.ethermint.eth_contracts.client] 325 | addr = "" # client manager 合约 326 | topic = "" 327 | opt_priv_key = "" # eth relayer 私钥 328 | 329 | [chain.source] 330 | 331 | chain_type = "tendermint" 332 | enabled = true # Whether to enable relay 333 | 334 | [chain.source.cache] 335 | filename = "irita-a-testnet-source.json" 336 | start_height = 100 337 | 338 | [chain.source.tendermint] 339 | chain_id = "irita-a-testnet" 340 | chain_name = "irita-a-testnet" 341 | gas = 300000 342 | grpc_addr = "127.0.0.1:19090" 343 | rpc_addr = "http://127.0.0.1:36657" 344 | update_client_frequency = 1 345 | request_timeout = 60 346 | clean_packet_enabled = false 347 | algo="sm2" 348 | 349 | [chain.source.tendermint.fee] 350 | denom = "ugas" 351 | amount = 100 352 | 353 | [[chain.source.tendermint.allows]] 354 | contract_addr = "" 355 | senders = [""] 356 | 357 | [chain.source.tendermint.key] 358 | name = "relayereth-1" 359 | password = "12345678" 360 | priv_key_armor = "" 361 | 362 | ``` -------------------------------------------------------------------------------- /cmd/batch.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | 7 | "github.com/bianjieai/tibc-relayer-go/cmd/handlers" 8 | 9 | "github.com/spf13/cobra" 10 | ) 11 | 12 | var ( 13 | endHeight uint64 14 | batchCmd = &cobra.Command{ 15 | Use: "batch", 16 | Short: "Manual batch send update eth tx", 17 | Run: func(cmd *cobra.Command, args []string) { 18 | batchUpdateETHClient() 19 | }, 20 | } 21 | ) 22 | 23 | func init() { 24 | rootCmd.AddCommand(batchCmd) 25 | batchCmd.Flags().StringVarP(&localConfig, "CONFIG", "c", "", "config path: /opt/local.toml") 26 | batchCmd.Flags().Uint64VarP(&endHeight, "END", "e", 0, "ethereum ending height") 27 | } 28 | 29 | func batchUpdateETHClient() { 30 | data, err := ioutil.ReadFile(localConfig) 31 | if err != nil { 32 | fmt.Println("Error: get config data error: ", err) 33 | return 34 | } 35 | config, err := readConfig(data) 36 | if err != nil { 37 | fmt.Println("Error: read config error: ", err) 38 | return 39 | } 40 | 41 | handlers.BatchUpdateETHClient(config, endHeight) 42 | } 43 | -------------------------------------------------------------------------------- /cmd/config.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/spf13/cobra" 7 | 8 | "github.com/bianjieai/tibc-relayer-go/cmd/handlers" 9 | "github.com/bianjieai/tibc-relayer-go/tools" 10 | ) 11 | 12 | var ( 13 | home string 14 | 15 | configCmd = &cobra.Command{ 16 | Use: "config", 17 | Aliases: []string{"cfg"}, 18 | Short: "manage configuration file", 19 | Run: func(cmd *cobra.Command, args []string) { 20 | createConfig() 21 | }, 22 | } 23 | configInitCmd = &cobra.Command{ 24 | Use: "init", 25 | Short: "init configuration file", 26 | Run: func(cmd *cobra.Command, args []string) { 27 | initConfig() 28 | }, 29 | } 30 | ) 31 | 32 | func init() { 33 | rootCmd.AddCommand(configCmd) 34 | configCmd.AddCommand(configInitCmd) 35 | configCmd.Flags().StringVarP(&home, "path", "p", "", "config path: .relayer") 36 | } 37 | 38 | func createConfig() { 39 | if home == "" { 40 | fmt.Println("please enter dir, for example: relayer cfg -p .relayer ") 41 | return 42 | } 43 | handlers.ConfigInit(home) 44 | } 45 | 46 | func initConfig() { 47 | handlers.ConfigInit(tools.DefaultHomePath) 48 | } 49 | -------------------------------------------------------------------------------- /cmd/generate.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | 7 | "github.com/bianjieai/tibc-relayer-go/cmd/handlers" 8 | 9 | "github.com/spf13/cobra" 10 | ) 11 | 12 | var ( 13 | generateCmd = &cobra.Command{ 14 | Use: "generate", 15 | Aliases: []string{"gen"}, 16 | Short: "Generate the files needed for create client: clientStatus & consensusState", 17 | Run: func(cmd *cobra.Command, args []string) { 18 | createClientFiles() 19 | }, 20 | } 21 | ) 22 | 23 | func init() { 24 | rootCmd.AddCommand(generateCmd) 25 | generateCmd.Flags().StringVarP(&localConfig, "CONFIG", "c", "", "config path: /opt/local.toml") 26 | } 27 | 28 | func createClientFiles() { 29 | data, err := ioutil.ReadFile(localConfig) 30 | if err != nil { 31 | fmt.Println("Error: get config data error: ", err) 32 | return 33 | } 34 | config, err := readConfig(data) 35 | if err != nil { 36 | fmt.Println("Error: read config error: ", err) 37 | return 38 | } 39 | handlers.CreateClientFiles(config) 40 | } 41 | -------------------------------------------------------------------------------- /cmd/handlers/batch.go: -------------------------------------------------------------------------------- 1 | package handlers 2 | 3 | import ( 4 | "context" 5 | "math/big" 6 | "time" 7 | 8 | tibc "github.com/bianjieai/tibc-sdk-go" 9 | tibcclient "github.com/bianjieai/tibc-sdk-go/modules/core/client" 10 | tibcbcs "github.com/bianjieai/tibc-sdk-go/modules/light-clients/bsc" 11 | tibceth "github.com/bianjieai/tibc-sdk-go/modules/light-clients/eth" 12 | tibctypes "github.com/bianjieai/tibc-sdk-go/modules/types" 13 | gethethclient "github.com/ethereum/go-ethereum/ethclient" 14 | gethrpc "github.com/ethereum/go-ethereum/rpc" 15 | "github.com/irisnet/core-sdk-go/bank" 16 | "github.com/irisnet/core-sdk-go/client" 17 | "github.com/irisnet/core-sdk-go/common/codec" 18 | cdctypes "github.com/irisnet/core-sdk-go/common/codec/types" 19 | cryptotypes "github.com/irisnet/core-sdk-go/common/codec/types" 20 | cryptocodec "github.com/irisnet/core-sdk-go/common/crypto/codec" 21 | "github.com/irisnet/core-sdk-go/gov" 22 | "github.com/irisnet/core-sdk-go/staking" 23 | "github.com/irisnet/core-sdk-go/types" 24 | coretypes "github.com/irisnet/core-sdk-go/types" 25 | corestore "github.com/irisnet/core-sdk-go/types/store" 26 | txtypes "github.com/irisnet/core-sdk-go/types/tx" 27 | "github.com/irisnet/irismod-sdk-go/nft" 28 | log "github.com/sirupsen/logrus" 29 | 30 | "github.com/bianjieai/tibc-relayer-go/internal/pkg/configs" 31 | ) 32 | 33 | const CtxTimeout = 10 * time.Second 34 | const SendMsgDelayTime = 7 * time.Second 35 | 36 | func BatchUpdateETHClient(cfg *configs.Config, endHeight uint64) { 37 | logger := log.WithFields(log.Fields{ 38 | "source_chain": cfg.Chain.Source.Tendermint.ChainName, 39 | "dest_chain": cfg.Chain.Dest.Bsc.ChainName, 40 | }) 41 | if len(cfg.App.ChannelTypes) != 1 { 42 | logger.Fatal("channel_types length must be 1") 43 | } 44 | for _, channelType := range cfg.App.ChannelTypes { 45 | 46 | if channelType != TendermintAndETH && channelType != TendermintAndBsc { 47 | logger.Fatal("only applicable for eth and tendermint") 48 | } 49 | batchUpdateETHClient(cfg, channelType, endHeight, logger) 50 | } 51 | 52 | } 53 | 54 | func batchUpdateETHClient(cfg *configs.Config, channelType string, endHeight uint64, logger *log.Entry) { 55 | 56 | defer func() { 57 | if r := recover(); r != nil { 58 | logger.Println("Recovered in : ", r) 59 | time.Sleep(10 * time.Second) 60 | batchUpdateETHClient(cfg, channelType, endHeight, logger) 61 | } 62 | }() 63 | switch channelType { 64 | case TendermintAndETH: 65 | batchUpdateETHClientRoutine(cfg, endHeight, logger) 66 | case TendermintAndBsc: 67 | batchUpdateBscClientRoutine(cfg, endHeight, logger) 68 | } 69 | 70 | } 71 | 72 | func batchUpdateBscClientRoutine(cfg *configs.Config, endHeight uint64, logger *log.Entry) { 73 | 74 | options := []coretypes.Option{ 75 | coretypes.KeyDAOOption(corestore.NewMemory(corestore.NewMemory(nil))), 76 | coretypes.TimeoutOption(cfg.Chain.Source.Tendermint.RequestTimeout), 77 | coretypes.ModeOption(coretypes.Async), 78 | coretypes.GasOption(cfg.Chain.Source.Tendermint.Gas), 79 | coretypes.CachedOption(true), 80 | } 81 | if cfg.Chain.Source.Tendermint.Algo != "" { 82 | options = append(options, coretypes.AlgoOption(cfg.Chain.Source.Tendermint.Algo)) 83 | } 84 | chainCfg, err := coretypes.NewClientConfig( 85 | cfg.Chain.Source.Tendermint.RPCAddr, 86 | cfg.Chain.Source.Tendermint.GrpcAddr, 87 | cfg.Chain.Source.Tendermint.ChainID, 88 | options..., 89 | ) 90 | if err != nil { 91 | logger.WithField("err_msg", err).Fatal("failed to init chain cfg") 92 | } 93 | 94 | fee := coretypes.NewDecCoins( 95 | coretypes.NewDecCoin( 96 | cfg.Chain.Source.Tendermint.Fee.Denom, 97 | coretypes.NewInt(cfg.Chain.Source.Tendermint.Fee.Amount))) 98 | baseTx := coretypes.BaseTx{ 99 | From: cfg.Chain.Source.Tendermint.Key.Name, 100 | Password: cfg.Chain.Source.Tendermint.Key.Password, 101 | Gas: cfg.Chain.Source.Tendermint.Gas, 102 | Mode: coretypes.Commit, 103 | Fee: fee, 104 | SimulateAndExecute: false, 105 | GasAdjustment: 1.5, 106 | } 107 | 108 | tClient := newTendermintClient(chainCfg, cfg.Chain.Source.Tendermint.ChainName) 109 | address, err := tClient.BaseClient.Import( 110 | cfg.Chain.Source.Tendermint.Key.Name, 111 | cfg.Chain.Source.Tendermint.Key.Password, 112 | cfg.Chain.Source.Tendermint.Key.PrivKeyArmor) 113 | if err != nil { 114 | logger.WithField("err_msg", err).Fatal("failed to get owner err") 115 | } 116 | logger.WithField("address", address).Info("address output") 117 | 118 | owner, err := tClient.QueryAddress(baseTx.From, baseTx.Password) 119 | if err != nil { 120 | logger.WithField("err_msg", err).Fatal("failed to get owner err") 121 | } 122 | logger.WithField("owner", owner.String()).Info("owner output") 123 | ethCli, err := newEthClient(cfg.Chain.Dest.Bsc.URI) 124 | if err != nil { 125 | logger.WithField("err_msg", err).Fatal("failed to eth client") 126 | } 127 | 128 | clientStatus, err := tClient.TIBC.GetClientState(cfg.Chain.Dest.Bsc.ChainName) 129 | if err != nil { 130 | logger.WithField("err_msg", err).Fatal("failed to get eth light client status") 131 | } 132 | 133 | startHeight := clientStatus.GetLatestHeight().GetRevisionHeight() + 1 134 | logger.WithFields(log.Fields{ 135 | "latest_height": clientStatus.GetLatestHeight().GetRevisionHeight(), 136 | "start_height": startHeight, 137 | }).Info() 138 | 139 | var msgs []types.Msg 140 | for i := startHeight; i <= endHeight; i++ { 141 | header, err := getBscHeader(ethCli, i) 142 | if err != nil { 143 | logger.WithField("err_msg", err).Fatal("failed to eth client") 144 | } 145 | anyHeader, err := cryptotypes.NewAnyWithValue(header) 146 | if err != nil { 147 | logger.WithField("err_msg", err).Fatal("failed to get owner err") 148 | } 149 | msg := &tibcclient.MsgUpdateClient{ 150 | ChainName: cfg.Chain.Dest.Bsc.ChainName, 151 | Header: anyHeader, 152 | Signer: owner.String(), 153 | } 154 | 155 | msgs = append(msgs, msg) 156 | if len(msgs) == 10 || (len(msgs) == 1 && i == endHeight) { 157 | resultTx, err := tClient.BuildAndSend(msgs, baseTx) 158 | if err != nil { 159 | logger.WithField("err_msg", err).Error("failed to tx") 160 | panic("failed to BuildAndSend ") 161 | } 162 | logger.WithFields(log.Fields{ 163 | "tx_height": resultTx.Height, 164 | "tx_hash": resultTx.Hash, 165 | "gas_wanted": resultTx.GasWanted, 166 | "gas_used": resultTx.GasUsed, 167 | }).Info("success") 168 | msgs = []types.Msg{} 169 | //time.Sleep(SendMsgDelayTime) 170 | } 171 | } 172 | 173 | } 174 | 175 | func getBscHeader(ethCli *gethethclient.Client, height uint64) (tibctypes.Header, error) { 176 | 177 | ctx, cancel := context.WithTimeout(context.Background(), CtxTimeout) 178 | defer cancel() 179 | blockRes, err := ethCli.BlockByNumber(ctx, new(big.Int).SetUint64(height)) 180 | if err != nil { 181 | return nil, err 182 | } 183 | 184 | return &tibcbcs.Header{ 185 | ParentHash: blockRes.ParentHash().Bytes(), 186 | UncleHash: blockRes.UncleHash().Bytes(), 187 | Coinbase: blockRes.Coinbase().Bytes(), 188 | Root: blockRes.Root().Bytes(), 189 | TxHash: blockRes.TxHash().Bytes(), 190 | ReceiptHash: blockRes.ReceiptHash().Bytes(), 191 | Bloom: blockRes.Bloom().Bytes(), 192 | Difficulty: blockRes.Difficulty().Uint64(), 193 | Height: tibcclient.Height{ 194 | RevisionNumber: 0, 195 | RevisionHeight: height, 196 | }, 197 | GasLimit: blockRes.GasLimit(), 198 | GasUsed: blockRes.GasUsed(), 199 | Time: blockRes.Time(), 200 | Extra: blockRes.Extra(), 201 | MixDigest: blockRes.MixDigest().Bytes(), 202 | Nonce: blockRes.Header().Nonce[:], 203 | }, nil 204 | } 205 | 206 | func batchUpdateETHClientRoutine(cfg *configs.Config, endHeight uint64, logger *log.Entry) { 207 | 208 | options := []coretypes.Option{ 209 | coretypes.KeyDAOOption(corestore.NewMemory(corestore.NewMemory(nil))), 210 | coretypes.TimeoutOption(cfg.Chain.Source.Tendermint.RequestTimeout), 211 | coretypes.ModeOption(coretypes.Async), 212 | coretypes.GasOption(cfg.Chain.Source.Tendermint.Gas), 213 | coretypes.CachedOption(true), 214 | } 215 | if cfg.Chain.Source.Tendermint.Algo != "" { 216 | options = append(options, coretypes.AlgoOption(cfg.Chain.Source.Tendermint.Algo)) 217 | } 218 | chainCfg, err := coretypes.NewClientConfig( 219 | cfg.Chain.Source.Tendermint.RPCAddr, 220 | cfg.Chain.Source.Tendermint.GrpcAddr, 221 | cfg.Chain.Source.Tendermint.ChainID, 222 | options..., 223 | ) 224 | if err != nil { 225 | logger.WithField("err_msg", err).Fatal("failed to init chain cfg") 226 | } 227 | 228 | fee := coretypes.NewDecCoins( 229 | coretypes.NewDecCoin( 230 | cfg.Chain.Source.Tendermint.Fee.Denom, 231 | coretypes.NewInt(cfg.Chain.Source.Tendermint.Fee.Amount))) 232 | baseTx := coretypes.BaseTx{ 233 | From: cfg.Chain.Source.Tendermint.Key.Name, 234 | Password: cfg.Chain.Source.Tendermint.Key.Password, 235 | Gas: cfg.Chain.Source.Tendermint.Gas, 236 | Mode: coretypes.Async, 237 | Fee: fee, 238 | SimulateAndExecute: false, 239 | GasAdjustment: 1.5, 240 | } 241 | 242 | tClient := newTendermintClient(chainCfg, cfg.Chain.Source.Tendermint.ChainName) 243 | address, err := tClient.BaseClient.Import( 244 | cfg.Chain.Source.Tendermint.Key.Name, 245 | cfg.Chain.Source.Tendermint.Key.Password, 246 | cfg.Chain.Source.Tendermint.Key.PrivKeyArmor) 247 | if err != nil { 248 | logger.WithField("err_msg", err).Fatal("failed to get owner err") 249 | } 250 | logger.WithField("address", address).Info("address output") 251 | 252 | owner, err := tClient.QueryAddress(baseTx.From, baseTx.Password) 253 | if err != nil { 254 | logger.WithField("err_msg", err).Fatal("failed to get owner err") 255 | } 256 | logger.WithField("owner", owner.String()).Info("owner output") 257 | ethCli, err := newEthClient(cfg.Chain.Dest.Eth.URI) 258 | if err != nil { 259 | logger.WithField("err_msg", err).Fatal("failed to eth client") 260 | } 261 | 262 | clientStatus, err := tClient.TIBC.GetClientState(cfg.Chain.Dest.Eth.ChainName) 263 | if err != nil { 264 | logger.WithField("err_msg", err).Fatal("failed to get eth light client status") 265 | } 266 | 267 | startHeight := clientStatus.GetLatestHeight().GetRevisionHeight() + 1 268 | logger.WithFields(log.Fields{ 269 | "latest_height": clientStatus.GetLatestHeight().GetRevisionHeight(), 270 | "start_height": startHeight, 271 | }).Info() 272 | 273 | var msgs []types.Msg 274 | for i := startHeight; i <= endHeight; i++ { 275 | header, err := getETHHeader(ethCli, i) 276 | if err != nil { 277 | logger.WithField("err_msg", err).Fatal("failed to eth client") 278 | } 279 | anyHeader, err := cryptotypes.NewAnyWithValue(header) 280 | if err != nil { 281 | logger.WithField("err_msg", err).Fatal("failed to get owner err") 282 | } 283 | msg := &tibcclient.MsgUpdateClient{ 284 | ChainName: cfg.Chain.Dest.Eth.ChainName, 285 | Header: anyHeader, 286 | Signer: owner.String(), 287 | } 288 | 289 | msgs = append(msgs, msg) 290 | if len(msgs) == 2 || (len(msgs) == 1 && i == endHeight) { 291 | resultTx, err := tClient.BuildAndSend(msgs, baseTx) 292 | if err != nil { 293 | logger.WithField("err_msg", err).Error("failed to tx") 294 | panic("failed to BuildAndSend ") 295 | } 296 | logger.WithFields(log.Fields{ 297 | "tx_height": resultTx.Height, 298 | "tx_hash": resultTx.Hash, 299 | "gas_wanted": resultTx.GasWanted, 300 | "gas_used": resultTx.GasUsed, 301 | }).Info("success") 302 | msgs = []types.Msg{} 303 | time.Sleep(SendMsgDelayTime) 304 | } 305 | } 306 | 307 | } 308 | 309 | func getETHHeader(ethCli *gethethclient.Client, height uint64) (tibctypes.Header, error) { 310 | 311 | ctx, cancel := context.WithTimeout(context.Background(), CtxTimeout) 312 | defer cancel() 313 | blockRes, err := ethCli.BlockByNumber(ctx, new(big.Int).SetUint64(height)) 314 | if err != nil { 315 | return nil, err 316 | } 317 | return &tibceth.Header{ 318 | ParentHash: blockRes.ParentHash().Bytes(), 319 | UncleHash: blockRes.UncleHash().Bytes(), 320 | Coinbase: blockRes.Coinbase().Bytes(), 321 | Root: blockRes.Root().Bytes(), 322 | TxHash: blockRes.TxHash().Bytes(), 323 | ReceiptHash: blockRes.ReceiptHash().Bytes(), 324 | Bloom: blockRes.Bloom().Bytes(), 325 | Difficulty: blockRes.Difficulty().String(), 326 | Height: tibcclient.Height{ 327 | RevisionNumber: 0, 328 | RevisionHeight: height, 329 | }, 330 | GasLimit: blockRes.GasLimit(), 331 | GasUsed: blockRes.GasUsed(), 332 | Time: blockRes.Time(), 333 | Extra: blockRes.Extra(), 334 | MixDigest: blockRes.MixDigest().Bytes(), 335 | Nonce: blockRes.Nonce(), 336 | BaseFee: blockRes.BaseFee().String(), 337 | }, nil 338 | } 339 | 340 | func newEthClient(uri string) (*gethethclient.Client, error) { 341 | ctx, cancel := context.WithTimeout(context.Background(), CtxTimeout) 342 | defer cancel() 343 | rpcClient, err := gethrpc.DialContext(ctx, uri) 344 | if err != nil { 345 | return nil, err 346 | } 347 | 348 | ethClient := gethethclient.NewClient(rpcClient) 349 | return ethClient, nil 350 | } 351 | 352 | func newTendermintClient(cfg types.ClientConfig, chainName string) tendermintClient { 353 | encodingConfig := makeEncodingConfig() 354 | // create a instance of baseClient 355 | baseClient := client.NewBaseClient(cfg, encodingConfig, nil) 356 | bankClient := bank.NewClient(baseClient, encodingConfig.Marshaler) 357 | stakingClient := staking.NewClient(baseClient, encodingConfig.Marshaler) 358 | govClient := gov.NewClient(baseClient, encodingConfig.Marshaler) 359 | tibcClient := tibc.NewClient(baseClient, encodingConfig) 360 | nftClient := nft.NewClient(baseClient, encodingConfig.Marshaler) 361 | 362 | tc := &tendermintClient{ 363 | encodingConfig: encodingConfig, 364 | BaseClient: baseClient, 365 | Bank: bankClient, 366 | Staking: stakingClient, 367 | Gov: govClient, 368 | NFT: nftClient, 369 | TIBC: tibcClient, 370 | ChainName: chainName, 371 | } 372 | 373 | tc.RegisterModule( 374 | bankClient, 375 | stakingClient, 376 | govClient, 377 | ) 378 | return *tc 379 | } 380 | 381 | type tendermintClient struct { 382 | encodingConfig types.EncodingConfig 383 | types.BaseClient 384 | Bank bank.Client 385 | Staking staking.Client 386 | Gov gov.Client 387 | NFT nft.Client 388 | TIBC tibc.Client 389 | ChainName string 390 | } 391 | 392 | func (tc tendermintClient) RegisterModule(ms ...types.Module) { 393 | for _, m := range ms { 394 | m.RegisterInterfaceTypes(tc.encodingConfig.InterfaceRegistry) 395 | } 396 | } 397 | 398 | func makeEncodingConfig() types.EncodingConfig { 399 | amino := codec.NewLegacyAmino() 400 | interfaceRegistry := cdctypes.NewInterfaceRegistry() 401 | marshaler := codec.NewProtoCodec(interfaceRegistry) 402 | txCfg := txtypes.NewTxConfig(marshaler, txtypes.DefaultSignModes) 403 | 404 | encodingConfig := types.EncodingConfig{ 405 | InterfaceRegistry: interfaceRegistry, 406 | Marshaler: marshaler, 407 | TxConfig: txCfg, 408 | Amino: amino, 409 | } 410 | registerLegacyAminoCodec(encodingConfig.Amino) 411 | registerInterfaces(encodingConfig.InterfaceRegistry) 412 | return encodingConfig 413 | } 414 | 415 | // RegisterLegacyAminoCodec registers the sdk message type. 416 | func registerLegacyAminoCodec(cdc *codec.LegacyAmino) { 417 | cdc.RegisterInterface((*types.Msg)(nil), nil) 418 | cdc.RegisterInterface((*types.Tx)(nil), nil) 419 | cryptocodec.RegisterCrypto(cdc) 420 | } 421 | 422 | // RegisterInterfaces registers the sdk message type. 423 | func registerInterfaces(registry cdctypes.InterfaceRegistry) { 424 | registry.RegisterInterface("cosmos.v1beta1.Msg", (*types.Msg)(nil)) 425 | txtypes.RegisterInterfaces(registry) 426 | cryptocodec.RegisterInterfaces(registry) 427 | } 428 | -------------------------------------------------------------------------------- /cmd/handlers/config.go: -------------------------------------------------------------------------------- 1 | package handlers 2 | 3 | import ( 4 | "os" 5 | "path" 6 | 7 | "github.com/pelletier/go-toml" 8 | 9 | "github.com/bianjieai/tibc-relayer-go/internal/pkg/configs" 10 | "github.com/bianjieai/tibc-relayer-go/tools" 11 | ) 12 | 13 | func ConfigInit(home string) error { 14 | cfgDir := path.Join(home, tools.DefaultConfigDirName) 15 | cfgPath := path.Join(cfgDir, tools.DefaultConfigName) 16 | if _, err := os.Stat(cfgPath); os.IsNotExist(err) { 17 | // And the home folder doesn't exist 18 | if _, err := os.Stat(home); os.IsNotExist(err) { 19 | // Create the home folder 20 | if err = os.Mkdir(home, os.ModePerm); err != nil { 21 | return err 22 | } 23 | } 24 | // Create the home config folder 25 | if err = os.Mkdir(cfgDir, os.ModePerm); err != nil { 26 | return err 27 | } 28 | } 29 | 30 | // Then create the file... 31 | f, err := os.Create(cfgPath) 32 | if err != nil { 33 | return err 34 | } 35 | defer f.Close() 36 | 37 | // And write the default config to that location... 38 | if _, err = f.Write(defaultConfig()); err != nil { 39 | return err 40 | } 41 | 42 | // And return no error... 43 | return nil 44 | } 45 | 46 | func defaultConfig() []byte { 47 | cfg := configs.NewConfig() 48 | cfg.App.MetricAddr = "0.0.0.0:8083" 49 | cfg.App.Env = "dev" 50 | cfg.App.LogLevel = "debug" 51 | data, err := toml.Marshal(cfg) 52 | if err != nil { 53 | panic(err) 54 | } 55 | return data 56 | } 57 | -------------------------------------------------------------------------------- /cmd/handlers/config_test.go: -------------------------------------------------------------------------------- 1 | package handlers 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestConfigInit(t *testing.T) { 8 | home := ".tibc-relayer" 9 | err := ConfigInit(home) 10 | if err != nil { 11 | 12 | t.Fatal("init config error") 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /cmd/root.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "os" 5 | 6 | "github.com/spf13/cobra" 7 | ) 8 | 9 | var ( 10 | Version = "v0.2.0" 11 | Date = "2021-11-01" 12 | ) 13 | 14 | var rootCmd = &cobra.Command{ 15 | Use: "relayer", 16 | Short: "relayer for tibc", 17 | Run: func(cmd *cobra.Command, args []string) { 18 | cmd.Help() 19 | }, 20 | } 21 | 22 | func Execute() { 23 | if err := rootCmd.Execute(); err != nil { 24 | os.Exit(-1) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /cmd/start.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "io/ioutil" 7 | 8 | "github.com/spf13/cobra" 9 | "github.com/spf13/viper" 10 | 11 | "github.com/bianjieai/tibc-relayer-go/internal/app/relayer" 12 | "github.com/bianjieai/tibc-relayer-go/internal/pkg/configs" 13 | ) 14 | 15 | var ( 16 | localConfig string 17 | 18 | startCmd = &cobra.Command{ 19 | Use: "start", 20 | Short: "Start TIBC relayer.", 21 | Run: func(cmd *cobra.Command, args []string) { 22 | online() 23 | }, 24 | } 25 | ) 26 | 27 | func init() { 28 | rootCmd.AddCommand(startCmd) 29 | startCmd.Flags().StringVarP(&localConfig, "CONFIG", "c", "", "config path: /opt/local.toml") 30 | } 31 | 32 | func online() { 33 | data, err := ioutil.ReadFile(localConfig) 34 | if err != nil { 35 | fmt.Println("Error: get config data error: ", err) 36 | return 37 | } 38 | config, err := readConfig(data) 39 | if err != nil { 40 | fmt.Println("Error: read config error: ", err) 41 | return 42 | } 43 | run(config) 44 | } 45 | 46 | func run(cfg *configs.Config) { 47 | relayer.Serve(cfg) 48 | } 49 | 50 | func readConfig(data []byte) (*configs.Config, error) { 51 | v := viper.New() 52 | v.SetConfigType("toml") 53 | reader := bytes.NewReader(data) 54 | err := v.ReadConfig(reader) 55 | if err != nil { 56 | return nil, err 57 | } 58 | cfg := configs.NewConfig() 59 | if err := v.Unmarshal(cfg); err != nil { 60 | return nil, err 61 | } 62 | return cfg, nil 63 | } 64 | -------------------------------------------------------------------------------- /configs/example.toml: -------------------------------------------------------------------------------- 1 | [app] 2 | 3 | env = "dev" 4 | log_level = "debug" 5 | metric_addr = "0.0.0.0:8083" 6 | 7 | # currently only supports: 8 | # 1. tendermint <---> eth: tendermint_and_eth 9 | # 2. tendermint <---> tendermint: tendermint_and_tendermint 10 | # Currently only supports a pair of child chain interactions: 11 | # len(channel_types) == 1 12 | 13 | channel_types = ["tendermint_and_tendermint"] 14 | 15 | #==========================# 16 | # Dest Config # 17 | #==========================# 18 | 19 | [chain] 20 | 21 | enabled = true 22 | 23 | chain_type = "eth" 24 | 25 | [chain.dest] 26 | [chain.dest.cache] 27 | filename = "dest.json" 28 | start_height = 4 29 | 30 | #==========================# 31 | # Dest Tendermint Config # 32 | #==========================# 33 | 34 | [chain.dest.tendermint] 35 | chain_id = "test" 36 | chain_name = "testCreateClientB" 37 | gas = 0 38 | grpc_addr = "127.0.0.1:9091" 39 | rpc_addr = "tcp://127.0.0.1:36657" 40 | algo = "sm2" 41 | update_client_frequency = 10 # update client frequency, unit hour 42 | request_timeout = 60 43 | clean_packet_enabled = false 44 | 45 | [chain.dest.tendermint.fee] 46 | denom = "stake" 47 | amount = 100 48 | 49 | [chain.dest.tendermint.key] 50 | name = "your_dest_chain_relayer_name" 51 | password = "your_dest_chain_relayer_password" 52 | priv_key_armor = "your_dest_chain_relayer_priv_key_armor" 53 | 54 | [[chain.dest.tendermint.allows]] 55 | contract_addr = "addr_00" 56 | senders = ["xxxxxxx000"] 57 | 58 | [[chain.dest.tendermint.allows]] 59 | contract_addr = "addr_01" 60 | senders = ["xxxxxxx001"] 61 | 62 | #==========================# 63 | # Dest ETH Config # 64 | #==========================# 65 | [chain.dest.eth] 66 | chain_id = 3 67 | chain_name = "eth" 68 | update_client_frequency = 2 # 69 | uri = "youre_request_eth_uri" # example: http://xxxxxx 70 | gas_limit = 2000000 71 | max_gas_price = 150000000000 72 | comment_slot = 104 73 | tip_coefficient = 0.2 74 | 75 | [chain.dest.eth.eth_contracts] 76 | [chain.dest.eth.eth_contracts.packet] 77 | addr = "your_packet_contract_addr" 78 | topic = "PacketSent((uint64,string,string,string,string,bytes))" 79 | opt_priv_key = "your_eth_priv_key" 80 | 81 | [chain.dest.eth.eth_contracts.ack_packet] 82 | addr = "your_packet_contract_addr" 83 | topic = "AckWritten((uint64,string,string,string,string,bytes),bytes)" 84 | opt_priv_key = "your_eth_priv_key" 85 | 86 | [chain.dest.eth.eth_contracts.clean_packet] 87 | addr = "your_packet_contract_addr" 88 | topic = "CleanPacketSent((uint64,string,string,string))" 89 | opt_priv_key = "your_eth_priv_key" 90 | 91 | [chain.dest.eth.eth_contracts.client] 92 | addr = "your_client_manager_contract_addr" 93 | topic = "" 94 | opt_priv_key = "your_eth_priv_key" 95 | 96 | #==========================# 97 | # Source Config # 98 | #==========================# 99 | 100 | [chain.source] 101 | 102 | chain_type = "tendermint" 103 | enabled = true 104 | 105 | [chain.source.cache] 106 | filename = "source.json" 107 | start_height = 4 108 | 109 | #==========================# 110 | # Source Tendermint Config # 111 | #==========================# 112 | 113 | [chain.source.tendermint] 114 | 115 | chain_id = "test" 116 | chain_name = "testCreateClientA" 117 | gas = 0 118 | grpc_addr = "127.0.0.1:9090" 119 | rpc_addr = "tcp://127.0.0.1:26657" 120 | algo = "sm2" # if your chain is IRITA 121 | update_client_frequency = 2 122 | request_timeout = 60 123 | clean_packet_enabled = false 124 | 125 | [chain.source.tendermint.fee] 126 | denom = "stake" 127 | amount = 100 128 | 129 | [chain.source.tendermint.key] 130 | 131 | name = "your_source_chain_relayer_name" 132 | password = "your_source_chain_relayer_password" 133 | priv_key_armor = "your_source_chain_relayer_priv_key_armor" 134 | 135 | [[chain.source.tendermint.allows]] 136 | contract_addr = "addr_00" 137 | senders = ["xxxxxxx000"] 138 | 139 | [[chain.source.tendermint.allows]] 140 | contract_addr = "addr_01" 141 | senders = ["xxxxxxx001"] 142 | 143 | 144 | #==========================# 145 | # Source ETH Config # 146 | #==========================# 147 | [chain.source.eth] 148 | chain_id = 3 149 | chain_name = "eth" 150 | update_client_frequency = 2 # 151 | uri = "youre_request_eth_uri" # example: http://xxxxxx 152 | gas_limit = 2000000 153 | max_gas_price = 150000000000 154 | comment_slot = 104 155 | tip_coefficient = 0.2 156 | 157 | [chain.source.eth.eth_contracts] 158 | [chain.source.eth.eth_contracts.packet] 159 | addr = "your_packet_contract_addr" 160 | topic = "PacketSent((uint64,string,string,string,string,bytes))" 161 | opt_priv_key = "your_eth_priv_key" 162 | 163 | [chain.source.eth.eth_contracts.ack_packet] 164 | addr = "your_packet_contract_addr" 165 | topic = "AckWritten((uint64,string,string,string,string,bytes),bytes)" 166 | opt_priv_key = "your_eth_priv_key" 167 | 168 | [chain.source.eth.eth_contracts.clean_packet] 169 | addr = "your_packet_contract_addr" 170 | topic = "CleanPacketSent((uint64,string,string,string))" 171 | opt_priv_key = "your_eth_priv_key" 172 | 173 | [chain.source.eth.eth_contracts.client] 174 | addr = "your_client_manager_contract_addr" 175 | topic = "" 176 | opt_priv_key = "your_eth_priv_key" -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/bianjieai/tibc-relayer-go 2 | 3 | go 1.17 4 | 5 | require ( 6 | github.com/bianjieai/tibc-sdk-go v0.0.0-20220701022618-62f95eee5558 7 | github.com/ethereum/go-ethereum v1.10.8 8 | github.com/go-kit/kit v0.11.0 9 | github.com/irisnet/core-sdk-go v0.0.0-20211019075829-8bb6cca8d315 10 | github.com/irisnet/irismod-sdk-go/nft v0.0.0-20210810032454-3ae775c15f1e 11 | github.com/jasonlvhit/gocron v0.0.1 12 | github.com/pelletier/go-toml v1.9.3 13 | github.com/prometheus/client_golang v1.11.0 14 | github.com/sirupsen/logrus v1.8.1 15 | github.com/spf13/cobra v1.1.3 16 | github.com/spf13/viper v1.7.1 17 | github.com/tendermint/tendermint v0.34.11 18 | ) 19 | 20 | require ( 21 | github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d // indirect 22 | github.com/DataDog/zstd v1.4.5 // indirect 23 | github.com/StackExchange/wmi v0.0.0-20180116203802-5d049714c4a6 // indirect 24 | github.com/VictoriaMetrics/fastcache v1.6.0 // indirect 25 | github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 // indirect 26 | github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d // indirect 27 | github.com/avast/retry-go v3.0.0+incompatible // indirect 28 | github.com/beorn7/perks v1.0.1 // indirect 29 | github.com/bluele/gcache v0.0.2 // indirect 30 | github.com/btcsuite/btcd v0.21.0-beta // indirect 31 | github.com/btcsuite/btcutil v1.0.2 // indirect 32 | github.com/cespare/xxhash v1.1.0 // indirect 33 | github.com/cespare/xxhash/v2 v2.1.1 // indirect 34 | github.com/confio/ics23/go v0.6.6 // indirect 35 | github.com/cosmos/go-bip39 v1.0.0 // indirect 36 | github.com/davecgh/go-spew v1.1.1 // indirect 37 | github.com/deckarep/golang-set v0.0.0-20180603214616-504e848d77ea // indirect 38 | github.com/dgraph-io/badger/v2 v2.2007.2 // indirect 39 | github.com/dgraph-io/ristretto v0.0.3 // indirect 40 | github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 // indirect 41 | github.com/dustin/go-humanize v1.0.0 // indirect 42 | github.com/fsnotify/fsnotify v1.4.9 // indirect 43 | github.com/go-logfmt/logfmt v0.5.0 // indirect 44 | github.com/go-ole/go-ole v1.2.1 // indirect 45 | github.com/go-stack/stack v1.8.0 // indirect 46 | github.com/gogo/protobuf v1.3.3 // indirect 47 | github.com/golang/protobuf v1.5.2 // indirect 48 | github.com/golang/snappy v0.0.3 // indirect 49 | github.com/google/btree v1.0.0 // indirect 50 | github.com/google/uuid v1.1.5 // indirect 51 | github.com/gorilla/websocket v1.4.2 // indirect 52 | github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect 53 | github.com/gtank/merlin v0.1.1 // indirect 54 | github.com/gtank/ristretto255 v0.1.2 // indirect 55 | github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d // indirect 56 | github.com/hashicorp/hcl v1.0.0 // indirect 57 | github.com/holiman/bloomfilter/v2 v2.0.3 // indirect 58 | github.com/huin/goupnp v1.0.2 // indirect 59 | github.com/inconshreveable/mousetrap v1.0.0 // indirect 60 | github.com/jackpal/go-nat-pmp v1.0.2-0.20160603034137-1fa385a6f458 // indirect 61 | github.com/jmhodges/levigo v1.0.0 // indirect 62 | github.com/libp2p/go-buffer-pool v0.0.2 // indirect 63 | github.com/magiconair/properties v1.8.5 // indirect 64 | github.com/mattn/go-runewidth v0.0.9 // indirect 65 | github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect 66 | github.com/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643 // indirect 67 | github.com/mitchellh/mapstructure v1.1.2 // indirect 68 | github.com/olekukonko/tablewriter v0.0.5 // indirect 69 | github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 // indirect 70 | github.com/pkg/errors v0.9.1 // indirect 71 | github.com/prometheus/client_model v0.2.0 // indirect 72 | github.com/prometheus/common v0.26.0 // indirect 73 | github.com/prometheus/procfs v0.6.0 // indirect 74 | github.com/prometheus/tsdb v0.7.1 // indirect 75 | github.com/rcrowley/go-metrics v0.0.0-20200313005456-10cdbea86bc0 // indirect 76 | github.com/regen-network/cosmos-proto v0.3.1 // indirect 77 | github.com/rjeczalik/notify v0.9.1 // indirect 78 | github.com/sasha-s/go-deadlock v0.2.0 // indirect 79 | github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible // indirect 80 | github.com/spf13/afero v1.1.2 // indirect 81 | github.com/spf13/cast v1.3.0 // indirect 82 | github.com/spf13/jwalterweatherman v1.0.0 // indirect 83 | github.com/spf13/pflag v1.0.5 // indirect 84 | github.com/subosito/gotenv v1.2.0 // indirect 85 | github.com/syndtr/goleveldb v1.0.1-0.20210305035536-64b5b1c73954 // indirect 86 | github.com/tecbot/gorocksdb v0.0.0-20191217155057-f0fad39f321c // indirect 87 | github.com/tendermint/crypto v0.0.0-20191022145703-50d29ede1e15 // indirect 88 | github.com/tendermint/go-amino v0.16.0 // indirect 89 | github.com/tendermint/tm-db v0.6.4 // indirect 90 | github.com/tjfoc/gmsm v1.4.0 // indirect 91 | github.com/tklauser/go-sysconf v0.3.5 // indirect 92 | github.com/tklauser/numcpus v0.2.2 // indirect 93 | go.etcd.io/bbolt v1.3.5 // indirect 94 | golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2 // indirect 95 | golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d // indirect 96 | golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect 97 | golang.org/x/sys v0.0.0-20210816183151-1e6c022a8912 // indirect 98 | golang.org/x/text v0.3.6 // indirect 99 | google.golang.org/genproto v0.0.0-20210805201207-89edb61ffb67 // indirect 100 | google.golang.org/grpc v1.39.1 // indirect 101 | google.golang.org/protobuf v1.27.1 // indirect 102 | gopkg.in/alecthomas/kingpin.v2 v2.2.6 // indirect 103 | gopkg.in/ini.v1 v1.51.0 // indirect 104 | gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce // indirect 105 | gopkg.in/yaml.v2 v2.4.0 // indirect 106 | ) 107 | 108 | replace ( 109 | github.com/gogo/protobuf => github.com/regen-network/protobuf v1.3.2-alpha.regen.4 110 | github.com/irisnet/core-sdk-go => github.com/irisnet/core-sdk-go v0.0.0-20211019075829-8bb6cca8d315 111 | github.com/tendermint/tendermint => github.com/bianjieai/tendermint v0.34.1-irita-210113 112 | ) 113 | -------------------------------------------------------------------------------- /internal/app/relayer/app.go: -------------------------------------------------------------------------------- 1 | package relayer 2 | 3 | import ( 4 | "net/http" 5 | 6 | "github.com/jasonlvhit/gocron" 7 | "github.com/prometheus/client_golang/prometheus/promhttp" 8 | log "github.com/sirupsen/logrus" 9 | 10 | "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/services" 11 | "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/services/channels" 12 | "github.com/bianjieai/tibc-relayer-go/internal/pkg/configs" 13 | "github.com/bianjieai/tibc-relayer-go/internal/pkg/initialization" 14 | ) 15 | 16 | func Serve(cfg *configs.Config) { 17 | 18 | logger := initialization.Logger(cfg) 19 | logger.Info("1. service init relayers ") 20 | channelMap := initialization.ChannelMap(cfg, logger) 21 | logger.Info("2. service init listener & TaskPerformer") 22 | listener := services.NewListener(channelMap, logger) 23 | logger.Info("3. service start & crontab start") 24 | go runTask(channelMap, logger) 25 | go runMetricHandler(cfg, logger) 26 | logger.Fatal(listener.Listen()) 27 | } 28 | 29 | func runTask(channelMap map[string]channels.IChannel, logger *log.Logger) { 30 | s := gocron.NewScheduler() 31 | for channelName := range channelMap { 32 | // execute every x hours 33 | channel := channelMap[channelName] 34 | doFunc := func(channel channels.IChannel) { 35 | err := channel.UpdateClient() 36 | if err != nil { 37 | logger.Error(err) 38 | } 39 | } 40 | updateClientFrequency := channel.UpdateClientFrequency() 41 | s.Every(updateClientFrequency).Hours().Do(doFunc, channel) 42 | } 43 | 44 | _, nextTime := s.NextRun() 45 | logger.WithFields(log.Fields{"next_time": nextTime}).Info() 46 | <-s.Start() 47 | } 48 | 49 | func runMetricHandler(cfg *configs.Config, logger *log.Logger) { 50 | logger.Info("scanner metric start: addr ", cfg.App.MetricAddr) 51 | metricMux := http.NewServeMux() 52 | metricMux.Handle("/metrics", promhttp.Handler()) 53 | logger.Fatal(http.ListenAndServe(cfg.App.MetricAddr, metricMux)) 54 | } 55 | -------------------------------------------------------------------------------- /internal/app/relayer/domain/README.md: -------------------------------------------------------------------------------- 1 | ## domain 层 -------------------------------------------------------------------------------- /internal/app/relayer/domain/cache_file_write.go: -------------------------------------------------------------------------------- 1 | package domain 2 | 3 | import ( 4 | "encoding/json" 5 | "os" 6 | "path" 7 | 8 | "github.com/bianjieai/tibc-relayer-go/internal/pkg/types/cache" 9 | ) 10 | 11 | type CacheFileWriter struct { 12 | homeDir string 13 | cacheDir string 14 | cacheFilename string 15 | } 16 | 17 | func NewCacheFileWriter(homeDir, cacheDir, cacheFilename string) *CacheFileWriter { 18 | return &CacheFileWriter{homeDir: homeDir, cacheDir: cacheDir, cacheFilename: cacheFilename} 19 | } 20 | 21 | func (w *CacheFileWriter) Write(height uint64) error { 22 | 23 | cacheDataObj := &cache.Data{} 24 | cacheDataObj.LatestHeight = height 25 | 26 | cacheDataWriteBytes, err := json.Marshal(cacheDataObj) 27 | if err != nil { 28 | return err 29 | } 30 | 31 | cacheDir := path.Join(w.homeDir, w.cacheDir) 32 | filename := path.Join(cacheDir, w.cacheFilename) 33 | if _, err := os.Stat(filename); os.IsNotExist(err) { 34 | // And the home folder doesn't exist 35 | if _, err := os.Stat(w.homeDir); os.IsNotExist(err) { 36 | // Create the home folder 37 | if err = os.Mkdir(w.homeDir, os.ModePerm); err != nil { 38 | return err 39 | } 40 | } 41 | // Create the home config folder 42 | if _, err := os.Stat(cacheDir); os.IsNotExist(err) { 43 | // Create the home folder 44 | if err = os.Mkdir(cacheDir, os.ModePerm); err != nil { 45 | return err 46 | } 47 | } 48 | // Then create the file... 49 | file, err := os.Create(filename) 50 | if err != nil { 51 | return err 52 | } 53 | defer file.Close() 54 | 55 | if _, err = file.Write(cacheDataWriteBytes); err != nil { 56 | return err 57 | } 58 | 59 | } else { 60 | file, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm) 61 | if err != nil { 62 | return err 63 | } 64 | defer file.Close() 65 | if _, err = file.Write(cacheDataWriteBytes); err != nil { 66 | return err 67 | } 68 | } 69 | return nil 70 | } 71 | -------------------------------------------------------------------------------- /internal/app/relayer/domain/cache_file_write_test.go: -------------------------------------------------------------------------------- 1 | package domain 2 | 3 | import ( 4 | "os" 5 | "path/filepath" 6 | "testing" 7 | ) 8 | 9 | func TestCacheFileWriter_Write(t *testing.T) { 10 | cfgDirName := ".tibc-relayer" 11 | userDir, _ := os.UserHomeDir() 12 | homeDir := filepath.Join(userDir, cfgDirName) 13 | dir := "cache" 14 | filename := "iris.json" 15 | writer := NewCacheFileWriter(homeDir, dir, filename) 16 | err := writer.Write(1) 17 | if err != nil { 18 | t.Fatal(err) 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /internal/app/relayer/domain/context.go: -------------------------------------------------------------------------------- 1 | package domain 2 | 3 | import "github.com/irisnet/core-sdk-go/types" 4 | 5 | type QueueMetaData struct { 6 | Timestamp uint64 7 | Height uint64 8 | RecvPackets types.Msgs 9 | } 10 | 11 | type Context struct { 12 | height uint64 13 | chainName string 14 | 15 | queue []QueueMetaData 16 | } 17 | 18 | func NewContext(height uint64, chainName string) *Context { 19 | return &Context{height: height, chainName: chainName, queue: []QueueMetaData{}} 20 | } 21 | 22 | // Height return the current height of the chain 23 | func (ctx *Context) Height() uint64 { 24 | return ctx.height 25 | } 26 | 27 | func (ctx *Context) IncrHeight() { 28 | ctx.height += 1 29 | } 30 | 31 | func (ctx *Context) DecrHeight() { 32 | ctx.height -= 1 33 | } 34 | 35 | func (ctx *Context) SetHeight(height uint64) { 36 | ctx.height = height 37 | } 38 | 39 | // ChainName return the ChainName of the chain 40 | func (ctx *Context) ChainName() string { 41 | return ctx.chainName 42 | } 43 | 44 | func (ctx *Context) Queue() []QueueMetaData { 45 | return ctx.queue 46 | } 47 | 48 | func (ctx *Context) SetQueue(queue []QueueMetaData) { 49 | ctx.queue = queue 50 | } 51 | 52 | func (ctx *Context) PushQueue(queue QueueMetaData) { 53 | ctx.queue = append(ctx.queue, queue) 54 | } 55 | -------------------------------------------------------------------------------- /internal/app/relayer/repostitory/README.md: -------------------------------------------------------------------------------- 1 | ## repo 层 -------------------------------------------------------------------------------- /internal/app/relayer/repostitory/bsc/bsc_client_test.go: -------------------------------------------------------------------------------- 1 | package bsc 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | repotypes "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/repostitory/types" 8 | 9 | gethcmn "github.com/ethereum/go-ethereum/common" 10 | 11 | "github.com/ethereum/go-ethereum/accounts/abi" 12 | 13 | "github.com/bianjieai/tibc-relayer-go/internal/pkg/types/constant" 14 | ) 15 | 16 | func TestNewEth(t *testing.T) { 17 | //ropsten := "https://rinkeby.infura.io/v3/023f2af0f670457d9c4ea9cb524f0810" 18 | ropsten := "https://ropsten.infura.io/v3/023f2af0f670457d9c4ea9cb524f0810" 19 | optPrivKey := "c59f553aa4d23dad1db5b42aa8d72ce98223e29e4e6f873d95b1ced451edad39" 20 | var chainID uint64 = 3 21 | 22 | contractCfgGroup := NewContractCfgGroup() 23 | contractCfgGroup.Packet.Addr = "0x6c2d2868487665C766740ec4cAD006110CfDCff8" 24 | contractCfgGroup.Packet.Topic = "PacketSent((uint64,string,string,string,string,bytes))" 25 | contractCfgGroup.Packet.OptPrivKey = optPrivKey 26 | 27 | contractCfgGroup.AckPacket.Addr = "0x6c2d2868487665C766740ec4cAD006110CfDCff8" 28 | contractCfgGroup.AckPacket.Topic = "AckWritten((uint64,string,string,string,string,bytes),bytes)" 29 | contractCfgGroup.AckPacket.OptPrivKey = optPrivKey 30 | 31 | contractCfgGroup.CleanPacket.Addr = "0x6c2d2868487665C766740ec4cAD006110CfDCff8" 32 | contractCfgGroup.CleanPacket.Topic = "CleanPacketSent((uint64,string,string,string))" 33 | contractCfgGroup.CleanPacket.OptPrivKey = optPrivKey 34 | 35 | contractCfgGroup.Client.Addr = "0x5845092693e6708dEDAF6489719963F76d31C51C" 36 | contractCfgGroup.Client.Topic = "" 37 | contractCfgGroup.Client.OptPrivKey = optPrivKey 38 | 39 | contractBindOptsCfg := NewContractBindOptsCfg() 40 | contractBindOptsCfg.ChainID = chainID 41 | contractBindOptsCfg.ClientPrivKey = optPrivKey 42 | contractBindOptsCfg.PacketPrivKey = optPrivKey 43 | contractBindOptsCfg.GasLimit = 2000000 44 | //contractBindOptsCfg.GasPrice = 1500000000 45 | 46 | chainCfg := NewChainConfig() 47 | chainCfg.ContractCfgGroup = contractCfgGroup 48 | chainCfg.ContractBindOptsCfg = contractBindOptsCfg 49 | chainCfg.ChainType = constant.ETH 50 | chainCfg.ChainName = "ETH" 51 | chainCfg.ChainURI = ropsten 52 | chainCfg.ChainID = chainID 53 | chainCfg.Slot = 4 54 | chainCfg.UpdateClientFrequency = 10 55 | 56 | bscClient, err := NewBsc(chainCfg) 57 | if err != nil { 58 | t.Fatal(err) 59 | } 60 | latestHeight, err := bscClient.GetLatestHeight() 61 | if err != nil { 62 | t.Fatal(err) 63 | } 64 | t.Log(latestHeight) 65 | bscClient.GetProof("eth-testnet", "irishub-testnet", 3, latestHeight, repotypes.CommitmentPoof) 66 | 67 | //packets, err := ethClient.GetPackets(11128997) 68 | ////packets, err := ethClient.GetPackets(11128966) 69 | // 70 | //if err != nil { 71 | // t.Fatal(err) 72 | //} 73 | //t.Log(packets) 74 | 75 | } 76 | 77 | func Test_Hex(t *testing.T) { 78 | 79 | str := "0000000000000000000000000000000000000000000000000000000000000003" 80 | dataBytes := gethcmn.HexToHash(str) 81 | args := abi.Arguments{ 82 | abi.Argument{Type: Uint64}, 83 | } 84 | 85 | headerBytes, err := args.Unpack(dataBytes.Bytes()) 86 | if err != nil { 87 | return 88 | } 89 | fmt.Println("headerBytes: ", headerBytes) 90 | } 91 | -------------------------------------------------------------------------------- /internal/app/relayer/repostitory/bsc/config.go: -------------------------------------------------------------------------------- 1 | package bsc 2 | 3 | func NewChainConfig() *ChainConfig { 4 | return &ChainConfig{} 5 | } 6 | 7 | type ChainConfig struct { 8 | ChainType string 9 | ChainName string 10 | UpdateClientFrequency uint64 11 | ChainURI string 12 | ChainID uint64 13 | 14 | Slot int64 15 | TipCoefficient float64 16 | 17 | ContractCfgGroup *ContractCfgGroup 18 | ContractBindOptsCfg *ContractBindOptsCfg 19 | } 20 | 21 | func NewContractCfgGroup() *ContractCfgGroup { 22 | return &ContractCfgGroup{} 23 | } 24 | 25 | type ContractCfgGroup struct { 26 | Client ContractCfg 27 | Packet ContractCfg 28 | AckPacket ContractCfg 29 | CleanPacket ContractCfg 30 | } 31 | 32 | type ContractCfg struct { 33 | Addr string 34 | Topic string 35 | OptPrivKey string 36 | } 37 | 38 | func NewContractBindOptsCfg() *ContractBindOptsCfg { 39 | return &ContractBindOptsCfg{} 40 | } 41 | 42 | type ContractBindOptsCfg struct { 43 | ClientPrivKey string 44 | PacketPrivKey string 45 | GasLimit uint64 46 | MaxGasPrice uint64 47 | ChainID uint64 48 | } 49 | -------------------------------------------------------------------------------- /internal/app/relayer/repostitory/eth/config.go: -------------------------------------------------------------------------------- 1 | package eth 2 | 3 | func NewChainConfig() *ChainConfig { 4 | return &ChainConfig{} 5 | } 6 | 7 | type ChainConfig struct { 8 | ChainType string 9 | ChainName string 10 | UpdateClientFrequency uint64 11 | ChainURI string 12 | ChainID uint64 13 | 14 | Slot int64 15 | TipCoefficient float64 16 | 17 | ContractCfgGroup *ContractCfgGroup 18 | ContractBindOptsCfg *ContractBindOptsCfg 19 | } 20 | 21 | func NewContractCfgGroup() *ContractCfgGroup { 22 | return &ContractCfgGroup{} 23 | } 24 | 25 | type ContractCfgGroup struct { 26 | Client ContractCfg 27 | Packet ContractCfg 28 | AckPacket ContractCfg 29 | CleanPacket ContractCfg 30 | } 31 | 32 | type ContractCfg struct { 33 | Addr string 34 | Topic string 35 | OptPrivKey string 36 | } 37 | 38 | func NewContractBindOptsCfg() *ContractBindOptsCfg { 39 | return &ContractBindOptsCfg{} 40 | } 41 | 42 | type ContractBindOptsCfg struct { 43 | ClientPrivKey string 44 | PacketPrivKey string 45 | GasLimit uint64 46 | MaxGasPrice uint64 47 | ChainID uint64 48 | } 49 | -------------------------------------------------------------------------------- /internal/app/relayer/repostitory/eth/eth_client.go: -------------------------------------------------------------------------------- 1 | package eth 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "encoding/json" 7 | "fmt" 8 | "math/big" 9 | "strings" 10 | "time" 11 | 12 | "github.com/ethereum/go-ethereum/common/hexutil" 13 | 14 | "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/repostitory" 15 | "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/repostitory/eth/contracts" 16 | repotypes "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/repostitory/types" 17 | "github.com/bianjieai/tibc-relayer-go/internal/pkg/types/errors" 18 | "github.com/bianjieai/tibc-relayer-go/tools" 19 | 20 | geth "github.com/ethereum/go-ethereum" 21 | "github.com/ethereum/go-ethereum/accounts/abi" 22 | "github.com/ethereum/go-ethereum/accounts/abi/bind" 23 | gethcmn "github.com/ethereum/go-ethereum/common" 24 | gethtypes "github.com/ethereum/go-ethereum/core/types" 25 | gethcrypto "github.com/ethereum/go-ethereum/crypto" 26 | gethethclient "github.com/ethereum/go-ethereum/ethclient" 27 | "github.com/ethereum/go-ethereum/ethclient/gethclient" 28 | gethrpc "github.com/ethereum/go-ethereum/rpc" 29 | 30 | tibcclient "github.com/bianjieai/tibc-sdk-go/modules/core/client" 31 | "github.com/bianjieai/tibc-sdk-go/modules/core/packet" 32 | tibceth "github.com/bianjieai/tibc-sdk-go/modules/light-clients/eth" 33 | tibctendermint "github.com/bianjieai/tibc-sdk-go/modules/light-clients/tendermint" 34 | tibctypes "github.com/bianjieai/tibc-sdk-go/modules/types" 35 | "github.com/irisnet/core-sdk-go/types" 36 | ) 37 | 38 | var _ repostitory.IChain = new(Eth) 39 | 40 | const CtxTimeout = 10 * time.Second 41 | const TryGetGasPriceTimeInterval = 10 * time.Second 42 | 43 | var ( 44 | Uint64, _ = abi.NewType("uint64", "", nil) 45 | Bytes32, _ = abi.NewType("bytes32", "", nil) 46 | Bytes, _ = abi.NewType("bytes", "", nil) 47 | String, _ = abi.NewType("string", "", nil) 48 | ) 49 | 50 | type Eth struct { 51 | uri string 52 | chainName string 53 | chainType string 54 | updateClientFrequency uint64 55 | 56 | contractCfgGroup *ContractCfgGroup 57 | contracts *contractGroup 58 | bindOpts *bindOpts 59 | 60 | slot int64 61 | maxGasPrice *big.Int 62 | tipCoefficient float64 63 | 64 | ethClient *gethethclient.Client 65 | gethCli *gethclient.Client 66 | gethRpcCli *gethrpc.Client 67 | 68 | //amino codec.Marshaler 69 | } 70 | 71 | func NewEth(config *ChainConfig) (repostitory.IChain, error) { 72 | ctx, cancel := context.WithTimeout(context.Background(), CtxTimeout) 73 | defer cancel() 74 | rpcClient, err := gethrpc.DialContext(ctx, config.ChainURI) 75 | if err != nil { 76 | return nil, err 77 | } 78 | 79 | ethClient := gethethclient.NewClient(rpcClient) 80 | gethCli := gethclient.New(rpcClient) 81 | 82 | contractGroup, err := newContractGroup(ethClient, config.ContractCfgGroup) 83 | if err != nil { 84 | return nil, err 85 | } 86 | 87 | tmpBindOpts, err := newBindOpts(config.ContractBindOptsCfg) 88 | 89 | if err != nil { 90 | return nil, err 91 | } 92 | 93 | return &Eth{ 94 | chainType: config.ChainType, 95 | chainName: config.ChainName, 96 | updateClientFrequency: config.UpdateClientFrequency, 97 | contractCfgGroup: config.ContractCfgGroup, 98 | ethClient: ethClient, 99 | gethCli: gethCli, 100 | gethRpcCli: rpcClient, 101 | contracts: contractGroup, 102 | bindOpts: tmpBindOpts, 103 | slot: config.Slot, 104 | tipCoefficient: config.TipCoefficient, 105 | maxGasPrice: new(big.Int).SetUint64(config.ContractBindOptsCfg.MaxGasPrice), 106 | }, nil 107 | } 108 | 109 | func (eth *Eth) RecvPackets(msgs types.Msgs) (*repotypes.ResultTx, types.Error) { 110 | resultTx := &repotypes.ResultTx{} 111 | 112 | for _, d := range msgs { 113 | 114 | switch d.Type() { 115 | case "recv_packet": 116 | msg := d.(*packet.MsgRecvPacket) 117 | 118 | tmpPack := contracts.PacketTypesPacket{ 119 | Sequence: msg.Packet.Sequence, 120 | Port: msg.Packet.Port, 121 | DestChain: msg.Packet.DestinationChain, 122 | SourceChain: msg.Packet.SourceChain, 123 | RelayChain: msg.Packet.RelayChain, 124 | Data: msg.Packet.Data, 125 | } 126 | height := contracts.HeightData{ 127 | RevisionNumber: msg.ProofHeight.RevisionNumber, 128 | RevisionHeight: msg.ProofHeight.RevisionHeight, 129 | } 130 | 131 | err := eth.setPacketOpts() 132 | if err != nil { 133 | return nil, types.Wrap(err) 134 | } 135 | result, err := eth.contracts.Packet.RecvPacket( 136 | eth.bindOpts.packetTransactOpts, 137 | tmpPack, 138 | msg.ProofCommitment, 139 | height) 140 | if err != nil { 141 | return nil, types.Wrap(err) 142 | } 143 | resultTx.GasUsed += int64(result.Gas()) 144 | resultTx.Hash = resultTx.Hash + "," + result.Hash().String() 145 | case "acknowledge_packet": 146 | msg := d.(*packet.MsgAcknowledgement) 147 | tmpPack := contracts.PacketTypesPacket{ 148 | Sequence: msg.Packet.Sequence, 149 | Port: msg.Packet.Port, 150 | DestChain: msg.Packet.DestinationChain, 151 | SourceChain: msg.Packet.SourceChain, 152 | RelayChain: msg.Packet.RelayChain, 153 | Data: msg.Packet.Data, 154 | } 155 | height := contracts.HeightData{ 156 | RevisionNumber: msg.ProofHeight.RevisionNumber, 157 | RevisionHeight: msg.ProofHeight.RevisionHeight, 158 | } 159 | 160 | err := eth.setPacketOpts() 161 | if err != nil { 162 | return nil, types.Wrap(err) 163 | } 164 | 165 | result, err := eth.contracts.Packet.AcknowledgePacket( 166 | eth.bindOpts.packetTransactOpts, 167 | tmpPack, msg.Acknowledgement, msg.ProofAcked, 168 | height) 169 | if err != nil { 170 | return nil, types.Wrap(err) 171 | } 172 | resultTx.GasUsed += int64(result.Gas()) 173 | resultTx.Hash = resultTx.Hash + "," + result.Hash().String() 174 | case "recv_clean_packet": 175 | msg := d.(*packet.MsgRecvCleanPacket) 176 | cleanPack := contracts.PacketTypesCleanPacket{ 177 | Sequence: msg.CleanPacket.Sequence, 178 | DestChain: msg.CleanPacket.DestinationChain, 179 | SourceChain: msg.CleanPacket.SourceChain, 180 | RelayChain: msg.CleanPacket.RelayChain, 181 | } 182 | 183 | err := eth.setPacketOpts() 184 | if err != nil { 185 | return nil, types.Wrap(err) 186 | } 187 | 188 | result, err := eth.contracts.Packet.CleanPacket( 189 | eth.bindOpts.packetTransactOpts, 190 | cleanPack, 191 | ) 192 | if err != nil { 193 | return nil, types.Wrap(err) 194 | } 195 | resultTx.GasUsed += int64(result.Gas()) 196 | resultTx.Hash = resultTx.Hash + "," + result.Hash().String() 197 | } 198 | 199 | } 200 | 201 | resultTx.Hash = strings.Trim(resultTx.Hash, ",") 202 | 203 | return resultTx, nil 204 | } 205 | 206 | func (eth *Eth) UpdateClient(header tibctypes.Header, chainName string) (string, error) { 207 | h := header.(*tibctendermint.Header) 208 | args := abi.Arguments{ 209 | abi.Argument{Type: Uint64}, 210 | abi.Argument{Type: Uint64}, 211 | abi.Argument{Type: Uint64}, 212 | abi.Argument{Type: Bytes32}, 213 | abi.Argument{Type: Bytes32}, 214 | } 215 | timestamp := uint64(h.GetTime().Unix()) 216 | revisionNumber := h.GetHeight().GetRevisionNumber() 217 | revisionHeight := h.GetHeight().GetRevisionHeight() 218 | 219 | var appHash [32]byte 220 | copy(appHash[:], h.GetHeader().AppHash[:32]) 221 | 222 | var nextValidatorsHash [32]byte 223 | copy(nextValidatorsHash[:], h.GetHeader().NextValidatorsHash[:32]) 224 | 225 | headerBytes, err := args.Pack( 226 | &revisionNumber, 227 | &revisionHeight, 228 | ×tamp, 229 | appHash, 230 | nextValidatorsHash, 231 | ) 232 | 233 | err = eth.setClientOpts() 234 | if err != nil { 235 | return "", err 236 | } 237 | 238 | result, err := eth.contracts.Client.UpdateClient(eth.bindOpts.client, chainName, headerBytes) 239 | if err != nil { 240 | return "", err 241 | } 242 | 243 | return result.Hash().String(), nil 244 | } 245 | 246 | func (eth *Eth) GetPackets(height uint64, destChainType string) (*repotypes.Packets, error) { 247 | 248 | bizPackets, err := eth.getPackets(height) 249 | if err != nil { 250 | return nil, err 251 | } 252 | ackPackets, err := eth.getAckPackets(height) 253 | if err != nil { 254 | return nil, err 255 | } 256 | cleanPackets, err := eth.getCleanPacket(height) 257 | if err != nil { 258 | return nil, err 259 | } 260 | 261 | packets := &repotypes.Packets{ 262 | BizPackets: bizPackets, 263 | AckPackets: ackPackets, 264 | CleanPackets: cleanPackets, 265 | } 266 | 267 | return packets, nil 268 | } 269 | 270 | func (eth *Eth) GetProof(sourChainName, destChainName string, sequence uint64, height uint64, typ string) ([]byte, error) { 271 | pkConstr := tools.NewProofKeyConstructor(sourChainName, destChainName, sequence) 272 | var key []byte 273 | switch typ { 274 | case repotypes.CommitmentPoof: 275 | key = pkConstr.GetPacketCommitmentProofKey(eth.slot) 276 | case repotypes.AckProof: 277 | key = pkConstr.GetAckProofKey(eth.slot) 278 | case repotypes.CleanProof: 279 | key = pkConstr.GetCleanPacketCommitmentProofKey(eth.slot) 280 | default: 281 | return nil, errors.ErrGetProof 282 | } 283 | ctx, cancel := context.WithTimeout(context.Background(), CtxTimeout) 284 | defer cancel() 285 | address := gethcmn.HexToAddress(eth.contractCfgGroup.Packet.Addr) 286 | result, err := eth.getProof(ctx, address, []string{hexutil.Encode(key)}, new(big.Int).SetUint64(height)) 287 | if err != nil { 288 | return nil, err 289 | } 290 | 291 | var storageProof []*tibceth.StorageResult 292 | for _, sp := range result.StorageProof { 293 | 294 | tmpStorageProof := &tibceth.StorageResult{ 295 | Key: sp.Key, 296 | Value: hexutil.EncodeBig(sp.Value), 297 | Proof: sp.Proof, 298 | } 299 | 300 | storageProof = append(storageProof, tmpStorageProof) 301 | } 302 | nonce := hexutil.EncodeUint64(result.Nonce) 303 | balance := hexutil.EncodeBig(result.Balance) 304 | proof := &tibceth.Proof{ 305 | Address: result.Address.String(), 306 | Balance: balance, 307 | CodeHash: result.CodeHash.String(), 308 | Nonce: nonce, 309 | StorageHash: result.StorageHash.String(), 310 | AccountProof: result.AccountProof, 311 | StorageProof: storageProof, 312 | } 313 | proofBz, err := json.Marshal(proof) 314 | if err != nil { 315 | return nil, err 316 | } 317 | return proofBz, nil 318 | } 319 | 320 | func (eth *Eth) GetCommitmentsPacket(sourChainName, destChainName string, sequence uint64) error { 321 | 322 | hashBytes, err := eth.contracts.Packet.Commitments(nil, 323 | packet.PacketCommitmentKey(sourChainName, destChainName, sequence)) 324 | if err != nil { 325 | return err 326 | } 327 | expectByte := make([]byte, 32) 328 | if bytes.Equal(expectByte, hashBytes[:]) { 329 | return fmt.Errorf("commitment does not exist") 330 | } 331 | return nil 332 | } 333 | 334 | func (eth *Eth) GetReceiptPacket(sourChainName, destChainName string, sequence uint64) (bool, error) { 335 | result, err := eth.contracts.Packet.Receipts(nil, 336 | packet.PacketReceiptKey(sourChainName, destChainName, sequence)) 337 | if err != nil { 338 | return result, err 339 | } 340 | return result, nil 341 | } 342 | 343 | func (eth *Eth) GetBlockTimestamp(height uint64) (uint64, error) { 344 | ctx, cancel := context.WithTimeout(context.Background(), CtxTimeout) 345 | defer cancel() 346 | blockRes, err := eth.ethClient.BlockByNumber(ctx, new(big.Int).SetUint64(height)) 347 | if err != nil { 348 | return 0, err 349 | } 350 | return blockRes.Time(), nil 351 | } 352 | 353 | func (eth *Eth) GetBlockHeader(req *repotypes.GetBlockHeaderReq) (tibctypes.Header, error) { 354 | ctx, cancel := context.WithTimeout(context.Background(), CtxTimeout) 355 | defer cancel() 356 | blockRes, err := eth.ethClient.BlockByNumber(ctx, new(big.Int).SetUint64(req.LatestHeight)) 357 | if err != nil { 358 | return nil, err 359 | } 360 | 361 | return &tibceth.Header{ 362 | ParentHash: blockRes.ParentHash().Bytes(), 363 | UncleHash: blockRes.UncleHash().Bytes(), 364 | Coinbase: blockRes.Coinbase().Bytes(), 365 | Root: blockRes.Root().Bytes(), 366 | TxHash: blockRes.TxHash().Bytes(), 367 | ReceiptHash: blockRes.ReceiptHash().Bytes(), 368 | Bloom: blockRes.Bloom().Bytes(), 369 | Difficulty: blockRes.Difficulty().String(), 370 | Height: tibcclient.Height{ 371 | RevisionNumber: req.RevisionNumber, 372 | RevisionHeight: req.LatestHeight, 373 | }, 374 | GasLimit: blockRes.GasLimit(), 375 | GasUsed: blockRes.GasUsed(), 376 | Time: blockRes.Time(), 377 | Extra: blockRes.Extra(), 378 | MixDigest: blockRes.MixDigest().Bytes(), 379 | Nonce: blockRes.Nonce(), 380 | BaseFee: blockRes.BaseFee().String(), 381 | }, nil 382 | 383 | } 384 | 385 | func (eth *Eth) GetLightClientState(chainName string) (tibctypes.ClientState, error) { 386 | latestHeight, err := eth.contracts.Client.GetLatestHeight(nil, chainName) 387 | if err != nil { 388 | return nil, err 389 | } 390 | return &tibctendermint.ClientState{ 391 | LatestHeight: tibcclient.Height{ 392 | RevisionHeight: latestHeight.RevisionHeight, 393 | RevisionNumber: latestHeight.RevisionNumber, 394 | }, 395 | }, nil 396 | } 397 | 398 | func (eth *Eth) GetLightClientConsensusState(string, uint64) (tibctypes.ConsensusState, error) { 399 | return nil, nil 400 | } 401 | 402 | func (eth *Eth) GetLatestHeight() (uint64, error) { 403 | ctx, cancel := context.WithTimeout(context.Background(), CtxTimeout) 404 | defer cancel() 405 | return eth.ethClient.BlockNumber(ctx) 406 | } 407 | 408 | func (eth *Eth) GetLightClientDelayHeight(chainName string) (uint64, error) { 409 | return 0, nil 410 | } 411 | 412 | func (eth *Eth) GetLightClientDelayTime(chainName string) (uint64, error) { 413 | return 0, nil 414 | } 415 | 416 | func (eth *Eth) GetResult(hash string) (uint64, error) { 417 | ctx, cancel := context.WithTimeout(context.Background(), CtxTimeout) 418 | defer cancel() 419 | 420 | cmnHash := gethcmn.HexToHash(hash) 421 | result, err := eth.ethClient.TransactionReceipt(ctx, cmnHash) 422 | if err != nil { 423 | return 0, err 424 | } 425 | return result.Status, nil 426 | } 427 | 428 | func (eth *Eth) ChainName() string { 429 | return eth.chainName 430 | } 431 | func (eth *Eth) UpdateClientFrequency() uint64 { 432 | return eth.updateClientFrequency 433 | } 434 | 435 | func (eth *Eth) ChainType() string { 436 | return eth.chainType 437 | } 438 | 439 | func (eth *Eth) getProof(ctx context.Context, account gethcmn.Address, keys []string, blockNumber *big.Int) (*gethclient.AccountResult, error) { 440 | type storageResult struct { 441 | Key string `json:"key"` 442 | Value *hexutil.Big `json:"value"` 443 | Proof []string `json:"proof"` 444 | } 445 | 446 | type accountResult struct { 447 | Address gethcmn.Address `json:"address"` 448 | AccountProof []string `json:"accountProof"` 449 | Balance *hexutil.Big `json:"balance"` 450 | CodeHash gethcmn.Hash `json:"codeHash"` 451 | Nonce hexutil.Uint64 `json:"nonce"` 452 | StorageHash gethcmn.Hash `json:"storageHash"` 453 | StorageProof []storageResult `json:"storageProof"` 454 | } 455 | 456 | var res accountResult 457 | err := eth.gethRpcCli.CallContext(ctx, &res, "eth_getProof", account, keys, toBlockNumArg(blockNumber)) 458 | 459 | // Turn hexutils back to normal datatypes 460 | storageResults := make([]gethclient.StorageResult, 0, len(res.StorageProof)) 461 | for _, st := range res.StorageProof { 462 | storageResults = append(storageResults, gethclient.StorageResult{ 463 | Key: st.Key, 464 | Value: st.Value.ToInt(), 465 | Proof: st.Proof, 466 | }) 467 | } 468 | result := &gethclient.AccountResult{ 469 | Address: res.Address, 470 | AccountProof: res.AccountProof, 471 | Balance: res.Balance.ToInt(), 472 | Nonce: uint64(res.Nonce), 473 | CodeHash: res.CodeHash, 474 | StorageHash: res.StorageHash, 475 | StorageProof: storageResults, 476 | } 477 | return result, err 478 | } 479 | 480 | func toBlockNumArg(number *big.Int) string { 481 | if number == nil { 482 | return "latest" 483 | } 484 | pending := big.NewInt(-1) 485 | if number.Cmp(pending) == 0 { 486 | return "pending" 487 | } 488 | return hexutil.EncodeBig(number) 489 | } 490 | 491 | // get packets from block 492 | func (eth *Eth) getPackets(height uint64) ([]packet.Packet, error) { 493 | address := gethcmn.HexToAddress(eth.contractCfgGroup.Packet.Addr) 494 | topic := eth.contractCfgGroup.Packet.Topic 495 | logs, err := eth.getLogs(address, topic, height, height) 496 | if err != nil { 497 | return nil, err 498 | } 499 | 500 | var bizPackets []packet.Packet 501 | for _, log := range logs { 502 | 503 | packSent, err := eth.contracts.Packet.ParsePacketSent(log) 504 | if err != nil { 505 | return nil, err 506 | } 507 | tmpPack := packet.Packet{ 508 | Sequence: packSent.Packet.Sequence, 509 | Data: packSent.Packet.Data, 510 | SourceChain: packSent.Packet.SourceChain, 511 | DestinationChain: packSent.Packet.DestChain, 512 | Port: packSent.Packet.Port, 513 | RelayChain: packSent.Packet.RelayChain, 514 | } 515 | bizPackets = append(bizPackets, tmpPack) 516 | 517 | } 518 | return bizPackets, nil 519 | } 520 | 521 | // get ack packets from block 522 | func (eth *Eth) getAckPackets(height uint64) ([]repotypes.AckPacket, error) { 523 | address := gethcmn.HexToAddress(eth.contractCfgGroup.AckPacket.Addr) 524 | topic := eth.contractCfgGroup.AckPacket.Topic 525 | logs, err := eth.getLogs(address, topic, height, height) 526 | if err != nil { 527 | return nil, err 528 | } 529 | 530 | var ackPackets []repotypes.AckPacket 531 | for _, log := range logs { 532 | ackWritten, err := eth.contracts.Packet.ParseAckWritten(log) 533 | if err != nil { 534 | return nil, err 535 | } 536 | tmpAckPack := repotypes.AckPacket{} 537 | tmpAckPack.Packet = packet.Packet{ 538 | Sequence: ackWritten.Packet.Sequence, 539 | Data: ackWritten.Packet.Data, 540 | SourceChain: ackWritten.Packet.SourceChain, 541 | DestinationChain: ackWritten.Packet.DestChain, 542 | Port: ackWritten.Packet.Port, 543 | RelayChain: ackWritten.Packet.RelayChain, 544 | } 545 | tmpAckPack.Acknowledgement = ackWritten.Ack 546 | ackPackets = append(ackPackets, tmpAckPack) 547 | } 548 | return ackPackets, nil 549 | } 550 | 551 | // get clean packets from block 552 | func (eth *Eth) getCleanPacket(height uint64) ([]packet.CleanPacket, error) { 553 | address := gethcmn.HexToAddress(eth.contractCfgGroup.AckPacket.Addr) 554 | topic := eth.contractCfgGroup.CleanPacket.Topic 555 | logs, err := eth.getLogs(address, topic, height, height) 556 | if err != nil { 557 | return nil, err 558 | } 559 | 560 | var cleanPackets []packet.CleanPacket 561 | for _, log := range logs { 562 | packSent, err := eth.contracts.Packet.ParseCleanPacketSent(log) 563 | if err != nil { 564 | return nil, err 565 | } 566 | tmpPack := packet.CleanPacket{ 567 | Sequence: packSent.Packet.Sequence, 568 | SourceChain: packSent.Packet.SourceChain, 569 | DestinationChain: packSent.Packet.DestChain, 570 | RelayChain: packSent.Packet.RelayChain, 571 | } 572 | cleanPackets = append(cleanPackets, tmpPack) 573 | } 574 | return cleanPackets, nil 575 | } 576 | 577 | func (eth *Eth) getLogs(address gethcmn.Address, topic string, fromBlock, toBlock uint64) ([]gethtypes.Log, error) { 578 | filter := geth.FilterQuery{ 579 | FromBlock: new(big.Int).SetUint64(fromBlock), 580 | ToBlock: new(big.Int).SetUint64(toBlock), 581 | Addresses: []gethcmn.Address{address}, 582 | Topics: [][]gethcmn.Hash{{gethcrypto.Keccak256Hash([]byte(topic))}}, 583 | } 584 | return eth.ethClient.FilterLogs(context.Background(), filter) 585 | } 586 | 587 | func (eth *Eth) getGasPrice() (*big.Int, error) { 588 | ctx, cancel := context.WithTimeout(context.Background(), CtxTimeout) 589 | defer cancel() 590 | return eth.ethClient.SuggestGasPrice(ctx) 591 | 592 | } 593 | 594 | func (eth *Eth) setPacketOpts() error { 595 | var curGasPrice *big.Int 596 | for { 597 | gasPrice, err := eth.getGasPrice() 598 | if err != nil { 599 | return err 600 | } 601 | cmpRes := eth.maxGasPrice.Cmp(gasPrice) 602 | if cmpRes == -1 { 603 | time.Sleep(TryGetGasPriceTimeInterval) 604 | continue 605 | } else { 606 | gasPriceUint := gasPrice.Int64() 607 | gasPriceUint += int64(float64(gasPriceUint) * eth.tipCoefficient) 608 | curGasPrice = new(big.Int).SetInt64(gasPriceUint) 609 | break 610 | } 611 | } 612 | 613 | eth.bindOpts.packetTransactOpts.GasPrice = curGasPrice 614 | return nil 615 | } 616 | 617 | func (eth *Eth) setClientOpts() error { 618 | var curGasPrice *big.Int 619 | for { 620 | gasPrice, err := eth.getGasPrice() 621 | if err != nil { 622 | return err 623 | } 624 | cmpRes := eth.maxGasPrice.Cmp(gasPrice) 625 | if cmpRes == -1 { 626 | continue 627 | } else { 628 | gasPriceUint := gasPrice.Int64() 629 | gasPriceUint += int64(float64(gasPriceUint) * eth.tipCoefficient) 630 | curGasPrice = new(big.Int).SetInt64(gasPriceUint) 631 | break 632 | } 633 | } 634 | 635 | eth.bindOpts.client.GasPrice = curGasPrice 636 | return nil 637 | } 638 | 639 | // ================================================================================================================== 640 | // contract bind opts 641 | type bindOpts struct { 642 | client *bind.TransactOpts 643 | packetTransactOpts *bind.TransactOpts 644 | } 645 | 646 | func newBindOpts(cfg *ContractBindOptsCfg) (*bindOpts, error) { 647 | 648 | cliPriv, err := gethcrypto.HexToECDSA(cfg.ClientPrivKey) 649 | if err != nil { 650 | return nil, err 651 | } 652 | clientOpts, err := bind.NewKeyedTransactorWithChainID(cliPriv, new(big.Int).SetUint64(cfg.ChainID)) 653 | if err != nil { 654 | return nil, err 655 | } 656 | clientOpts.GasLimit = cfg.GasLimit 657 | 658 | //================================================================================ 659 | // packet transfer opts 660 | packPriv, err := gethcrypto.HexToECDSA(cfg.PacketPrivKey) 661 | if err != nil { 662 | return nil, err 663 | } 664 | packOpts, err := bind.NewKeyedTransactorWithChainID(packPriv, new(big.Int).SetUint64(cfg.ChainID)) 665 | if err != nil { 666 | return nil, err 667 | } 668 | packOpts.GasLimit = cfg.GasLimit 669 | 670 | return &bindOpts{ 671 | client: clientOpts, 672 | packetTransactOpts: packOpts, 673 | }, nil 674 | } 675 | 676 | // ================================================================================================================== 677 | // contract client group 678 | type contractGroup struct { 679 | Packet *contracts.Packet 680 | Client *contracts.Client 681 | } 682 | 683 | func newContractGroup(ethClient *gethethclient.Client, cfgGroup *ContractCfgGroup) (*contractGroup, error) { 684 | packAddr := gethcmn.HexToAddress(cfgGroup.Packet.Addr) 685 | packetFilter, err := contracts.NewPacket(packAddr, ethClient) 686 | if err != nil { 687 | return nil, err 688 | } 689 | 690 | clientAddr := gethcmn.HexToAddress(cfgGroup.Client.Addr) 691 | clientFilter, err := contracts.NewClient(clientAddr, ethClient) 692 | if err != nil { 693 | return nil, err 694 | } 695 | 696 | return &contractGroup{ 697 | Packet: packetFilter, 698 | Client: clientFilter, 699 | }, nil 700 | } 701 | -------------------------------------------------------------------------------- /internal/app/relayer/repostitory/eth/eth_client_test.go: -------------------------------------------------------------------------------- 1 | package eth 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | repotypes "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/repostitory/types" 8 | 9 | gethcmn "github.com/ethereum/go-ethereum/common" 10 | 11 | "github.com/ethereum/go-ethereum/accounts/abi" 12 | 13 | "github.com/bianjieai/tibc-relayer-go/internal/pkg/types/constant" 14 | ) 15 | 16 | func TestNewEth(t *testing.T) { 17 | //ropsten := "https://rinkeby.infura.io/v3/023f2af0f670457d9c4ea9cb524f0810" 18 | ropsten := "https://ropsten.infura.io/v3/023f2af0f670457d9c4ea9cb524f0810" 19 | optPrivKey := "c59f553aa4d23dad1db5b42aa8d72ce98223e29e4e6f873d95b1ced451edad39" 20 | var chainID uint64 = 3 21 | 22 | contractCfgGroup := NewContractCfgGroup() 23 | contractCfgGroup.Packet.Addr = "0x6c2d2868487665C766740ec4cAD006110CfDCff8" 24 | contractCfgGroup.Packet.Topic = "PacketSent((uint64,string,string,string,string,bytes))" 25 | contractCfgGroup.Packet.OptPrivKey = optPrivKey 26 | 27 | contractCfgGroup.AckPacket.Addr = "0x6c2d2868487665C766740ec4cAD006110CfDCff8" 28 | contractCfgGroup.AckPacket.Topic = "AckWritten((uint64,string,string,string,string,bytes),bytes)" 29 | contractCfgGroup.AckPacket.OptPrivKey = optPrivKey 30 | 31 | contractCfgGroup.CleanPacket.Addr = "0x6c2d2868487665C766740ec4cAD006110CfDCff8" 32 | contractCfgGroup.CleanPacket.Topic = "CleanPacketSent((uint64,string,string,string))" 33 | contractCfgGroup.CleanPacket.OptPrivKey = optPrivKey 34 | 35 | contractCfgGroup.Client.Addr = "0x5845092693e6708dEDAF6489719963F76d31C51C" 36 | contractCfgGroup.Client.Topic = "" 37 | contractCfgGroup.Client.OptPrivKey = optPrivKey 38 | 39 | contractBindOptsCfg := NewContractBindOptsCfg() 40 | contractBindOptsCfg.ChainID = chainID 41 | contractBindOptsCfg.ClientPrivKey = optPrivKey 42 | contractBindOptsCfg.PacketPrivKey = optPrivKey 43 | contractBindOptsCfg.GasLimit = 2000000 44 | 45 | chainCfg := NewChainConfig() 46 | chainCfg.ContractCfgGroup = contractCfgGroup 47 | chainCfg.ContractBindOptsCfg = contractBindOptsCfg 48 | chainCfg.ChainType = constant.ETH 49 | chainCfg.ChainName = "ETH" 50 | chainCfg.ChainURI = ropsten 51 | chainCfg.ChainID = chainID 52 | chainCfg.Slot = 4 53 | chainCfg.UpdateClientFrequency = 10 54 | 55 | ethClient, err := NewEth(chainCfg) 56 | if err != nil { 57 | t.Fatal(err) 58 | } 59 | latestHeight, err := ethClient.GetLatestHeight() 60 | if err != nil { 61 | t.Fatal(err) 62 | } 63 | t.Log(latestHeight) 64 | ethClient.GetProof("eth-testnet", "irishub-testnet", 3, latestHeight, repotypes.CommitmentPoof) 65 | 66 | //packets, err := ethClient.GetPackets(11128997) 67 | ////packets, err := ethClient.GetPackets(11128966) 68 | // 69 | //if err != nil { 70 | // t.Fatal(err) 71 | //} 72 | //t.Log(packets) 73 | 74 | } 75 | 76 | func Test_Hex(t *testing.T) { 77 | 78 | str := "0000000000000000000000000000000000000000000000000000000000000003" 79 | dataBytes := gethcmn.HexToHash(str) 80 | args := abi.Arguments{ 81 | abi.Argument{Type: Uint64}, 82 | } 83 | 84 | headerBytes, err := args.Unpack(dataBytes.Bytes()) 85 | if err != nil { 86 | return 87 | } 88 | fmt.Println("headerBytes: ", headerBytes) 89 | } 90 | -------------------------------------------------------------------------------- /internal/app/relayer/repostitory/ethermint/config.go: -------------------------------------------------------------------------------- 1 | package ethermint 2 | 3 | import ( 4 | coretypes "github.com/irisnet/core-sdk-go/types" 5 | ) 6 | 7 | type Config struct { 8 | Tendermint *TendermintConfig 9 | Eth *EthChainConfig 10 | } 11 | 12 | func NewConfig() *Config { 13 | return &Config{} 14 | } 15 | 16 | ///=============== 17 | // eth config 18 | 19 | type TendermintConfig struct { 20 | Options []coretypes.Option 21 | 22 | RPCAddr string 23 | GrpcAddr string 24 | ChainID string 25 | } 26 | 27 | func NewTendermintConfig() *TendermintConfig { 28 | return &TendermintConfig{} 29 | } 30 | 31 | ///=============== 32 | // eth config 33 | 34 | func NewEthChainConfig() *EthChainConfig { 35 | return &EthChainConfig{} 36 | } 37 | 38 | type EthChainConfig struct { 39 | ChainURI string 40 | 41 | Slot int64 42 | TipCoefficient float64 43 | 44 | ContractCfgGroup *ContractCfgGroup 45 | ContractBindOptsCfg *ContractBindOptsCfg 46 | } 47 | 48 | func NewContractCfgGroup() *ContractCfgGroup { 49 | return &ContractCfgGroup{} 50 | } 51 | 52 | type ContractCfgGroup struct { 53 | Client ContractCfg 54 | Packet ContractCfg 55 | AckPacket ContractCfg 56 | CleanPacket ContractCfg 57 | } 58 | 59 | type ContractCfg struct { 60 | Addr string 61 | Topic string 62 | OptPrivKey string 63 | } 64 | 65 | func NewContractBindOptsCfg() *ContractBindOptsCfg { 66 | return &ContractBindOptsCfg{} 67 | } 68 | 69 | type ContractBindOptsCfg struct { 70 | ClientPrivKey string 71 | PacketPrivKey string 72 | GasLimit uint64 73 | MaxGasPrice uint64 74 | ChainID uint64 75 | } 76 | -------------------------------------------------------------------------------- /internal/app/relayer/repostitory/ethermint/contract.go: -------------------------------------------------------------------------------- 1 | package ethermint 2 | 3 | import ( 4 | "math/big" 5 | 6 | "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/repostitory/ethermint/contracts" 7 | "github.com/ethereum/go-ethereum/accounts/abi/bind" 8 | gethcmn "github.com/ethereum/go-ethereum/common" 9 | gethcrypto "github.com/ethereum/go-ethereum/crypto" 10 | gethethclient "github.com/ethereum/go-ethereum/ethclient" 11 | ) 12 | 13 | // ================================================================================================================== 14 | // contract bind opts 15 | type bindOpts struct { 16 | client *bind.TransactOpts 17 | packetTransactOpts *bind.TransactOpts 18 | } 19 | 20 | func newBindOpts(cfg *ContractBindOptsCfg) (*bindOpts, error) { 21 | 22 | cliPriv, err := gethcrypto.HexToECDSA(cfg.ClientPrivKey) 23 | if err != nil { 24 | return nil, err 25 | } 26 | clientOpts, err := bind.NewKeyedTransactorWithChainID(cliPriv, new(big.Int).SetUint64(cfg.ChainID)) 27 | if err != nil { 28 | return nil, err 29 | } 30 | clientOpts.GasLimit = cfg.GasLimit 31 | 32 | //================================================================================ 33 | // packet transfer opts 34 | packPriv, err := gethcrypto.HexToECDSA(cfg.PacketPrivKey) 35 | if err != nil { 36 | return nil, err 37 | } 38 | packOpts, err := bind.NewKeyedTransactorWithChainID(packPriv, new(big.Int).SetUint64(cfg.ChainID)) 39 | if err != nil { 40 | return nil, err 41 | } 42 | packOpts.GasLimit = cfg.GasLimit 43 | 44 | return &bindOpts{ 45 | client: clientOpts, 46 | packetTransactOpts: packOpts, 47 | }, nil 48 | } 49 | 50 | // ================================================================================================================== 51 | // contract client group 52 | type contractGroup struct { 53 | Packet *contracts.Packet 54 | Client *contracts.Client 55 | } 56 | 57 | func newContractGroup(ethClient *gethethclient.Client, cfgGroup *ContractCfgGroup) (*contractGroup, error) { 58 | packAddr := gethcmn.HexToAddress(cfgGroup.Packet.Addr) 59 | packetFilter, err := contracts.NewPacket(packAddr, ethClient) 60 | if err != nil { 61 | return nil, err 62 | } 63 | 64 | clientAddr := gethcmn.HexToAddress(cfgGroup.Client.Addr) 65 | clientFilter, err := contracts.NewClient(clientAddr, ethClient) 66 | if err != nil { 67 | return nil, err 68 | } 69 | 70 | return &contractGroup{ 71 | Packet: packetFilter, 72 | Client: clientFilter, 73 | }, nil 74 | } 75 | -------------------------------------------------------------------------------- /internal/app/relayer/repostitory/ethermint/eth.go: -------------------------------------------------------------------------------- 1 | package ethermint 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "fmt" 7 | "math/big" 8 | "strings" 9 | "time" 10 | 11 | "github.com/irisnet/core-sdk-go/common/codec" 12 | 13 | "github.com/bianjieai/tibc-relayer-go/internal/pkg/types/errors" 14 | "github.com/bianjieai/tibc-relayer-go/tools" 15 | 16 | tibcclient "github.com/bianjieai/tibc-sdk-go/modules/core/client" 17 | 18 | "github.com/irisnet/core-sdk-go/types" 19 | 20 | commitmenttypes "github.com/bianjieai/tibc-sdk-go/modules/core/commitment" 21 | tibctendermint "github.com/bianjieai/tibc-sdk-go/modules/light-clients/tendermint" 22 | tibctypes "github.com/bianjieai/tibc-sdk-go/modules/types" 23 | "github.com/ethereum/go-ethereum/accounts/abi" 24 | "github.com/ethereum/go-ethereum/common" 25 | 26 | "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/repostitory/ethermint/contracts" 27 | repotypes "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/repostitory/types" 28 | "github.com/bianjieai/tibc-sdk-go/modules/core/packet" 29 | geth "github.com/ethereum/go-ethereum" 30 | gethcmn "github.com/ethereum/go-ethereum/common" 31 | gethtypes "github.com/ethereum/go-ethereum/core/types" 32 | gethcrypto "github.com/ethereum/go-ethereum/crypto" 33 | ) 34 | 35 | const CtxTimeout = 10 * time.Second 36 | const TryGetGasPriceTimeInterval = 10 * time.Second 37 | 38 | const evmStoreKey = "evm" 39 | 40 | const ( 41 | prefixCode = iota + 1 42 | prefixStorage 43 | ) 44 | 45 | var ( 46 | KeyPrefixStorage = []byte{prefixStorage} 47 | ) 48 | 49 | var ( 50 | Uint64, _ = abi.NewType("uint64", "", nil) 51 | Bytes32, _ = abi.NewType("bytes32", "", nil) 52 | Bytes, _ = abi.NewType("bytes", "", nil) 53 | String, _ = abi.NewType("string", "", nil) 54 | ) 55 | 56 | func (eth *Ethermint) GetProof(sourChainName, destChainName string, sequence uint64, height uint64, typ string) ([]byte, error) { 57 | 58 | pkConstr := tools.NewProofKeyConstructor(sourChainName, destChainName, sequence) 59 | var key []byte 60 | switch typ { 61 | case repotypes.CommitmentPoof: 62 | key = pkConstr.GetPacketCommitmentProofKey(eth.slot) 63 | case repotypes.AckProof: 64 | key = pkConstr.GetAckProofKey(eth.slot) 65 | case repotypes.CleanProof: 66 | key = pkConstr.GetCleanPacketCommitmentProofKey(eth.slot) 67 | default: 68 | return nil, errors.ErrGetProof 69 | } 70 | 71 | address := gethcmn.HexToAddress(eth.contractCfgGroup.Packet.Addr) 72 | 73 | _, proofBz, _, err := eth.getProof(int64(height), evmStoreKey, eth.stateKey(address, key)) 74 | if err != nil { 75 | return nil, err 76 | } 77 | 78 | return proofBz, nil 79 | } 80 | 81 | func (eth *Ethermint) GetLightClientState(chainName string) (tibctypes.ClientState, error) { 82 | latestHeight, err := eth.contracts.Client.GetLatestHeight(nil, chainName) 83 | if err != nil { 84 | return nil, err 85 | } 86 | return &tibctendermint.ClientState{ 87 | LatestHeight: tibcclient.Height{ 88 | RevisionHeight: latestHeight.RevisionHeight, 89 | RevisionNumber: latestHeight.RevisionNumber, 90 | }, 91 | }, nil 92 | } 93 | 94 | func (eth *Ethermint) GetLightClientConsensusState(string, uint64) (tibctypes.ConsensusState, error) { 95 | return nil, nil 96 | } 97 | 98 | func (eth *Ethermint) GetCommitmentsPacket(sourChainName, destChainName string, sequence uint64) error { 99 | 100 | hashBytes, err := eth.contracts.Packet.Commitments(nil, 101 | packet.PacketCommitmentKey(sourChainName, destChainName, sequence)) 102 | if err != nil { 103 | return err 104 | } 105 | expectByte := make([]byte, 32) 106 | if bytes.Equal(expectByte, hashBytes[:]) { 107 | return fmt.Errorf("commitment does not exist") 108 | } 109 | return nil 110 | } 111 | 112 | func (eth *Ethermint) GetReceiptPacket(sourChainName, destChainName string, sequence uint64) (bool, error) { 113 | result, err := eth.contracts.Packet.Receipts(nil, 114 | packet.PacketReceiptKey(sourChainName, destChainName, sequence)) 115 | if err != nil { 116 | return result, err 117 | } 118 | return result, nil 119 | } 120 | 121 | func (eth *Ethermint) RecvPackets(msgs types.Msgs) (*repotypes.ResultTx, types.Error) { 122 | resultTx := &repotypes.ResultTx{} 123 | 124 | for _, d := range msgs { 125 | 126 | switch d.Type() { 127 | case "recv_packet": 128 | msg := d.(*packet.MsgRecvPacket) 129 | 130 | tmpPack := contracts.PacketTypesPacket{ 131 | Sequence: msg.Packet.Sequence, 132 | Port: msg.Packet.Port, 133 | DestChain: msg.Packet.DestinationChain, 134 | SourceChain: msg.Packet.SourceChain, 135 | RelayChain: msg.Packet.RelayChain, 136 | Data: msg.Packet.Data, 137 | } 138 | height := contracts.HeightData{ 139 | RevisionNumber: msg.ProofHeight.RevisionNumber, 140 | RevisionHeight: msg.ProofHeight.RevisionHeight, 141 | } 142 | 143 | err := eth.setPacketOpts() 144 | if err != nil { 145 | return nil, types.Wrap(err) 146 | } 147 | result, err := eth.contracts.Packet.RecvPacket( 148 | eth.bindOpts.packetTransactOpts, 149 | tmpPack, 150 | msg.ProofCommitment, 151 | height) 152 | if err != nil { 153 | return nil, types.Wrap(err) 154 | } 155 | resultTx.GasUsed += int64(result.Gas()) 156 | resultTx.Hash = resultTx.Hash + "," + result.Hash().String() 157 | case "acknowledge_packet": 158 | msg := d.(*packet.MsgAcknowledgement) 159 | tmpPack := contracts.PacketTypesPacket{ 160 | Sequence: msg.Packet.Sequence, 161 | Port: msg.Packet.Port, 162 | DestChain: msg.Packet.DestinationChain, 163 | SourceChain: msg.Packet.SourceChain, 164 | RelayChain: msg.Packet.RelayChain, 165 | Data: msg.Packet.Data, 166 | } 167 | height := contracts.HeightData{ 168 | RevisionNumber: msg.ProofHeight.RevisionNumber, 169 | RevisionHeight: msg.ProofHeight.RevisionHeight, 170 | } 171 | 172 | err := eth.setPacketOpts() 173 | if err != nil { 174 | return nil, types.Wrap(err) 175 | } 176 | 177 | result, err := eth.contracts.Packet.AcknowledgePacket( 178 | eth.bindOpts.packetTransactOpts, 179 | tmpPack, msg.Acknowledgement, msg.ProofAcked, 180 | height) 181 | if err != nil { 182 | return nil, types.Wrap(err) 183 | } 184 | resultTx.GasUsed += int64(result.Gas()) 185 | resultTx.Hash = resultTx.Hash + "," + result.Hash().String() 186 | case "recv_clean_packet": 187 | msg := d.(*packet.MsgRecvCleanPacket) 188 | cleanPack := contracts.PacketTypesCleanPacket{ 189 | Sequence: msg.CleanPacket.Sequence, 190 | DestChain: msg.CleanPacket.DestinationChain, 191 | SourceChain: msg.CleanPacket.SourceChain, 192 | RelayChain: msg.CleanPacket.RelayChain, 193 | } 194 | 195 | err := eth.setPacketOpts() 196 | if err != nil { 197 | return nil, types.Wrap(err) 198 | } 199 | 200 | result, err := eth.contracts.Packet.CleanPacket( 201 | eth.bindOpts.packetTransactOpts, 202 | cleanPack, 203 | ) 204 | if err != nil { 205 | return nil, types.Wrap(err) 206 | } 207 | resultTx.GasUsed += int64(result.Gas()) 208 | resultTx.Hash = resultTx.Hash + "," + result.Hash().String() 209 | } 210 | 211 | } 212 | 213 | resultTx.Hash = strings.Trim(resultTx.Hash, ",") 214 | 215 | return resultTx, nil 216 | } 217 | 218 | func (eth *Ethermint) UpdateClient(header tibctypes.Header, chainName string) (string, error) { 219 | h := header.(*tibctendermint.Header) 220 | args := abi.Arguments{ 221 | abi.Argument{Type: Uint64}, 222 | abi.Argument{Type: Uint64}, 223 | abi.Argument{Type: Uint64}, 224 | abi.Argument{Type: Bytes32}, 225 | abi.Argument{Type: Bytes32}, 226 | } 227 | timestamp := uint64(h.GetTime().Unix()) 228 | revisionNumber := h.GetHeight().GetRevisionNumber() 229 | revisionHeight := h.GetHeight().GetRevisionHeight() 230 | 231 | var appHash [32]byte 232 | copy(appHash[:], h.GetHeader().AppHash[:32]) 233 | 234 | var nextValidatorsHash [32]byte 235 | copy(nextValidatorsHash[:], h.GetHeader().NextValidatorsHash[:32]) 236 | 237 | headerBytes, err := args.Pack( 238 | &revisionNumber, 239 | &revisionHeight, 240 | ×tamp, 241 | appHash, 242 | nextValidatorsHash, 243 | ) 244 | 245 | err = eth.setClientOpts() 246 | if err != nil { 247 | return "", err 248 | } 249 | 250 | result, err := eth.contracts.Client.UpdateClient(eth.bindOpts.client, chainName, headerBytes) 251 | if err != nil { 252 | return "", err 253 | } 254 | 255 | return result.Hash().String(), nil 256 | } 257 | 258 | func (eth *Ethermint) GetPackets(height uint64, destChainType string) (*repotypes.Packets, error) { 259 | 260 | bizPackets, err := eth.getPackets(height) 261 | if err != nil { 262 | return nil, err 263 | } 264 | ackPackets, err := eth.getAckPackets(height) 265 | if err != nil { 266 | return nil, err 267 | } 268 | cleanPackets, err := eth.getCleanPacket(height) 269 | if err != nil { 270 | return nil, err 271 | } 272 | 273 | packets := &repotypes.Packets{ 274 | BizPackets: bizPackets, 275 | AckPackets: ackPackets, 276 | CleanPackets: cleanPackets, 277 | } 278 | 279 | return packets, nil 280 | } 281 | 282 | // get packets from block 283 | func (eth *Ethermint) getPackets(height uint64) ([]packet.Packet, error) { 284 | address := gethcmn.HexToAddress(eth.contractCfgGroup.Packet.Addr) 285 | topic := eth.contractCfgGroup.Packet.Topic 286 | logs, err := eth.getLogs(address, topic, height, height) 287 | if err != nil { 288 | return nil, err 289 | } 290 | 291 | var bizPackets []packet.Packet 292 | for _, log := range logs { 293 | 294 | packSent, err := eth.contracts.Packet.ParsePacketSent(log) 295 | if err != nil { 296 | return nil, err 297 | } 298 | tmpPack := packet.Packet{ 299 | Sequence: packSent.Packet.Sequence, 300 | Data: packSent.Packet.Data, 301 | SourceChain: packSent.Packet.SourceChain, 302 | DestinationChain: packSent.Packet.DestChain, 303 | Port: packSent.Packet.Port, 304 | RelayChain: packSent.Packet.RelayChain, 305 | } 306 | bizPackets = append(bizPackets, tmpPack) 307 | 308 | } 309 | return bizPackets, nil 310 | } 311 | 312 | // get ack packets from block 313 | func (eth *Ethermint) getAckPackets(height uint64) ([]repotypes.AckPacket, error) { 314 | address := gethcmn.HexToAddress(eth.contractCfgGroup.AckPacket.Addr) 315 | topic := eth.contractCfgGroup.AckPacket.Topic 316 | logs, err := eth.getLogs(address, topic, height, height) 317 | if err != nil { 318 | return nil, err 319 | } 320 | 321 | var ackPackets []repotypes.AckPacket 322 | for _, log := range logs { 323 | ackWritten, err := eth.contracts.Packet.ParseAckWritten(log) 324 | if err != nil { 325 | return nil, err 326 | } 327 | tmpAckPack := repotypes.AckPacket{} 328 | tmpAckPack.Packet = packet.Packet{ 329 | Sequence: ackWritten.Packet.Sequence, 330 | Data: ackWritten.Packet.Data, 331 | SourceChain: ackWritten.Packet.SourceChain, 332 | DestinationChain: ackWritten.Packet.DestChain, 333 | Port: ackWritten.Packet.Port, 334 | RelayChain: ackWritten.Packet.RelayChain, 335 | } 336 | tmpAckPack.Acknowledgement = ackWritten.Ack 337 | ackPackets = append(ackPackets, tmpAckPack) 338 | } 339 | return ackPackets, nil 340 | } 341 | 342 | // get clean packets from block 343 | func (eth *Ethermint) getCleanPacket(height uint64) ([]packet.CleanPacket, error) { 344 | address := gethcmn.HexToAddress(eth.contractCfgGroup.AckPacket.Addr) 345 | topic := eth.contractCfgGroup.CleanPacket.Topic 346 | logs, err := eth.getLogs(address, topic, height, height) 347 | if err != nil { 348 | return nil, err 349 | } 350 | 351 | var cleanPackets []packet.CleanPacket 352 | for _, log := range logs { 353 | packSent, err := eth.contracts.Packet.ParseCleanPacketSent(log) 354 | if err != nil { 355 | return nil, err 356 | } 357 | tmpPack := packet.CleanPacket{ 358 | Sequence: packSent.Packet.Sequence, 359 | SourceChain: packSent.Packet.SourceChain, 360 | DestinationChain: packSent.Packet.DestChain, 361 | RelayChain: packSent.Packet.RelayChain, 362 | } 363 | cleanPackets = append(cleanPackets, tmpPack) 364 | } 365 | return cleanPackets, nil 366 | } 367 | 368 | func (eth *Ethermint) getLogs(address gethcmn.Address, topic string, fromBlock, toBlock uint64) ([]gethtypes.Log, error) { 369 | filter := geth.FilterQuery{ 370 | FromBlock: new(big.Int).SetUint64(fromBlock), 371 | ToBlock: new(big.Int).SetUint64(toBlock), 372 | Addresses: []gethcmn.Address{address}, 373 | Topics: [][]gethcmn.Hash{{gethcrypto.Keccak256Hash([]byte(topic))}}, 374 | } 375 | return eth.ethClient.FilterLogs(context.Background(), filter) 376 | } 377 | 378 | func (eth *Ethermint) getGasPrice() (*big.Int, error) { 379 | ctx, cancel := context.WithTimeout(context.Background(), CtxTimeout) 380 | defer cancel() 381 | return eth.ethClient.SuggestGasPrice(ctx) 382 | 383 | } 384 | 385 | func (eth *Ethermint) setPacketOpts() error { 386 | var curGasPrice *big.Int 387 | for { 388 | gasPrice, err := eth.getGasPrice() 389 | if err != nil { 390 | return err 391 | } 392 | cmpRes := eth.maxGasPrice.Cmp(gasPrice) 393 | if cmpRes == -1 { 394 | time.Sleep(TryGetGasPriceTimeInterval) 395 | continue 396 | } else { 397 | gasPriceUint := gasPrice.Int64() 398 | gasPriceUint += int64(float64(gasPriceUint) * eth.tipCoefficient) 399 | curGasPrice = new(big.Int).SetInt64(gasPriceUint) 400 | break 401 | } 402 | } 403 | 404 | eth.bindOpts.packetTransactOpts.GasPrice = curGasPrice 405 | return nil 406 | } 407 | 408 | func (eth *Ethermint) setClientOpts() error { 409 | var curGasPrice *big.Int 410 | for { 411 | gasPrice, err := eth.getGasPrice() 412 | if err != nil { 413 | return err 414 | } 415 | cmpRes := eth.maxGasPrice.Cmp(gasPrice) 416 | if cmpRes == -1 { 417 | continue 418 | } else { 419 | gasPriceUint := gasPrice.Int64() 420 | gasPriceUint += int64(float64(gasPriceUint) * eth.tipCoefficient) 421 | curGasPrice = new(big.Int).SetInt64(gasPriceUint) 422 | break 423 | } 424 | } 425 | 426 | eth.bindOpts.client.GasPrice = curGasPrice 427 | return nil 428 | } 429 | 430 | func (eth *Ethermint) getProof(height int64, storeKey string, key []byte) ([]byte, []byte, uint64, error) { 431 | // ABCI queries at heights 1, 2 or less than or equal to 0 are not supported. 432 | // Base app does not support queries for height less than or equal to 1. 433 | // Therefore, a query at height 2 would be equivalent to a query at height 3. 434 | // A height of 0 will query with the lastest state. 435 | if height != 0 && height <= 2 { 436 | return nil, nil, 0, fmt.Errorf("proof queries at height <= 2 are not supported") 437 | } 438 | 439 | // Use the IAVL height if a valid tendermint height is passed in. 440 | // A height of 0 will query with the latest state. 441 | if height != 0 { 442 | height-- 443 | } 444 | 445 | res, err := eth.terndermintCli.QueryStore(key, storeKey, height, true) 446 | if err != nil { 447 | return nil, nil, 0, err 448 | } 449 | 450 | merkleProof, err := commitmenttypes.ConvertProofs(res.ProofOps) 451 | if err != nil { 452 | return nil, nil, 0, err 453 | } 454 | 455 | cdc := codec.NewProtoCodec(eth.terndermintCli.TIBC.InterfaceRegistry) 456 | 457 | proofBz, err := cdc.MarshalBinaryBare(&merkleProof) 458 | if err != nil { 459 | return nil, nil, 0, err 460 | } 461 | return res.Value, proofBz, uint64(res.Height) + 1, nil 462 | } 463 | 464 | // StateKey defines the full key under which an account state is stored. 465 | func (eth *Ethermint) stateKey(address common.Address, key []byte) []byte { 466 | return append(addressStoragePrefix(address), key...) 467 | } 468 | 469 | // AddressStoragePrefix returns a prefix to iterate over a given account storage. 470 | func addressStoragePrefix(address common.Address) []byte { 471 | return append(KeyPrefixStorage, address.Bytes()...) 472 | } 473 | -------------------------------------------------------------------------------- /internal/app/relayer/repostitory/ethermint/tendermint.go: -------------------------------------------------------------------------------- 1 | package ethermint 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "math/big" 7 | "math/rand" 8 | "regexp" 9 | "time" 10 | 11 | gethethclient "github.com/ethereum/go-ethereum/ethclient" 12 | "github.com/ethereum/go-ethereum/ethclient/gethclient" 13 | gethrpc "github.com/ethereum/go-ethereum/rpc" 14 | 15 | "github.com/tendermint/tendermint/light/provider" 16 | 17 | tmtypes "github.com/tendermint/tendermint/types" 18 | 19 | "github.com/irisnet/core-sdk-go/bank" 20 | "github.com/irisnet/core-sdk-go/client" 21 | "github.com/irisnet/core-sdk-go/gov" 22 | "github.com/irisnet/core-sdk-go/staking" 23 | "github.com/irisnet/irismod-sdk-go/nft" 24 | 25 | tibc "github.com/bianjieai/tibc-sdk-go" 26 | tibcmttypes "github.com/bianjieai/tibc-sdk-go/modules/apps/mt_transfer" 27 | tibcclient "github.com/bianjieai/tibc-sdk-go/modules/core/client" 28 | "github.com/bianjieai/tibc-sdk-go/modules/light-clients/tendermint" 29 | tibctypes "github.com/bianjieai/tibc-sdk-go/modules/types" 30 | "github.com/irisnet/core-sdk-go/common/codec" 31 | cdctypes "github.com/irisnet/core-sdk-go/common/codec/types" 32 | cryptocodec "github.com/irisnet/core-sdk-go/common/crypto/codec" 33 | "github.com/irisnet/core-sdk-go/types" 34 | coretypes "github.com/irisnet/core-sdk-go/types" 35 | txtypes "github.com/irisnet/core-sdk-go/types/tx" 36 | "github.com/tendermint/tendermint/libs/log" 37 | tenderminttypes "github.com/tendermint/tendermint/proto/tendermint/types" 38 | 39 | "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/repostitory" 40 | repotypes "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/repostitory/types" 41 | ) 42 | 43 | var _ repostitory.IChain = new(Ethermint) 44 | 45 | var ( 46 | maxRetryAttempts = 5 47 | regexpTooHigh = regexp.MustCompile(`height \d+ must be less than or equal to`) 48 | regexpMissingHeight = regexp.MustCompile(`height \d+ is not available`) 49 | regexpTimedOut = regexp.MustCompile(`Timeout exceeded`) 50 | ) 51 | 52 | type Ethermint struct { 53 | logger log.Logger 54 | 55 | chainName string 56 | chainType string 57 | updateClientFrequency uint64 58 | 59 | // tendermint config 60 | terndermintCli tendermintClient 61 | 62 | // eth config 63 | uri string 64 | contractCfgGroup *ContractCfgGroup 65 | contracts *contractGroup 66 | bindOpts *bindOpts 67 | 68 | slot int64 69 | maxGasPrice *big.Int 70 | tipCoefficient float64 71 | 72 | ethClient *gethethclient.Client 73 | gethCli *gethclient.Client 74 | gethRpcCli *gethrpc.Client 75 | } 76 | 77 | func NewEthermintClient( 78 | chainType string, 79 | chainName string, 80 | updateClientFrequency uint64, 81 | config *Config) (*Ethermint, error) { 82 | 83 | // init eth client 84 | ctx, cancel := context.WithTimeout(context.Background(), CtxTimeout) 85 | defer cancel() 86 | rpcClient, err := gethrpc.DialContext(ctx, config.Eth.ChainURI) 87 | if err != nil { 88 | return nil, err 89 | } 90 | 91 | ethClient := gethethclient.NewClient(rpcClient) 92 | gethCli := gethclient.New(rpcClient) 93 | 94 | contractGroup, err := newContractGroup(ethClient, config.Eth.ContractCfgGroup) 95 | if err != nil { 96 | return nil, err 97 | } 98 | 99 | tmpBindOpts, err := newBindOpts(config.Eth.ContractBindOptsCfg) 100 | 101 | if err != nil { 102 | return nil, err 103 | } 104 | 105 | // init tendermint client 106 | cfg, err := coretypes.NewClientConfig( 107 | config.Tendermint.RPCAddr, 108 | config.Tendermint.GrpcAddr, 109 | config.Tendermint.ChainID, 110 | config.Tendermint.Options...) 111 | if err != nil { 112 | return nil, err 113 | } 114 | tc := newTendermintClient(cfg, chainName) 115 | 116 | return &Ethermint{ 117 | //Common properties 118 | chainType: chainType, 119 | chainName: chainName, 120 | updateClientFrequency: updateClientFrequency, 121 | 122 | terndermintCli: tc, 123 | logger: tc.BaseClient.Logger(), 124 | 125 | // eth 126 | contractCfgGroup: config.Eth.ContractCfgGroup, 127 | ethClient: ethClient, 128 | gethCli: gethCli, 129 | gethRpcCli: rpcClient, 130 | contracts: contractGroup, 131 | bindOpts: tmpBindOpts, 132 | slot: config.Eth.Slot, 133 | tipCoefficient: config.Eth.TipCoefficient, 134 | maxGasPrice: new(big.Int).SetUint64(config.Eth.ContractBindOptsCfg.MaxGasPrice), 135 | }, err 136 | } 137 | 138 | func (c *Ethermint) GetBlockTimestamp(height uint64) (uint64, error) { 139 | block, err := c.terndermintCli.QueryBlock(int64(height)) 140 | if err != nil { 141 | return 0, err 142 | } 143 | 144 | return uint64(block.Block.Time.Unix()), nil 145 | } 146 | 147 | func (c *Ethermint) GetBlockHeader(req *repotypes.GetBlockHeaderReq) (tibctypes.Header, error) { 148 | block, err := c.terndermintCli.QueryBlock(int64(req.LatestHeight)) 149 | if err != nil { 150 | return nil, err 151 | } 152 | rescommit, err := c.terndermintCli.Commit(context.Background(), &block.BlockResult.Height) 153 | if err != nil { 154 | return nil, err 155 | } 156 | commit := rescommit.Commit 157 | signedHeader := &tenderminttypes.SignedHeader{ 158 | Header: block.Block.Header.ToProto(), 159 | Commit: commit.ToProto(), 160 | } 161 | 162 | validatorSet, err := c.getValidator(int64(req.LatestHeight)) 163 | if err != nil { 164 | return nil, err 165 | 166 | } 167 | trustedValidators, err := c.getValidator(int64(req.TrustedHeight)) 168 | if err != nil { 169 | return nil, err 170 | } 171 | // The trusted fields may be nil. They may be filled before relaying messages to a client. 172 | // The relayer is responsible for querying client and injecting appropriate trusted fields. 173 | return &tendermint.Header{ 174 | SignedHeader: signedHeader, 175 | ValidatorSet: validatorSet, 176 | TrustedHeight: tibcclient.Height{ 177 | RevisionNumber: req.RevisionNumber, 178 | RevisionHeight: req.TrustedHeight, 179 | }, 180 | TrustedValidators: trustedValidators, 181 | }, nil 182 | } 183 | 184 | func (c *Ethermint) GetLatestHeight() (uint64, error) { 185 | block, err := c.terndermintCli.Block(context.Background(), nil) 186 | if err != nil { 187 | return 0, err 188 | } 189 | var height = block.Block.Height 190 | return uint64(height), err 191 | } 192 | 193 | func (c *Ethermint) GetResult(hash string) (uint64, error) { 194 | res, err := c.terndermintCli.QueryTx(hash) 195 | if err != nil { 196 | return 0, err 197 | } 198 | code := uint64(res.Result.Code) 199 | return code, nil 200 | } 201 | 202 | func (c *Ethermint) GetLightClientDelayHeight(chainName string) (uint64, error) { 203 | res, err := c.GetLightClientState(chainName) 204 | if err != nil { 205 | return 0, err 206 | } 207 | return res.GetDelayBlock(), nil 208 | } 209 | 210 | func (c *Ethermint) GetLightClientDelayTime(chainName string) (uint64, error) { 211 | res, err := c.GetLightClientState(chainName) 212 | if err != nil { 213 | return 0, err 214 | } 215 | return res.GetDelayTime(), nil 216 | 217 | } 218 | 219 | func (c *Ethermint) ChainName() string { 220 | 221 | return c.chainName 222 | } 223 | 224 | func (c *Ethermint) ChainType() string { 225 | return c.chainType 226 | } 227 | 228 | func (c *Ethermint) UpdateClientFrequency() uint64 { 229 | return c.updateClientFrequency 230 | } 231 | 232 | func (c *Ethermint) getValidator(height int64) (*tenderminttypes.ValidatorSet, error) { 233 | const maxPages = 100 234 | 235 | var ( 236 | perPage = 100 237 | vals = []*tmtypes.Validator{} 238 | page = 1 239 | total = -1 240 | ) 241 | ctx := context.Background() 242 | 243 | OUTER_LOOP: 244 | for len(vals) != total && page <= maxPages { 245 | for attempt := 1; attempt <= maxRetryAttempts; attempt++ { 246 | res, err := c.terndermintCli.TIBC.Validators(ctx, &height, &page, &perPage) 247 | switch { 248 | case err == nil: 249 | // Validate response. 250 | if len(res.Validators) == 0 { 251 | return nil, provider.ErrBadLightBlock{ 252 | Reason: fmt.Errorf("validator set is empty (height: %d, page: %d, per_page: %d)", 253 | height, page, perPage), 254 | } 255 | } 256 | if res.Total <= 0 { 257 | return nil, provider.ErrBadLightBlock{ 258 | Reason: fmt.Errorf("total number of vals is <= 0: %d (height: %d, page: %d, per_page: %d)", 259 | res.Total, height, page, perPage), 260 | } 261 | } 262 | 263 | total = res.Total 264 | vals = append(vals, res.Validators...) 265 | page++ 266 | continue OUTER_LOOP 267 | 268 | case regexpTooHigh.MatchString(err.Error()): 269 | return nil, fmt.Errorf("height requested is too high") 270 | 271 | case regexpMissingHeight.MatchString(err.Error()): 272 | return nil, provider.ErrLightBlockNotFound 273 | 274 | // if we have exceeded retry attempts then return no response error 275 | case attempt == maxRetryAttempts: 276 | return nil, provider.ErrNoResponse 277 | 278 | case regexpTimedOut.MatchString(err.Error()): 279 | // we wait and try again with exponential backoff 280 | time.Sleep(backoffTimeout(uint16(attempt))) 281 | continue 282 | 283 | // context canceled or connection refused we return the error 284 | default: 285 | return nil, err 286 | } 287 | 288 | } 289 | } 290 | validatorSet, err := tmtypes.NewValidatorSet(vals).ToProto() 291 | if err != nil { 292 | return nil, err 293 | } 294 | 295 | return validatorSet, nil 296 | } 297 | 298 | // exponential backoff (with jitter) 299 | // 0.5s -> 2s -> 4.5s -> 8s -> 12.5 with 1s variation 300 | func backoffTimeout(attempt uint16) time.Duration { 301 | // nolint:gosec // G404: Use of weak random number generator 302 | return time.Duration(500*attempt*attempt)*time.Millisecond + time.Duration(rand.Intn(1000))*time.Millisecond 303 | } 304 | 305 | //====================================== 306 | 307 | type tendermintClient struct { 308 | encodingConfig types.EncodingConfig 309 | coretypes.BaseClient 310 | Bank bank.Client 311 | Staking staking.Client 312 | Gov gov.Client 313 | NFT nft.Client 314 | TIBC tibc.Client 315 | ChainName string 316 | } 317 | 318 | func newTendermintClient(cfg types.ClientConfig, chainName string) tendermintClient { 319 | encodingConfig := makeEncodingConfig() 320 | // create a instance of baseClient 321 | baseClient := client.NewBaseClient(cfg, encodingConfig, nil) 322 | bankClient := bank.NewClient(baseClient, encodingConfig.Marshaler) 323 | stakingClient := staking.NewClient(baseClient, encodingConfig.Marshaler) 324 | govClient := gov.NewClient(baseClient, encodingConfig.Marshaler) 325 | tibcClient := tibc.NewClient(baseClient, encodingConfig) 326 | nftClient := nft.NewClient(baseClient, encodingConfig.Marshaler) 327 | 328 | tc := &tendermintClient{ 329 | encodingConfig: encodingConfig, 330 | BaseClient: baseClient, 331 | Bank: bankClient, 332 | Staking: stakingClient, 333 | Gov: govClient, 334 | NFT: nftClient, 335 | TIBC: tibcClient, 336 | ChainName: chainName, 337 | } 338 | 339 | tc.RegisterModule( 340 | bankClient, 341 | stakingClient, 342 | govClient, 343 | ) 344 | return *tc 345 | } 346 | 347 | func (tc tendermintClient) Manager() types.BaseClient { 348 | return tc.BaseClient 349 | } 350 | 351 | func (tc tendermintClient) RegisterModule(ms ...types.Module) { 352 | for _, m := range ms { 353 | m.RegisterInterfaceTypes(tc.encodingConfig.InterfaceRegistry) 354 | } 355 | } 356 | 357 | //client init 358 | func makeEncodingConfig() types.EncodingConfig { 359 | amino := codec.NewLegacyAmino() 360 | interfaceRegistry := cdctypes.NewInterfaceRegistry() 361 | marshaler := codec.NewProtoCodec(interfaceRegistry) 362 | txCfg := txtypes.NewTxConfig(marshaler, txtypes.DefaultSignModes) 363 | 364 | encodingConfig := types.EncodingConfig{ 365 | InterfaceRegistry: interfaceRegistry, 366 | Marshaler: marshaler, 367 | TxConfig: txCfg, 368 | Amino: amino, 369 | } 370 | registerLegacyAminoCodec(encodingConfig.Amino) 371 | registerInterfaces(encodingConfig.InterfaceRegistry) 372 | tibcmttypes.RegisterInterfaces(encodingConfig.InterfaceRegistry) 373 | return encodingConfig 374 | } 375 | 376 | // RegisterLegacyAminoCodec registers the sdk message type. 377 | func registerLegacyAminoCodec(cdc *codec.LegacyAmino) { 378 | cdc.RegisterInterface((*types.Msg)(nil), nil) 379 | cdc.RegisterInterface((*types.Tx)(nil), nil) 380 | cryptocodec.RegisterCrypto(cdc) 381 | } 382 | 383 | // RegisterInterfaces registers the sdk message type. 384 | func registerInterfaces(registry cdctypes.InterfaceRegistry) { 385 | registry.RegisterInterface("cosmos.v1beta1.Msg", (*types.Msg)(nil)) 386 | txtypes.RegisterInterfaces(registry) 387 | cryptocodec.RegisterInterfaces(registry) 388 | } 389 | -------------------------------------------------------------------------------- /internal/app/relayer/repostitory/exported.go: -------------------------------------------------------------------------------- 1 | package repostitory 2 | 3 | import ( 4 | tibctypes "github.com/bianjieai/tibc-sdk-go/modules/types" 5 | "github.com/irisnet/core-sdk-go/types" 6 | 7 | repotypes "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/repostitory/types" 8 | ) 9 | 10 | type IChain interface { 11 | GetPackets(height uint64, destChainType string) (*repotypes.Packets, error) 12 | GetProof(sourChainName, destChainName string, sequence uint64, height uint64, typ string) ([]byte, error) 13 | RecvPackets(msgs types.Msgs) (*repotypes.ResultTx, types.Error) 14 | GetCommitmentsPacket(sourChainName, destChainName string, sequence uint64) error 15 | GetReceiptPacket(sourChainName, destChianName string, sequence uint64) (bool, error) 16 | GetBlockHeader(*repotypes.GetBlockHeaderReq) (tibctypes.Header, error) 17 | GetBlockTimestamp(height uint64) (uint64, error) 18 | GetLightClientState(string) (tibctypes.ClientState, error) 19 | GetLightClientConsensusState(string, uint64) (tibctypes.ConsensusState, error) 20 | GetLatestHeight() (uint64, error) 21 | GetLightClientDelayHeight(string) (uint64, error) 22 | GetLightClientDelayTime(string) (uint64, error) 23 | UpdateClient(header tibctypes.Header, chainName string) (string, error) 24 | 25 | GetResult(hash string) (uint64, error) 26 | 27 | ChainName() string 28 | UpdateClientFrequency() uint64 29 | ChainType() string 30 | } 31 | -------------------------------------------------------------------------------- /internal/app/relayer/repostitory/tendermint_client.go: -------------------------------------------------------------------------------- 1 | package repostitory 2 | 3 | import ( 4 | "context" 5 | "encoding/hex" 6 | "fmt" 7 | "math/rand" 8 | "regexp" 9 | "strconv" 10 | "time" 11 | 12 | "github.com/bianjieai/tibc-relayer-go/internal/pkg/types/errors" 13 | 14 | "github.com/tendermint/tendermint/light/provider" 15 | 16 | tmtypes "github.com/tendermint/tendermint/types" 17 | 18 | "github.com/irisnet/core-sdk-go/bank" 19 | "github.com/irisnet/core-sdk-go/client" 20 | "github.com/irisnet/core-sdk-go/gov" 21 | "github.com/irisnet/core-sdk-go/staking" 22 | "github.com/irisnet/irismod-sdk-go/nft" 23 | 24 | tibc "github.com/bianjieai/tibc-sdk-go" 25 | tibcmttypes "github.com/bianjieai/tibc-sdk-go/modules/apps/mt_transfer" 26 | tibcnfttypes "github.com/bianjieai/tibc-sdk-go/modules/apps/nft_transfer" 27 | tibcclient "github.com/bianjieai/tibc-sdk-go/modules/core/client" 28 | "github.com/bianjieai/tibc-sdk-go/modules/core/packet" 29 | "github.com/bianjieai/tibc-sdk-go/modules/light-clients/tendermint" 30 | tibctypes "github.com/bianjieai/tibc-sdk-go/modules/types" 31 | "github.com/irisnet/core-sdk-go/common/codec" 32 | cdctypes "github.com/irisnet/core-sdk-go/common/codec/types" 33 | cryptocodec "github.com/irisnet/core-sdk-go/common/crypto/codec" 34 | "github.com/irisnet/core-sdk-go/types" 35 | coretypes "github.com/irisnet/core-sdk-go/types" 36 | txtypes "github.com/irisnet/core-sdk-go/types/tx" 37 | "github.com/tendermint/tendermint/libs/log" 38 | tenderminttypes "github.com/tendermint/tendermint/proto/tendermint/types" 39 | 40 | repotypes "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/repostitory/types" 41 | "github.com/bianjieai/tibc-relayer-go/internal/pkg/types/constant" 42 | ) 43 | 44 | var _ IChain = new(Tendermint) 45 | 46 | var ( 47 | maxRetryAttempts = 5 48 | regexpTooHigh = regexp.MustCompile(`height \d+ must be less than or equal to`) 49 | regexpMissingHeight = regexp.MustCompile(`height \d+ is not available`) 50 | regexpTimedOut = regexp.MustCompile(`Timeout exceeded`) 51 | ) 52 | 53 | type Tendermint struct { 54 | logger log.Logger 55 | 56 | terndermintCli tendermintClient 57 | baseTx types.BaseTx 58 | address string 59 | 60 | chainName string 61 | chainType string 62 | revisionNumber uint64 63 | updateClientFrequency uint64 64 | 65 | allowMapSender map[string][]string 66 | cleanPacketEnabled bool 67 | } 68 | 69 | func NewTendermintClient( 70 | chainType string, 71 | chainName string, 72 | updateClientFrequency uint64, 73 | allowMapSender map[string][]string, 74 | cleanPacketEnabled bool, 75 | config *TerndermintConfig) (*Tendermint, error) { 76 | cfg, err := coretypes.NewClientConfig(config.RPCAddr, config.GrpcAddr, config.ChainID, 77 | config.Options...) 78 | if err != nil { 79 | return nil, err 80 | } 81 | tc := newTendermintClient(cfg, chainName) 82 | 83 | // import key to core-sdk 84 | address, err := tc.BaseClient.Import(config.Name, config.Password, config.PrivKeyArmor) 85 | if err != nil { 86 | return nil, err 87 | } 88 | fmt.Println(address) 89 | 90 | return &Tendermint{ 91 | chainType: chainType, 92 | chainName: chainName, 93 | terndermintCli: tc, 94 | updateClientFrequency: updateClientFrequency, 95 | logger: tc.BaseClient.Logger(), 96 | baseTx: config.BaseTx, 97 | address: address, 98 | allowMapSender: allowMapSender, 99 | cleanPacketEnabled: cleanPacketEnabled, 100 | }, err 101 | } 102 | 103 | func (c *Tendermint) GetPackets(height uint64, destChainType string) (*repotypes.Packets, error) { 104 | var bizPackets []packet.Packet 105 | var ackPackets []repotypes.AckPacket 106 | var cleanPackets []packet.CleanPacket 107 | 108 | curHeight := int64(height) 109 | block, err := c.terndermintCli.Block(context.Background(), &curHeight) 110 | if err != nil { 111 | return nil, err 112 | } 113 | 114 | packets := repotypes.NewPackets() 115 | 116 | for _, tx := range block.Block.Txs { 117 | hash := hex.EncodeToString(tx.Hash()) 118 | resultTx, err := c.terndermintCli.BaseClient.QueryTx(hash) 119 | if err != nil { 120 | //todo 121 | // 需要修改sdk 122 | continue 123 | } 124 | if c.isExistPacket(repotypes.EventTypeSendPacket, resultTx) { 125 | tmpPacket, err := c.getPacket(resultTx, destChainType) 126 | if err != nil { 127 | return nil, err 128 | } 129 | bizPackets = append(bizPackets, tmpPacket...) 130 | } 131 | 132 | if c.isExistPacket(repotypes.EventTypeWriteAck, resultTx) { 133 | // get ack packet 134 | tmpAckPacks, acks, err := c.getAckPackets(resultTx, destChainType) 135 | if err != nil { 136 | return nil, err 137 | } 138 | for i := 0; i < len(tmpAckPacks); i++ { 139 | tmpAckPacket := repotypes.AckPacket{ 140 | Packet: tmpAckPacks[i], 141 | Acknowledgement: acks[i], 142 | } 143 | ackPackets = append(ackPackets, tmpAckPacket) 144 | } 145 | 146 | } 147 | 148 | if c.cleanPacketEnabled { 149 | if c.isExistPacket(repotypes.EventTypeSendCleanPacket, resultTx) { 150 | tmpCleanPacket, err := c.getCleanPacket(resultTx, destChainType) 151 | if err != nil { 152 | return nil, err 153 | } 154 | cleanPackets = append(cleanPackets, tmpCleanPacket...) 155 | } 156 | } 157 | 158 | } 159 | 160 | packets.BizPackets = bizPackets 161 | packets.AckPackets = ackPackets 162 | packets.CleanPackets = cleanPackets 163 | return packets, nil 164 | } 165 | 166 | func (c *Tendermint) GetProof(sourChainName, destChainName string, sequence uint64, height uint64, typ string) ([]byte, error) { 167 | var key []byte 168 | switch typ { 169 | case repotypes.CommitmentPoof: 170 | key = packet.PacketCommitmentKey(sourChainName, destChainName, sequence) 171 | case repotypes.AckProof: 172 | key = packet.PacketAcknowledgementKey(sourChainName, destChainName, sequence) 173 | case repotypes.CleanProof: 174 | key = packet.CleanPacketCommitmentKey(sourChainName, destChainName) 175 | default: 176 | return nil, errors.ErrGetProof 177 | } 178 | 179 | _, proofBz, _, err := c.terndermintCli.TIBC.QueryTendermintProof(int64(height), key) 180 | if err != nil { 181 | return nil, err 182 | } 183 | return proofBz, nil 184 | } 185 | 186 | func (c *Tendermint) RecvPackets(msgs types.Msgs) (*repotypes.ResultTx, types.Error) { 187 | for _, d := range msgs { 188 | switch d.Type() { 189 | case "recv_packet": 190 | msg := d.(*packet.MsgRecvPacket) 191 | msg.Signer = c.address 192 | case "acknowledge_packet": 193 | msg := d.(*packet.MsgAcknowledgement) 194 | msg.Signer = c.address 195 | case "recv_clean_packet": 196 | msg := d.(*packet.MsgRecvCleanPacket) 197 | msg.Signer = c.address 198 | } 199 | } 200 | 201 | resultTx, err := c.terndermintCli.TIBC.RecvPackets(msgs, c.baseTx) 202 | if err != nil { 203 | return nil, err 204 | } 205 | return &repotypes.ResultTx{ 206 | GasWanted: resultTx.GasWanted, 207 | GasUsed: resultTx.GasUsed, 208 | Hash: resultTx.Hash, 209 | Height: resultTx.Height, 210 | }, nil 211 | } 212 | 213 | func (c *Tendermint) GetBlockTimestamp(height uint64) (uint64, error) { 214 | block, err := c.terndermintCli.QueryBlock(int64(height)) 215 | if err != nil { 216 | return 0, err 217 | } 218 | return uint64(block.Block.Time.Unix()), nil 219 | } 220 | 221 | func (c *Tendermint) GetBlockHeader(req *repotypes.GetBlockHeaderReq) (tibctypes.Header, error) { 222 | block, err := c.terndermintCli.QueryBlock(int64(req.LatestHeight)) 223 | if err != nil { 224 | return nil, err 225 | } 226 | rescommit, err := c.terndermintCli.Commit(context.Background(), &block.BlockResult.Height) 227 | if err != nil { 228 | return nil, err 229 | } 230 | commit := rescommit.Commit 231 | signedHeader := &tenderminttypes.SignedHeader{ 232 | Header: block.Block.Header.ToProto(), 233 | Commit: commit.ToProto(), 234 | } 235 | 236 | validatorSet, err := c.getValidator(int64(req.LatestHeight)) 237 | if err != nil { 238 | return nil, err 239 | 240 | } 241 | trustedValidators, err := c.getValidator(int64(req.TrustedHeight)) 242 | if err != nil { 243 | return nil, err 244 | } 245 | // The trusted fields may be nil. They may be filled before relaying messages to a client. 246 | // The relayer is responsible for querying client and injecting appropriate trusted fields. 247 | return &tendermint.Header{ 248 | SignedHeader: signedHeader, 249 | ValidatorSet: validatorSet, 250 | TrustedHeight: tibcclient.Height{ 251 | RevisionNumber: req.RevisionNumber, 252 | RevisionHeight: req.TrustedHeight, 253 | }, 254 | TrustedValidators: trustedValidators, 255 | }, nil 256 | } 257 | 258 | func (c *Tendermint) GetLightClientState(chainName string) (tibctypes.ClientState, error) { 259 | return c.terndermintCli.TIBC.GetClientState(chainName) 260 | 261 | } 262 | 263 | func (c *Tendermint) GetLightClientConsensusState(chainName string, height uint64) (tibctypes.ConsensusState, error) { 264 | return c.terndermintCli.TIBC.GetConsensusState(chainName, height) 265 | 266 | } 267 | 268 | func (c *Tendermint) GetLatestHeight() (uint64, error) { 269 | block, err := c.terndermintCli.Block(context.Background(), nil) 270 | if err != nil { 271 | return 0, err 272 | } 273 | var height = block.Block.Height 274 | return uint64(height), err 275 | } 276 | 277 | func (c *Tendermint) GetResult(hash string) (uint64, error) { 278 | res, err := c.terndermintCli.QueryTx(hash) 279 | if err != nil { 280 | return 0, err 281 | } 282 | code := uint64(res.Result.Code) 283 | return code, nil 284 | } 285 | 286 | func (c *Tendermint) GetLightClientDelayHeight(chainName string) (uint64, error) { 287 | res, err := c.GetLightClientState(chainName) 288 | if err != nil { 289 | return 0, err 290 | } 291 | return res.GetDelayBlock(), nil 292 | } 293 | 294 | func (c *Tendermint) GetLightClientDelayTime(chainName string) (uint64, error) { 295 | res, err := c.GetLightClientState(chainName) 296 | if err != nil { 297 | return 0, err 298 | } 299 | return res.GetDelayTime(), nil 300 | 301 | } 302 | 303 | func (c *Tendermint) UpdateClient(header tibctypes.Header, chainName string) (string, error) { 304 | request := tibctypes.UpdateClientRequest{ 305 | ChainName: chainName, 306 | Header: header, 307 | } 308 | resTx, err := c.terndermintCli.TIBC.UpdateClient(request, c.baseTx) 309 | if err != nil { 310 | return "", err 311 | } 312 | return resTx.Hash, nil 313 | } 314 | 315 | func (c *Tendermint) GetCommitmentsPacket(sourceChainName, destChainName string, sequence uint64) error { 316 | _, err := c.terndermintCli.TIBC.PacketCommitment(destChainName, sourceChainName, sequence) 317 | if err != nil { 318 | return err 319 | } 320 | return nil 321 | } 322 | 323 | func (c *Tendermint) GetReceiptPacket(sourChainName, destChianName string, sequence uint64) (bool, error) { 324 | result, err := c.terndermintCli.TIBC.PacketReceipt(destChianName, sourChainName, sequence) 325 | if err != nil { 326 | return false, err 327 | } 328 | return result.Received, nil 329 | } 330 | 331 | func (c *Tendermint) ChainName() string { 332 | 333 | return c.chainName 334 | } 335 | 336 | func (c *Tendermint) ChainType() string { 337 | return c.chainType 338 | } 339 | 340 | func (c *Tendermint) UpdateClientFrequency() uint64 { 341 | return c.updateClientFrequency 342 | } 343 | 344 | func (c *Tendermint) getValidator(height int64) (*tenderminttypes.ValidatorSet, error) { 345 | const maxPages = 100 346 | 347 | var ( 348 | perPage = 100 349 | vals = []*tmtypes.Validator{} 350 | page = 1 351 | total = -1 352 | ) 353 | ctx := context.Background() 354 | 355 | OUTER_LOOP: 356 | for len(vals) != total && page <= maxPages { 357 | for attempt := 1; attempt <= maxRetryAttempts; attempt++ { 358 | res, err := c.terndermintCli.TIBC.Validators(ctx, &height, &page, &perPage) 359 | switch { 360 | case err == nil: 361 | // Validate response. 362 | if len(res.Validators) == 0 { 363 | return nil, provider.ErrBadLightBlock{ 364 | Reason: fmt.Errorf("validator set is empty (height: %d, page: %d, per_page: %d)", 365 | height, page, perPage), 366 | } 367 | } 368 | if res.Total <= 0 { 369 | return nil, provider.ErrBadLightBlock{ 370 | Reason: fmt.Errorf("total number of vals is <= 0: %d (height: %d, page: %d, per_page: %d)", 371 | res.Total, height, page, perPage), 372 | } 373 | } 374 | 375 | total = res.Total 376 | vals = append(vals, res.Validators...) 377 | page++ 378 | continue OUTER_LOOP 379 | 380 | case regexpTooHigh.MatchString(err.Error()): 381 | return nil, fmt.Errorf("height requested is too high") 382 | 383 | case regexpMissingHeight.MatchString(err.Error()): 384 | return nil, provider.ErrLightBlockNotFound 385 | 386 | // if we have exceeded retry attempts then return no response error 387 | case attempt == maxRetryAttempts: 388 | return nil, provider.ErrNoResponse 389 | 390 | case regexpTimedOut.MatchString(err.Error()): 391 | // we wait and try again with exponential backoff 392 | time.Sleep(backoffTimeout(uint16(attempt))) 393 | continue 394 | 395 | // context canceled or connection refused we return the error 396 | default: 397 | return nil, err 398 | } 399 | 400 | } 401 | } 402 | validatorSet, err := tmtypes.NewValidatorSet(vals).ToProto() 403 | if err != nil { 404 | return nil, err 405 | } 406 | 407 | return validatorSet, nil 408 | } 409 | 410 | // exponential backoff (with jitter) 411 | // 0.5s -> 2s -> 4.5s -> 8s -> 12.5 with 1s variation 412 | func backoffTimeout(attempt uint16) time.Duration { 413 | // nolint:gosec // G404: Use of weak random number generator 414 | return time.Duration(500*attempt*attempt)*time.Millisecond + time.Duration(rand.Intn(1000))*time.Millisecond 415 | } 416 | 417 | func (c *Tendermint) getPacket(tx types.ResultQueryTx, destChainType string) ([]packet.Packet, error) { 418 | sequences := tx.Result.Events.GetValues(repotypes.EventTypeSendPacket, "packet_sequence") 419 | srcChains := tx.Result.Events.GetValues(repotypes.EventTypeSendPacket, "packet_src_chain") 420 | dstPorts := tx.Result.Events.GetValues(repotypes.EventTypeSendPacket, "packet_dst_port") 421 | ports := tx.Result.Events.GetValues(repotypes.EventTypeSendPacket, "packet_port") 422 | rlyChains := tx.Result.Events.GetValues(repotypes.EventTypeSendPacket, "packet_relay_channel") 423 | datas := tx.Result.Events.GetValues(repotypes.EventTypeSendPacket, "packet_data") 424 | 425 | var packets []packet.Packet 426 | for i := 0; i < len(sequences); i++ { 427 | sequenceStr := sequences[i] 428 | sequence, err := strconv.Atoi(sequenceStr) 429 | if err != nil { 430 | return nil, err 431 | } 432 | 433 | tmpPack := packet.Packet{ 434 | Sequence: uint64(sequence), 435 | SourceChain: srcChains[i], 436 | DestinationChain: dstPorts[i], 437 | Port: ports[i], 438 | RelayChain: rlyChains[i], 439 | Data: []byte(datas[i]), 440 | } 441 | 442 | switch destChainType { 443 | case constant.ETH, constant.BSC: 444 | if !c.isNftPacketToEVMClass(tmpPack.Data) && !c.isMtPacketToEVMClass(tmpPack.Data) { 445 | continue 446 | } 447 | } 448 | 449 | packets = append(packets, tmpPack) 450 | } 451 | 452 | return packets, nil 453 | } 454 | 455 | func (c *Tendermint) isMtPacketToEVMClass(data []byte) bool { 456 | 457 | multiTokenPacketData := &tibcmttypes.MultiTokenPacketData{} 458 | if err := multiTokenPacketData.Unmarshal(data); err != nil { 459 | return false 460 | } 461 | //msgMtTransfer.DestContract 462 | 463 | //Is destContract in the allow list 464 | senders, ok := c.allowMapSender[multiTokenPacketData.DestContract] 465 | if !ok { 466 | return false 467 | } 468 | //Is msg.sender in the allow list 469 | if ok && !c.isExitsFromStringList(senders, multiTokenPacketData.Sender) { 470 | return false 471 | } 472 | return true 473 | } 474 | 475 | func (c *Tendermint) isNftPacketToEVMClass(data []byte) bool { 476 | 477 | nonFungibleTokenPacketData := &tibcnfttypes.NonFungibleTokenPacketData{} 478 | if err := nonFungibleTokenPacketData.Unmarshal(data); err != nil { 479 | return false 480 | } 481 | //msgNftTransfer.DestContract 482 | 483 | //Is destContract in the allow list 484 | senders, ok := c.allowMapSender[nonFungibleTokenPacketData.DestContract] 485 | if !ok { 486 | return false 487 | } 488 | //Is msg.sender in the allow list 489 | if ok && !c.isExitsFromStringList(senders, nonFungibleTokenPacketData.Sender) { 490 | return false 491 | } 492 | return true 493 | } 494 | 495 | func (c *Tendermint) getAckPackets(tx types.ResultQueryTx, destChainType string) ([]packet.Packet, [][]byte, error) { 496 | 497 | sequences := tx.Result.Events.GetValues(repotypes.EventTypeWriteAck, "packet_sequence") 498 | srcChains := tx.Result.Events.GetValues(repotypes.EventTypeWriteAck, "packet_src_chain") 499 | dstPorts := tx.Result.Events.GetValues(repotypes.EventTypeWriteAck, "packet_dst_port") 500 | ports := tx.Result.Events.GetValues(repotypes.EventTypeWriteAck, "packet_port") 501 | rlyChains := tx.Result.Events.GetValues(repotypes.EventTypeWriteAck, "packet_relay_channel") 502 | datas := tx.Result.Events.GetValues(repotypes.EventTypeWriteAck, "packet_data") 503 | acks := tx.Result.Events.GetValues(repotypes.EventTypeWriteAck, "packet_ack") 504 | var ackByteList [][]byte 505 | var packets []packet.Packet 506 | for i := 0; i < len(sequences); i++ { 507 | sequenceStr := sequences[i] 508 | sequence, err := strconv.Atoi(sequenceStr) 509 | if err != nil { 510 | return nil, nil, err 511 | } 512 | tmpAckPack := packet.Packet{ 513 | Sequence: uint64(sequence), 514 | SourceChain: srcChains[i], 515 | DestinationChain: dstPorts[i], 516 | Port: ports[i], 517 | RelayChain: rlyChains[i], 518 | Data: []byte(datas[i]), 519 | } 520 | ackByteList = append(ackByteList, []byte(acks[i])) 521 | packets = append(packets, tmpAckPack) 522 | } 523 | 524 | return packets, ackByteList, nil 525 | } 526 | 527 | func (c *Tendermint) getCleanPacket(tx types.ResultQueryTx, destChainType string) ([]packet.CleanPacket, error) { 528 | sequences := tx.Result.Events.GetValues(repotypes.EventTypeSendCleanPacket, "packet_sequence") 529 | sourceChains := tx.Result.Events.GetValues(repotypes.EventTypeSendCleanPacket, "packet_src_chain") 530 | dstPorts := tx.Result.Events.GetValues(repotypes.EventTypeSendCleanPacket, "packet_dst_port") 531 | rlyChains := tx.Result.Events.GetValues(repotypes.EventTypeSendCleanPacket, "packet_relay_channel") 532 | var packets []packet.CleanPacket 533 | for i := 0; i < len(sequences); i++ { 534 | sequenceStr := sequences[i] 535 | sequence, err := strconv.Atoi(sequenceStr) 536 | if err != nil { 537 | return nil, err 538 | } 539 | tmpCleanPack := packet.CleanPacket{ 540 | Sequence: uint64(sequence), 541 | SourceChain: sourceChains[i], 542 | DestinationChain: dstPorts[i], 543 | RelayChain: rlyChains[i], 544 | } 545 | packets = append(packets, tmpCleanPack) 546 | } 547 | 548 | return packets, nil 549 | 550 | } 551 | 552 | func (c *Tendermint) isExistPacket(typ string, tx types.ResultQueryTx) bool { 553 | _, err := tx.Result.Events.GetValue(typ, "packet_sequence") 554 | if err != nil { 555 | return false 556 | } 557 | return true 558 | } 559 | 560 | func (c *Tendermint) isExitsFromStringList(sources []string, target string) bool { 561 | for _, source := range sources { 562 | if source == target { 563 | return true 564 | } 565 | } 566 | return false 567 | } 568 | 569 | //====================================== 570 | 571 | type tendermintClient struct { 572 | encodingConfig types.EncodingConfig 573 | coretypes.BaseClient 574 | Bank bank.Client 575 | Staking staking.Client 576 | Gov gov.Client 577 | NFT nft.Client 578 | TIBC tibc.Client 579 | ChainName string 580 | } 581 | 582 | func newTendermintClient(cfg types.ClientConfig, chainName string) tendermintClient { 583 | encodingConfig := makeEncodingConfig() 584 | // create a instance of baseClient 585 | baseClient := client.NewBaseClient(cfg, encodingConfig, nil) 586 | bankClient := bank.NewClient(baseClient, encodingConfig.Marshaler) 587 | stakingClient := staking.NewClient(baseClient, encodingConfig.Marshaler) 588 | govClient := gov.NewClient(baseClient, encodingConfig.Marshaler) 589 | tibcClient := tibc.NewClient(baseClient, encodingConfig) 590 | nftClient := nft.NewClient(baseClient, encodingConfig.Marshaler) 591 | 592 | tc := &tendermintClient{ 593 | encodingConfig: encodingConfig, 594 | BaseClient: baseClient, 595 | Bank: bankClient, 596 | Staking: stakingClient, 597 | Gov: govClient, 598 | NFT: nftClient, 599 | TIBC: tibcClient, 600 | ChainName: chainName, 601 | } 602 | 603 | tc.RegisterModule( 604 | bankClient, 605 | stakingClient, 606 | govClient, 607 | ) 608 | return *tc 609 | } 610 | 611 | func (tc tendermintClient) Manager() types.BaseClient { 612 | return tc.BaseClient 613 | } 614 | 615 | func (tc tendermintClient) RegisterModule(ms ...types.Module) { 616 | for _, m := range ms { 617 | m.RegisterInterfaceTypes(tc.encodingConfig.InterfaceRegistry) 618 | } 619 | } 620 | 621 | //client init 622 | func makeEncodingConfig() types.EncodingConfig { 623 | amino := codec.NewLegacyAmino() 624 | interfaceRegistry := cdctypes.NewInterfaceRegistry() 625 | marshaler := codec.NewProtoCodec(interfaceRegistry) 626 | txCfg := txtypes.NewTxConfig(marshaler, txtypes.DefaultSignModes) 627 | 628 | encodingConfig := types.EncodingConfig{ 629 | InterfaceRegistry: interfaceRegistry, 630 | Marshaler: marshaler, 631 | TxConfig: txCfg, 632 | Amino: amino, 633 | } 634 | registerLegacyAminoCodec(encodingConfig.Amino) 635 | registerInterfaces(encodingConfig.InterfaceRegistry) 636 | tibcmttypes.RegisterInterfaces(encodingConfig.InterfaceRegistry) 637 | return encodingConfig 638 | } 639 | 640 | // RegisterLegacyAminoCodec registers the sdk message type. 641 | func registerLegacyAminoCodec(cdc *codec.LegacyAmino) { 642 | cdc.RegisterInterface((*types.Msg)(nil), nil) 643 | cdc.RegisterInterface((*types.Tx)(nil), nil) 644 | cryptocodec.RegisterCrypto(cdc) 645 | } 646 | 647 | // RegisterInterfaces registers the sdk message type. 648 | func registerInterfaces(registry cdctypes.InterfaceRegistry) { 649 | registry.RegisterInterface("cosmos.v1beta1.Msg", (*types.Msg)(nil)) 650 | txtypes.RegisterInterfaces(registry) 651 | cryptocodec.RegisterInterfaces(registry) 652 | } 653 | 654 | type TerndermintConfig struct { 655 | Options []coretypes.Option 656 | BaseTx types.BaseTx 657 | PrivKeyArmor string 658 | Name string 659 | Password string 660 | 661 | RPCAddr string 662 | GrpcAddr string 663 | ChainID string 664 | } 665 | 666 | func NewTerndermintConfig() *TerndermintConfig { 667 | return &TerndermintConfig{} 668 | } 669 | -------------------------------------------------------------------------------- /internal/app/relayer/repostitory/types/keys.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | const EventTypeSendPacket = "send_packet" 4 | const EventTypeWriteAck = "write_acknowledgement" 5 | const EventTypeSendCleanPacket = "send_clean_packet" 6 | 7 | const CommitmentPoof = "commitment" 8 | const AckProof = "ack" 9 | const CleanProof = "clean" 10 | -------------------------------------------------------------------------------- /internal/app/relayer/repostitory/types/types.go: -------------------------------------------------------------------------------- 1 | package types 2 | 3 | import "github.com/bianjieai/tibc-sdk-go/modules/core/packet" 4 | 5 | type GetBlockHeaderReq struct { 6 | LatestHeight uint64 7 | TrustedHeight uint64 8 | RevisionNumber uint64 9 | } 10 | 11 | type Packets struct { 12 | BizPackets []packet.Packet 13 | AckPackets []AckPacket 14 | CleanPackets []packet.CleanPacket 15 | } 16 | 17 | type AckPacket struct { 18 | Packet packet.Packet 19 | Acknowledgement []byte 20 | } 21 | 22 | func NewPackets() *Packets { 23 | return &Packets{ 24 | BizPackets: []packet.Packet{}, 25 | AckPackets: []AckPacket{}, 26 | CleanPackets: []packet.CleanPacket{}, 27 | } 28 | } 29 | 30 | type ResultTx struct { 31 | GasWanted int64 `json:"gas_wanted"` 32 | GasUsed int64 `json:"gas_used"` 33 | Hash string `json:"hash"` 34 | Height int64 `json:"height"` 35 | } 36 | -------------------------------------------------------------------------------- /internal/app/relayer/services/README.md: -------------------------------------------------------------------------------- 1 | ## service 层 -------------------------------------------------------------------------------- /internal/app/relayer/services/channels/channel.go: -------------------------------------------------------------------------------- 1 | package channels 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | "time" 7 | 8 | "github.com/bianjieai/tibc-sdk-go/modules/core/client" 9 | "github.com/bianjieai/tibc-sdk-go/modules/core/packet" 10 | tibctypes "github.com/bianjieai/tibc-sdk-go/modules/types" 11 | "github.com/irisnet/core-sdk-go/types" 12 | log "github.com/sirupsen/logrus" 13 | 14 | "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/domain" 15 | "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/repostitory" 16 | repotypes "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/repostitory/types" 17 | "github.com/bianjieai/tibc-relayer-go/internal/pkg/types/constant" 18 | typeserr "github.com/bianjieai/tibc-relayer-go/internal/pkg/types/errors" 19 | ) 20 | 21 | var _ IChannel = new(Channel) 22 | 23 | const RetryTimeout = 30 * time.Second 24 | const RetryTimes = 20 25 | 26 | type IChannel interface { 27 | UpdateClient() error 28 | Relay() error 29 | IsNotRelay() bool 30 | Context() *domain.Context 31 | UpdateClientFrequency() uint64 32 | } 33 | 34 | type Channel struct { 35 | source repostitory.IChain 36 | dest repostitory.IChain 37 | 38 | context *domain.Context 39 | 40 | logger *log.Logger 41 | } 42 | 43 | func NewChannel( 44 | source repostitory.IChain, 45 | dest repostitory.IChain, height uint64, logger *log.Logger) (IChannel, error) { 46 | var startHeight uint64 = 0 47 | if source.ChainType() == constant.Tendermint || source.ChainType() == constant.Ethermint { 48 | startHeight = height 49 | } else { 50 | clientStatus, err := dest.GetLightClientState(source.ChainName()) 51 | if err != nil { 52 | return nil, err 53 | } 54 | 55 | startHeight = clientStatus.GetLatestHeight().GetRevisionHeight() + 1 56 | } 57 | 58 | return &Channel{ 59 | logger: logger, 60 | source: source, 61 | dest: dest, 62 | context: domain.NewContext(startHeight, source.ChainName()), 63 | }, nil 64 | } 65 | 66 | func (channel *Channel) UpdateClientFrequency() uint64 { 67 | return channel.source.UpdateClientFrequency() 68 | } 69 | 70 | func (channel *Channel) UpdateClient() error { 71 | // 1. get light client state from dest chain 72 | logger := channel.logger.WithFields(log.Fields{ 73 | "source_chain": channel.source.ChainName(), 74 | "dest_chain": channel.dest.ChainName(), 75 | "option": "cron_update_client", 76 | "source_chain_type": channel.source.ChainType(), 77 | }) 78 | logger.Info("cron update client start ") 79 | if channel.source.ChainType() != constant.Tendermint { 80 | logger.Info("no need to update") 81 | return nil 82 | } 83 | clientState, err := channel.dest.GetLightClientState(channel.source.ChainName()) 84 | if err != nil { 85 | logger.WithField("err_msg", err).Error("failed to get light client state") 86 | return typeserr.ErrGetLightClientState 87 | } 88 | // 2. get source chain updated latest height from dest chain 89 | heightObj := clientState.GetLatestHeight() 90 | height := heightObj.GetRevisionHeight() 91 | 92 | // 3. Get the latest block currently scanned, and then update 93 | curHeight := channel.Context().Height() 94 | 95 | if curHeight <= height { 96 | logger.Info("curHeight <= clientStatus.height, no need to update") 97 | return nil 98 | } 99 | lastHeight, err := channel.dest.GetLatestHeight() 100 | if err != nil { 101 | logger.WithField("err_msg", err).Error("failed to get lastHeight") 102 | return typeserr.ErrGetLightClientState 103 | } 104 | // 4. if curHeight > lastHeight 105 | if curHeight > lastHeight { 106 | if err := channel.updateClient(height, lastHeight); err != nil { 107 | return typeserr.ErrUpdateClient 108 | } 109 | } else { 110 | if err := channel.updateClient(height, curHeight); err != nil { 111 | return typeserr.ErrUpdateClient 112 | } 113 | } 114 | 115 | return nil 116 | } 117 | 118 | func (channel *Channel) updateClient(trustedHeight, latestHeight uint64) error { 119 | // 3. get nextHeight block header from source chain 120 | logger := channel.logger.WithFields(log.Fields{ 121 | "trusted_height": trustedHeight, 122 | "latest_height": latestHeight, 123 | "source_chain": channel.source.ChainName(), 124 | "dest_chain": channel.dest.ChainName(), 125 | "option": "update_client", 126 | }) 127 | clientState, err1 := channel.dest.GetLightClientState(channel.source.ChainName()) 128 | if err1 != nil { 129 | logger.WithField("err_msg", err1).Error("failed to get light client state") 130 | return typeserr.ErrGetLightClientState 131 | } 132 | 133 | switch channel.source.ChainType() { 134 | case constant.Tendermint: 135 | case constant.Ethermint: 136 | if clientState.GetLatestHeight().GetRevisionHeight() >= latestHeight { 137 | return nil 138 | } 139 | 140 | } 141 | 142 | var header tibctypes.Header 143 | var err error 144 | switch channel.source.ChainType() { 145 | case constant.Tendermint, constant.Ethermint: 146 | req := &repotypes.GetBlockHeaderReq{ 147 | LatestHeight: latestHeight, 148 | TrustedHeight: clientState.GetLatestHeight().GetRevisionHeight(), 149 | RevisionNumber: clientState.GetLatestHeight().GetRevisionNumber(), 150 | } 151 | header, err = channel.source.GetBlockHeader(req) 152 | if err != nil { 153 | logger.WithField("err_msg", err).Error("failed to get block header") 154 | return typeserr.ErrGetBlockHeader 155 | } 156 | case constant.ETH: 157 | req := &repotypes.GetBlockHeaderReq{ 158 | LatestHeight: latestHeight, 159 | TrustedHeight: clientState.GetLatestHeight().GetRevisionHeight(), 160 | RevisionNumber: clientState.GetLatestHeight().GetRevisionNumber(), 161 | } 162 | header, err = channel.source.GetBlockHeader(req) 163 | if err != nil { 164 | logger.WithField("err_msg", err).Error("failed to get block header") 165 | return typeserr.ErrGetBlockHeader 166 | } 167 | case constant.BSC: 168 | req := &repotypes.GetBlockHeaderReq{ 169 | LatestHeight: latestHeight, 170 | TrustedHeight: clientState.GetLatestHeight().GetRevisionHeight(), 171 | RevisionNumber: clientState.GetLatestHeight().GetRevisionNumber(), 172 | } 173 | header, err = channel.source.GetBlockHeader(req) 174 | if err != nil { 175 | logger.WithField("err_msg", err).Error("failed to get block header") 176 | return typeserr.ErrGetBlockHeader 177 | } 178 | 179 | } 180 | 181 | // 4. update client to dest chain 182 | hash, err := channel.dest.UpdateClient(header, channel.source.ChainName()) 183 | if err != nil { 184 | logger.WithField("err_msg", err).Error("failed to update client") 185 | return err 186 | } 187 | logger.WithFields(log.Fields{"dest_hash": hash}).Info() 188 | if channel.dest.ChainType() == constant.ETH { 189 | if err := channel.reTryEthResult(hash, 0); err != nil { 190 | logger.WithField("err_msg", err).Error("failed to update client: retry: ", err) 191 | return err 192 | } 193 | } 194 | 195 | return nil 196 | } 197 | 198 | func (channel *Channel) Relay() error { 199 | return channel.relay() 200 | } 201 | 202 | func (channel *Channel) IsNotRelay() bool { 203 | curHeight := channel.Context().Height() 204 | latestHeight, err := channel.source.GetLatestHeight() 205 | if err != nil { 206 | return false 207 | } 208 | 209 | if curHeight < latestHeight { 210 | return true 211 | } 212 | 213 | return false 214 | } 215 | 216 | func (channel *Channel) Context() *domain.Context { 217 | return channel.context 218 | } 219 | 220 | func (channel *Channel) relay() error { 221 | 222 | logger := channel.logger.WithFields(log.Fields{ 223 | "source_height": channel.Context().Height(), 224 | "source_chain": channel.source.ChainName(), 225 | "dest_chain": channel.dest.ChainName(), 226 | "option": "relay", 227 | }) 228 | 229 | latestHeight, err := channel.source.GetLatestHeight() 230 | if err != nil { 231 | logger.Error("failed to get latest height") 232 | return typeserr.ErrGetLatestHeight 233 | } 234 | 235 | if latestHeight <= channel.Context().Height() { 236 | logger.Info("the current height cannot be relayed yet") 237 | return typeserr.ErrNotProduced 238 | } 239 | 240 | // 1. update client 241 | // 1.1 get eth clientState from dest 242 | clientState, err := channel.dest.GetLightClientState(channel.source.ChainName()) 243 | if err != nil { 244 | logger.WithField("err_msg", err).Error("failed to get light client state") 245 | return typeserr.ErrGetLightClientState 246 | } 247 | 248 | // 249 | 250 | delayHeight, err := channel.dest.GetLightClientDelayHeight(channel.source.ChainName()) 251 | if err != nil { 252 | logger.WithField("err_msg", err).Error("failed to get delay height") 253 | return typeserr.ErrDelayHeight 254 | } 255 | 256 | delayTime, err := channel.dest.GetLightClientDelayTime(channel.source.ChainName()) 257 | if err != nil { 258 | logger.WithField("err_msg", err).Error("failed to get delay time") 259 | return typeserr.ErrDelayTime 260 | } 261 | 262 | curBlockTimestamp, err := channel.source.GetBlockTimestamp(channel.Context().Height()) 263 | if err != nil { 264 | logger.WithField("err_msg", err).Error("failed to get block time") 265 | return typeserr.ErrCurBlockTime 266 | } 267 | var boastCommitPackets types.Msgs 268 | popLength := 0 269 | recvPacketQueue := channel.Context().Queue() 270 | for _, recvPack := range recvPacketQueue { 271 | if recvPack.Height+delayHeight < channel.Context().Height() && recvPack.Timestamp+delayTime < curBlockTimestamp { 272 | popLength += 1 273 | boastCommitPackets = append(boastCommitPackets, recvPack.RecvPackets...) 274 | } 275 | } 276 | 277 | if len(boastCommitPackets) > 0 { 278 | // boastCommit tx 279 | // if it is eth, how to submit it? 280 | resultTx, err := channel.dest.RecvPackets(boastCommitPackets) 281 | if err != nil { 282 | errMsg := err.Error() 283 | if ok := strings.Contains(errMsg, "already has been received"); ok { 284 | logger.Warning("sequence error") 285 | } else if ok := strings.Contains(errMsg, 286 | "acknowledge packet verification failed: commitment bytes are not equal:"); ok { 287 | logger.Warning("commitment error") 288 | } else { 289 | 290 | logger.WithFields(log.Fields{ 291 | "err_msg": err, 292 | "final_height": channel.Context().Height(), 293 | }).Error("recv packets ") 294 | return typeserr.ErrRecvPacket 295 | } 296 | 297 | } else { 298 | logger.WithFields(log.Fields{ 299 | "tx_height": resultTx.Height, 300 | "tx_hash": resultTx.Hash, 301 | "gas_wanted": resultTx.GasWanted, 302 | "gas_used": resultTx.GasUsed, 303 | }).Info("success") 304 | //eth block is probabilistic finality 305 | //wait result is return & result must be success 306 | if channel.dest.ChainType() == constant.ETH { 307 | if err := channel.reTryEthResult(resultTx.Hash, 0); err != nil { 308 | logger.WithField("err_msg", err).Error("failed to recv packet: retry: ", err) 309 | return typeserr.ErrRecvPacket 310 | } 311 | } 312 | } 313 | // remove the packets that have been chained 314 | channel.Context().SetQueue(recvPacketQueue[popLength:]) 315 | } 316 | /** 317 | * ======================================================== 318 | * get cur block packet 319 | * ======================================================== 320 | **/ 321 | // 2. get packets from source 322 | previousHeight := channel.Context().Height() - 1 323 | packets, err := channel.source.GetPackets(previousHeight, channel.dest.ChainType()) 324 | 325 | if err != nil { 326 | logger.WithField("err_msg", err).Error("failed to get packets") 327 | return typeserr.ErrGetPackets 328 | } 329 | 330 | //packets := &repotypes.Packets{} 331 | 332 | // 3. Process biz packets 333 | var recvPackets types.Msgs 334 | for _, pack := range packets.BizPackets { 335 | // If packet.sourceChain == channel.dest.ChainName(), 336 | // Indicates that the current packet is sent by dest. 337 | // So data packets should not be relayed back 338 | if pack.SourceChain == channel.dest.ChainName() { 339 | continue 340 | } 341 | 342 | // determine whether dest_chain or relay_chain is the target chain 343 | if pack.DestinationChain != channel.dest.ChainName() && pack.RelayChain != channel.dest.ChainName() { 344 | continue 345 | } 346 | 347 | // 3.1 get commitments packets from source chain 348 | // The source and dest in the packet must be used here 349 | // commitment path is determined 350 | err := channel.source.GetCommitmentsPacket( 351 | pack.SourceChain, pack.DestinationChain, pack.Sequence) 352 | if err != nil { 353 | if strings.Contains(err.Error(), "connection") { 354 | logger.WithFields(log.Fields{ 355 | "err_msg": err.Error(), 356 | }).Error("failed to get commitment packet") 357 | return typeserr.ErrGetCommitmentPacket 358 | } 359 | continue 360 | } 361 | 362 | // 3.2 get receipt packet from dest chain 363 | // The source and dest in the packet must be used here 364 | // commitment path is determined 365 | isNotReceipt, err := channel.dest.GetReceiptPacket(pack.SourceChain, pack.DestinationChain, pack.Sequence) 366 | if err != nil { 367 | logger.WithField("err_msg", err).Error("failed to get receipt packet") 368 | return typeserr.ErrGetReceiptPacket 369 | } 370 | // if receipt exist, skip 371 | if isNotReceipt { 372 | logger.Info("receipt exist, skip cur height ") 373 | continue 374 | } 375 | 376 | proof, err := channel.source.GetProof( 377 | pack.SourceChain, 378 | pack.DestinationChain, 379 | pack.Sequence, 380 | channel.Context().Height(), repotypes.CommitmentPoof) 381 | if err != nil { 382 | logger.WithFields(log.Fields{ 383 | "err_msg": err.Error(), 384 | "packet_type": "packet", 385 | }).Error("failed to get proof") 386 | return typeserr.ErrGetProof 387 | } 388 | //pack.SourceChain = "irishub-testnet10" 389 | recvPacket := &packet.MsgRecvPacket{ 390 | Packet: pack, 391 | ProofCommitment: proof, 392 | ProofHeight: client.Height{ 393 | RevisionNumber: clientState.GetLatestHeight().GetRevisionNumber(), 394 | RevisionHeight: channel.Context().Height(), 395 | }, 396 | } 397 | recvPackets = append(recvPackets, recvPacket) 398 | } 399 | //4. Process ack packets 400 | for _, pack := range packets.AckPackets { 401 | // If packet.DestinationChain == channel.source.ChainName(), 402 | // Indicates that the current packet is sent by dest. 403 | // So data packets should not be relayed back 404 | 405 | err := channel.dest.GetCommitmentsPacket( 406 | pack.Packet.SourceChain, pack.Packet.DestinationChain, pack.Packet.Sequence) 407 | if err != nil { 408 | if strings.Contains(err.Error(), "connection") { 409 | logger.WithFields(log.Fields{ 410 | "err_msg": err.Error(), 411 | }).Error("failed to get commitment packet") 412 | return typeserr.ErrGetCommitmentPacket 413 | } 414 | logger.Info("the current packet has been confirmed") 415 | continue 416 | } 417 | // determine whether source_chain is the target chain 418 | if pack.Packet.SourceChain != channel.dest.ChainName() && pack.Packet.RelayChain != channel.dest.ChainName() { 419 | continue 420 | } 421 | // query proof 422 | proof, err := channel.source.GetProof( 423 | pack.Packet.SourceChain, 424 | pack.Packet.DestinationChain, 425 | pack.Packet.Sequence, 426 | channel.Context().Height(), repotypes.AckProof) 427 | if err != nil { 428 | logger.WithFields(log.Fields{ 429 | "err_msg": err.Error(), 430 | "packet_type": "ack", 431 | }).Error("failed to get proof") 432 | return typeserr.ErrGetProof 433 | } 434 | //pack.Packet.SourceChain = "irishub-testnet10" 435 | recvPacket := &packet.MsgAcknowledgement{ 436 | Packet: pack.Packet, 437 | Acknowledgement: pack.Acknowledgement, 438 | ProofAcked: proof, 439 | ProofHeight: client.Height{ 440 | RevisionNumber: clientState.GetLatestHeight().GetRevisionNumber(), 441 | RevisionHeight: channel.Context().Height(), 442 | }, 443 | } 444 | recvPackets = append(recvPackets, recvPacket) 445 | } 446 | 447 | for _, pack := range packets.CleanPackets { 448 | // determine whether dest_chain or relay_chain is the target chain 449 | if pack.DestinationChain != channel.dest.ChainName() && pack.RelayChain != channel.dest.ChainName() { 450 | continue 451 | } 452 | 453 | proof, err := channel.source.GetProof( 454 | pack.SourceChain, 455 | pack.DestinationChain, 456 | pack.Sequence, 457 | channel.Context().Height(), repotypes.CleanProof) 458 | if err != nil { 459 | logger.WithField("err_msg", err).Error("failed to get proof") 460 | return typeserr.ErrGetProof 461 | } 462 | recvPacket := &packet.MsgRecvCleanPacket{ 463 | CleanPacket: pack, 464 | ProofCommitment: proof, 465 | ProofHeight: client.Height{ 466 | RevisionNumber: clientState.GetLatestHeight().GetRevisionNumber(), 467 | RevisionHeight: channel.Context().Height(), 468 | }, 469 | } 470 | recvPackets = append(recvPackets, recvPacket) 471 | } 472 | 473 | if (len(packets.CleanPackets) == 0 && len(packets.AckPackets) == 0 && len(packets.BizPackets) == 0) || len(recvPackets) == 0 { 474 | logger.Info("there are no packets to be relayed at the current altitude") 475 | // When the packet is empty, tendermint does not need to update the client 476 | switch channel.source.ChainType() { 477 | case constant.ETH, constant.BSC: 478 | //update client 479 | err = channel.updateClient( 480 | clientState.GetLatestHeight().GetRevisionHeight(), 481 | channel.Context().Height(), 482 | ) 483 | if err != nil { 484 | errMsg := err.Error() 485 | if ok := strings.Contains(errMsg, "post failed"); ok { 486 | logger.WithFields(log.Fields{ 487 | "err_msg": err, 488 | "final_height": channel.Context().Height(), 489 | }).Error("failed to network ") 490 | return typeserr.ErrUpdateClient 491 | } 492 | 493 | if ok := strings.Contains(errMsg, "Internal error: timed out"); ok { 494 | logger.WithFields(log.Fields{ 495 | "err_msg": err, 496 | "final_height": channel.Context().Height(), 497 | }).Error("failed to network ") 498 | return typeserr.ErrUpdateClient 499 | } 500 | 501 | if ok := strings.Contains(errMsg, "header already exist for hash"); ok { 502 | logger.WithFields(log.Fields{ 503 | "err_msg": err, 504 | "final_height": channel.Context().Height(), 505 | }).Warning("header already exist for hash ") 506 | 507 | channel.Context().IncrHeight() 508 | return nil 509 | } 510 | 511 | // After the update client fails, the height is reduced by 1 512 | updateHeight := channel.Context().Height() 513 | channel.Context().DecrHeight() 514 | logger.WithFields(log.Fields{ 515 | "err_msg": err, 516 | "update_height": updateHeight, 517 | "final_height": channel.Context().Height(), 518 | }).Warning("failed to update client, height = curHeight - 1 ") 519 | return typeserr.ErrUpdateClient 520 | } 521 | 522 | } 523 | } else { 524 | 525 | //Follow the client where the new proof is located 526 | err = channel.updateClient( 527 | clientState.GetLatestHeight().GetRevisionHeight(), 528 | channel.Context().Height()) 529 | if err != nil { 530 | logger.Warning("update client err: ", channel.source.ChainType()) 531 | if channel.source.ChainType() != constant.Tendermint { 532 | errMsg := err.Error() 533 | if ok := strings.Contains(errMsg, "post failed"); ok { 534 | logger.WithFields(log.Fields{ 535 | "err_msg": err, 536 | "final_height": channel.Context().Height(), 537 | }).Error("failed to network ") 538 | return typeserr.ErrUpdateClient 539 | } 540 | 541 | if ok := strings.Contains(errMsg, "Internal error: timed out"); ok { 542 | logger.WithFields(log.Fields{ 543 | "err_msg": err, 544 | "final_height": channel.Context().Height(), 545 | }).Error("failed to network ") 546 | return typeserr.ErrUpdateClient 547 | } 548 | 549 | if ok := strings.Contains(errMsg, "header already exist for hash"); ok { 550 | logger.WithFields(log.Fields{ 551 | "err_msg": err, 552 | "final_height": channel.Context().Height(), 553 | }).Warning("header already exist for hash ") 554 | 555 | channel.Context().IncrHeight() 556 | return nil 557 | } 558 | 559 | // After the update client fails, the height is reduced by 1 560 | updateHeight := channel.Context().Height() 561 | channel.Context().DecrHeight() 562 | logger.WithFields(log.Fields{ 563 | "err_msg": err, 564 | "update_height": updateHeight, 565 | "final_height": channel.Context().Height(), 566 | }).Warning("failed to update client, height = curHeight - 1 ") 567 | } else { 568 | logger.WithField("err_msg", err).Error("failed to update client") 569 | } 570 | 571 | return typeserr.ErrUpdateClient 572 | } 573 | 574 | // set data to queue 575 | queueMetaData := domain.QueueMetaData{ 576 | Height: channel.Context().Height(), 577 | Timestamp: curBlockTimestamp, 578 | RecvPackets: recvPackets, 579 | } 580 | channel.Context().PushQueue(queueMetaData) 581 | } 582 | 583 | channel.Context().IncrHeight() 584 | return nil 585 | } 586 | 587 | func (channel *Channel) reTryEthResult(hash string, n uint64) error { 588 | channel.logger.Infof("retry %d time", n) 589 | if n == RetryTimes { 590 | return fmt.Errorf("retry %d times and return error", RetryTimes) 591 | } 592 | txStatus, err := channel.dest.GetResult(hash) 593 | if err != nil { 594 | channel.logger.Info("re-request result ") 595 | time.Sleep(RetryTimeout) 596 | return channel.reTryEthResult(hash, n+1) 597 | } 598 | if txStatus == 0 { 599 | channel.logger.WithFields(log.Fields{ 600 | "hash": hash, 601 | "flag": "result_error", 602 | }).Warning("re-request result is false") 603 | return nil 604 | } 605 | return nil 606 | } 607 | -------------------------------------------------------------------------------- /internal/app/relayer/services/channels/mertic_mw.go: -------------------------------------------------------------------------------- 1 | package channels 2 | 3 | import ( 4 | "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/domain" 5 | internelerrors "github.com/bianjieai/tibc-relayer-go/internal/pkg/types/errors" 6 | merticsmodel "github.com/bianjieai/tibc-relayer-go/internal/pkg/types/mertics" 7 | ) 8 | 9 | var _ IChannel = new(Metric) 10 | 11 | type Metric struct { 12 | next IChannel 13 | 14 | metricsModel *merticsmodel.Model 15 | } 16 | 17 | func NewMetricMW(svc IChannel, metricsModel *merticsmodel.Model) IChannel { 18 | 19 | return &Metric{ 20 | next: svc, 21 | metricsModel: metricsModel, 22 | } 23 | } 24 | 25 | func (m *Metric) UpdateClientFrequency() uint64 { 26 | return m.next.UpdateClientFrequency() 27 | } 28 | 29 | func (m *Metric) UpdateClient() error { 30 | return m.next.UpdateClient() 31 | } 32 | 33 | func (m *Metric) Relay() error { 34 | err := m.next.Relay() 35 | defer func(err error) { 36 | labels := []string{"chain_name", m.Context().ChainName()} 37 | 38 | connChainLabels := []string{"chain_name", m.Context().ChainName(), "option", "connection"} 39 | getClientStatusLabels := []string{"chain_name", m.Context().ChainName(), "option", "client_get_client_status"} 40 | updateClientLabels := []string{"chain_name", m.Context().ChainName(), "option", "client_update_client_status"} 41 | recvPacketLabels := []string{"chain_name", m.Context().ChainName(), "option", "packet_recv_packet"} 42 | getPacketLabels := []string{"chain_name", m.Context().ChainName(), "option", "packet_get_packet"} 43 | getCommitmentLabels := []string{"chain_name", m.Context().ChainName(), "option", "packet_get_commitment"} 44 | getProofLabels := []string{"chain_name", m.Context().ChainName(), "option", "packet_get_proof"} 45 | getReceiptLabels := []string{"chain_name", m.Context().ChainName(), "option", "packet_get_receipt"} 46 | 47 | sysErr, ok := err.(internelerrors.IError) 48 | if !ok && sysErr != nil { 49 | m.metricsModel.Sys.With(labels...).Set(-1) 50 | return 51 | } 52 | switch sysErr { 53 | case internelerrors.ErrChainConn: 54 | m.metricsModel.Chain.With(connChainLabels...).Set(-1) 55 | case internelerrors.ErrGetLightClientState: 56 | m.metricsModel.Chain.With(getClientStatusLabels...).Set(-1) 57 | case internelerrors.ErrUpdateClient: 58 | m.metricsModel.Chain.With(updateClientLabels...).Set(-1) 59 | case internelerrors.ErrRecvPacket: 60 | m.metricsModel.Chain.With(recvPacketLabels...).Set(-1) 61 | case internelerrors.ErrGetPackets: 62 | m.metricsModel.Chain.With(getPacketLabels...).Set(-1) 63 | case internelerrors.ErrGetCommitmentPacket: 64 | m.metricsModel.Chain.With(getCommitmentLabels...).Set(-1) 65 | case internelerrors.ErrGetProof: 66 | m.metricsModel.Chain.With(getProofLabels...).Set(-1) 67 | case internelerrors.ErrGetReceiptPacket: 68 | m.metricsModel.Chain.With(getReceiptLabels...).Set(-1) 69 | 70 | default: 71 | m.metricsModel.Sys.With(labels...).Set(1) 72 | m.metricsModel.Chain.With(connChainLabels...).Set(1) 73 | m.metricsModel.Chain.With(getClientStatusLabels...).Set(1) 74 | m.metricsModel.Chain.With(updateClientLabels...).Set(1) 75 | m.metricsModel.Chain.With(recvPacketLabels...).Set(1) 76 | m.metricsModel.Chain.With(getPacketLabels...).Set(1) 77 | m.metricsModel.Chain.With(getCommitmentLabels...).Set(1) 78 | m.metricsModel.Chain.With(getProofLabels...).Set(1) 79 | m.metricsModel.Chain.With(getReceiptLabels...).Set(1) 80 | } 81 | }(err) 82 | return err 83 | } 84 | 85 | func (m *Metric) IsNotRelay() bool { 86 | return m.next.IsNotRelay() 87 | } 88 | 89 | func (m *Metric) Context() *domain.Context { 90 | return m.next.Context() 91 | } 92 | -------------------------------------------------------------------------------- /internal/app/relayer/services/channels/writer_mw.go: -------------------------------------------------------------------------------- 1 | package channels 2 | 3 | import ( 4 | log "github.com/sirupsen/logrus" 5 | 6 | "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/domain" 7 | ) 8 | 9 | var _ IChannel = new(Writer) 10 | 11 | type Writer struct { 12 | next IChannel 13 | 14 | logger *log.Entry 15 | 16 | chainName string 17 | 18 | cacheWriter *domain.CacheFileWriter 19 | } 20 | 21 | func NewWriterMW(svc IChannel, chainName string, logger *log.Logger, homeDir, dir, filename string) IChannel { 22 | 23 | entry := logger.WithFields(log.Fields{ 24 | "chain_name": chainName, 25 | }) 26 | cacheWriter := domain.NewCacheFileWriter(homeDir, dir, filename) 27 | return &Writer{ 28 | next: svc, 29 | chainName: chainName, 30 | cacheWriter: cacheWriter, 31 | logger: entry, 32 | } 33 | } 34 | 35 | func (w *Writer) UpdateClientFrequency() uint64 { 36 | return w.next.UpdateClientFrequency() 37 | } 38 | 39 | func (w *Writer) UpdateClient() error { 40 | return w.next.UpdateClient() 41 | } 42 | 43 | func (w *Writer) Relay() error { 44 | err := w.next.Relay() 45 | if err != nil { 46 | return err 47 | } 48 | w.Context().Height() 49 | ctx := w.next.Context() 50 | //if ctx.Height()%100 == 0 { 51 | // w.cacheWriter.Write(ctx.Height()) 52 | //} 53 | w.cacheWriter.Write(ctx.Height()) 54 | return nil 55 | } 56 | 57 | func (w *Writer) IsNotRelay() bool { 58 | return w.next.IsNotRelay() 59 | } 60 | 61 | func (w *Writer) Context() *domain.Context { 62 | return w.next.Context() 63 | } 64 | -------------------------------------------------------------------------------- /internal/app/relayer/services/listener.go: -------------------------------------------------------------------------------- 1 | package services 2 | 3 | import ( 4 | "context" 5 | "sync" 6 | "time" 7 | 8 | "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/services/channels" 9 | 10 | log "github.com/sirupsen/logrus" 11 | ) 12 | 13 | const DefaultTimeout = 10 14 | 15 | type IListener interface { 16 | Listen() error 17 | } 18 | 19 | type Listener struct { 20 | channelMap map[string]channels.IChannel 21 | 22 | ctxMap sync.Map 23 | logger *log.Logger 24 | } 25 | 26 | func NewListener( 27 | channelMap map[string]channels.IChannel, 28 | logger *log.Logger) IListener { 29 | listener := &Listener{ 30 | channelMap: channelMap, 31 | ctxMap: sync.Map{}, 32 | logger: logger, 33 | } 34 | return listener 35 | } 36 | 37 | func (listener *Listener) Listen() error { 38 | 39 | // 启动N个goroutine去处理 40 | for chainName := range listener.channelMap { 41 | ctx, cancel := context.WithCancel(context.Background()) 42 | listener.ctxMap.Store(chainName, cancel) 43 | go listener.start(ctx, chainName) 44 | } 45 | listener.ctxMap.Range(listener.walk) 46 | select {} 47 | } 48 | 49 | func (listener *Listener) start(ctx context.Context, chainName string) { 50 | 51 | for { 52 | select { 53 | case <-ctx.Done(): 54 | listener.logger.WithFields(log.Fields{ 55 | "chain_name": chainName, 56 | }).Info("canceled") 57 | return 58 | default: 59 | if !listener.channelMap[chainName].IsNotRelay() { 60 | time.Sleep(DefaultTimeout * time.Second) 61 | } else { 62 | err := listener.channelMap[chainName].Relay() 63 | if err != nil { 64 | time.Sleep(DefaultTimeout * time.Second) 65 | } 66 | } 67 | 68 | } 69 | } 70 | } 71 | 72 | func (listener *Listener) cancelCtx(locality string) { 73 | if value, ok := listener.ctxMap.Load(locality); ok { 74 | cancel := value.(context.CancelFunc) 75 | cancel() 76 | listener.ctxMap.Delete(locality) 77 | } 78 | } 79 | 80 | func (listener *Listener) walk(key, value interface{}) bool { 81 | listener.logger.WithFields(log.Fields{"chain": key}).Info("start") 82 | return true 83 | } 84 | -------------------------------------------------------------------------------- /internal/pkg/configs/configs.go: -------------------------------------------------------------------------------- 1 | package configs 2 | 3 | type ( 4 | Config struct { 5 | App App `mapstructure:"app"` 6 | Chain Chain `mapstructure:"chain"` 7 | } 8 | 9 | Chain struct { 10 | Source ChainCfg `mapstructure:"source"` 11 | Dest ChainCfg `mapstructure:"dest"` 12 | } 13 | 14 | ChainCfg struct { 15 | Cache Cache `mapstructure:"cache"` 16 | Tendermint Tendermint `mapstructure:"tendermint"` 17 | Eth Eth `mapstructure:"eth"` 18 | Bsc Eth `mapstructure:"bsc"` 19 | Ethermint Ethermint `mapstructure:"ethermint"` 20 | ChainType string `mapstructure:"chain_type"` 21 | Enabled bool `mapstructure:"enabled"` 22 | } 23 | 24 | Ethermint struct { 25 | // comment 26 | ChainName string `mapstructure:"chain_name"` 27 | UpdateClientFrequency uint64 `mapstructure:"update_client_frequency"` 28 | 29 | // eth 30 | URI string `mapstructure:"uri"` 31 | EthChainID uint64 `mapstructure:"eth_chain_id"` 32 | Contracts EthContracts `mapstructure:"eth_contracts"` 33 | GasLimit uint64 `mapstructure:"gas_limit"` 34 | MaxGasPrice uint64 `mapstructure:"max_gas_price"` 35 | CommentSlot int64 `mapstructure:"comment_slot"` 36 | TipCoefficient float64 `mapstructure:"tip_coefficient"` 37 | 38 | // tendermint 39 | TendermintChainID string `mapstructure:"tendermint_chain_id"` 40 | RPCAddr string `mapstructure:"rpc_addr"` 41 | GrpcAddr string `mapstructure:"grpc_addr"` 42 | Algo string `mapstructure:"algo"` 43 | Gas uint64 `mapstructure:"gas"` 44 | RequestTimeout uint `mapstructure:"request_timeout"` 45 | } 46 | 47 | // Eth config============================================================ 48 | Eth struct { 49 | URI string `mapstructure:"uri"` 50 | ChainID uint64 `mapstructure:"chain_id"` 51 | ChainName string `mapstructure:"chain_name"` 52 | Contracts EthContracts `mapstructure:"eth_contracts"` 53 | UpdateClientFrequency uint64 `mapstructure:"update_client_frequency"` 54 | GasLimit uint64 `mapstructure:"gas_limit"` 55 | MaxGasPrice uint64 `mapstructure:"max_gas_price"` 56 | CommentSlot int64 `mapstructure:"comment_slot"` 57 | TipCoefficient float64 `mapstructure:"tip_coefficient"` 58 | } 59 | 60 | EthContracts struct { 61 | Packet EthContractCfg `mapstructure:"packet"` 62 | AckPacket EthContractCfg `mapstructure:"ack_packet"` 63 | CleanPacket EthContractCfg `mapstructure:"clean_packet"` 64 | Client EthContractCfg `mapstructure:"client"` 65 | } 66 | 67 | EthContractCfg struct { 68 | Addr string `mapstructure:"addr"` 69 | Topic string `mapstructure:"topic"` 70 | OptPrivKey string `mapstructure:"opt_priv_key"` 71 | } 72 | // Tendermint ===================================================================== 73 | Tendermint struct { 74 | ChainName string `mapstructure:"chain_name"` 75 | ChainID string `mapstructure:"chain_id"` 76 | RPCAddr string `mapstructure:"rpc_addr"` 77 | GrpcAddr string `mapstructure:"grpc_addr"` 78 | Gas uint64 `mapstructure:"gas"` 79 | Key ChainKey `mapstructure:"key"` 80 | Fee Fee `mapstructure:"fee"` 81 | Algo string `mapstructure:"algo"` 82 | 83 | RequestTimeout uint `mapstructure:"request_timeout"` 84 | UpdateClientFrequency uint64 `mapstructure:"update_client_frequency"` 85 | 86 | Allows []Allow `mapstructure:"allows"` 87 | CleanPacketEnabled bool `mapstructure:"clean_packet_enabled"` 88 | } 89 | 90 | Fee struct { 91 | Denom string `mapstructure:"denom"` 92 | Amount int64 `mapstructure:"amount"` 93 | } 94 | 95 | ChainKey struct { 96 | Name string `mapstructure:"name"` 97 | Password string `mapstructure:"password"` 98 | PrivKeyArmor string `mapstructure:"priv_key_armor"` 99 | } 100 | 101 | Allow struct { 102 | ContractAddr string `mapstructure:"contract_addr"` 103 | Senders []string `mapstructure:"senders"` 104 | } 105 | 106 | // ===================================================================== 107 | 108 | App struct { 109 | MetricAddr string `mapstructure:"metric_addr"` 110 | Env string `mapstructure:"env"` 111 | LogLevel string `mapstructure:"log_level"` 112 | ChannelTypes []string `mapstructure:"channel_types"` 113 | } 114 | 115 | Cache struct { 116 | Filename string `mapstructure:"filename"` 117 | StartHeight uint64 `mapstructure:"start_height"` 118 | } 119 | ) 120 | 121 | func NewConfig() *Config { 122 | return &Config{} 123 | } 124 | -------------------------------------------------------------------------------- /internal/pkg/initialization/bsc.go: -------------------------------------------------------------------------------- 1 | package initialization 2 | 3 | import ( 4 | log "github.com/sirupsen/logrus" 5 | 6 | "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/repostitory" 7 | repobsc "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/repostitory/bsc" 8 | "github.com/bianjieai/tibc-relayer-go/internal/pkg/configs" 9 | "github.com/bianjieai/tibc-relayer-go/internal/pkg/types/constant" 10 | ) 11 | 12 | func bscChain(cfg *configs.ChainCfg, logger *log.Logger) repostitory.IChain { 13 | loggerEntry := logger.WithFields(log.Fields{ 14 | "chain_name": cfg.Bsc.ChainName, 15 | }) 16 | 17 | loggerEntry.Info(" init eth chain start") 18 | 19 | contractCfgGroup := repobsc.NewContractCfgGroup() 20 | contractCfgGroup.Packet.Addr = cfg.Bsc.Contracts.Packet.Addr 21 | contractCfgGroup.Packet.Topic = cfg.Bsc.Contracts.Packet.Topic 22 | contractCfgGroup.Packet.OptPrivKey = cfg.Bsc.Contracts.Packet.OptPrivKey 23 | 24 | contractCfgGroup.AckPacket.Addr = cfg.Bsc.Contracts.AckPacket.Addr 25 | contractCfgGroup.AckPacket.Topic = cfg.Bsc.Contracts.AckPacket.Topic 26 | contractCfgGroup.CleanPacket.Addr = cfg.Bsc.Contracts.CleanPacket.Addr 27 | contractCfgGroup.CleanPacket.Topic = cfg.Bsc.Contracts.CleanPacket.Topic 28 | 29 | contractCfgGroup.Client.Addr = cfg.Bsc.Contracts.Client.Addr 30 | contractCfgGroup.Client.Topic = cfg.Bsc.Contracts.Client.Topic 31 | contractCfgGroup.Client.OptPrivKey = cfg.Bsc.Contracts.Client.OptPrivKey 32 | 33 | contractBindOptsCfg := repobsc.NewContractBindOptsCfg() 34 | contractBindOptsCfg.ChainID = cfg.Bsc.ChainID 35 | contractBindOptsCfg.ClientPrivKey = cfg.Bsc.Contracts.Client.OptPrivKey 36 | contractBindOptsCfg.PacketPrivKey = cfg.Bsc.Contracts.Packet.OptPrivKey 37 | contractBindOptsCfg.GasLimit = cfg.Bsc.GasLimit 38 | contractBindOptsCfg.MaxGasPrice = cfg.Bsc.MaxGasPrice 39 | 40 | bscChainCfg := repobsc.NewChainConfig() 41 | bscChainCfg.ContractCfgGroup = contractCfgGroup 42 | bscChainCfg.ContractBindOptsCfg = contractBindOptsCfg 43 | 44 | bscChainCfg.ChainType = constant.BSC 45 | bscChainCfg.ChainName = cfg.Bsc.ChainName 46 | bscChainCfg.ChainID = cfg.Bsc.ChainID 47 | bscChainCfg.ChainURI = cfg.Bsc.URI 48 | bscChainCfg.Slot = cfg.Bsc.CommentSlot 49 | bscChainCfg.UpdateClientFrequency = cfg.Bsc.UpdateClientFrequency 50 | bscChainCfg.TipCoefficient = cfg.Bsc.TipCoefficient 51 | 52 | ethRepo, err := repobsc.NewBsc(bscChainCfg) 53 | if err != nil { 54 | loggerEntry.WithFields(log.Fields{ 55 | "err_msg": err, 56 | }).Fatal("failed to init chain") 57 | } 58 | 59 | return ethRepo 60 | } 61 | -------------------------------------------------------------------------------- /internal/pkg/initialization/channel.go: -------------------------------------------------------------------------------- 1 | package initialization 2 | 3 | import ( 4 | "encoding/json" 5 | "io/ioutil" 6 | "os" 7 | "path" 8 | 9 | log "github.com/sirupsen/logrus" 10 | 11 | "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/repostitory" 12 | "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/services/channels" 13 | "github.com/bianjieai/tibc-relayer-go/internal/pkg/configs" 14 | "github.com/bianjieai/tibc-relayer-go/internal/pkg/types/cache" 15 | metricsmodel "github.com/bianjieai/tibc-relayer-go/internal/pkg/types/mertics" 16 | "github.com/bianjieai/tibc-relayer-go/tools" 17 | ) 18 | 19 | const TendermintAndTendermint = "tendermint_and_tendermint" 20 | const TendermintAndETH = "tendermint_and_eth" 21 | const TendermintAndBsc = "tendermint_and_bsc" 22 | const TendermintAndEthermint = "tendermint_and_ethermint" 23 | 24 | const TypSource = "source" 25 | const TypDest = "dest" 26 | 27 | func ChannelMap(cfg *configs.Config, logger *log.Logger) map[string]channels.IChannel { 28 | if len(cfg.App.ChannelTypes) != 1 { 29 | logger.Fatal("channel_types should be equal 1") 30 | } 31 | for _, channelType := range cfg.App.ChannelTypes { 32 | switch channelType { 33 | case TendermintAndTendermint: 34 | sourceChain := tendermintChain(&cfg.Chain.Source, logger) 35 | destChain := tendermintChain(&cfg.Chain.Dest, logger) 36 | return channelMap(cfg, sourceChain, destChain, logger) 37 | case TendermintAndETH: 38 | sourceChain := tendermintChain(&cfg.Chain.Source, logger) 39 | destChain := ethChain(&cfg.Chain.Dest, logger) 40 | return channelMap(cfg, sourceChain, destChain, logger) 41 | case TendermintAndBsc: 42 | sourceChain := tendermintChain(&cfg.Chain.Source, logger) 43 | destChain := bscChain(&cfg.Chain.Dest, logger) 44 | return channelMap(cfg, sourceChain, destChain, logger) 45 | case TendermintAndEthermint: 46 | sourceChain := tendermintChain(&cfg.Chain.Source, logger) 47 | destChain := ethermintChain(&cfg.Chain.Dest, logger) 48 | return channelMap(cfg, sourceChain, destChain, logger) 49 | default: 50 | logger.WithFields(log.Fields{ 51 | "channel_type": channelType, 52 | }).Fatal("channel type does not exist") 53 | } 54 | } 55 | return nil 56 | } 57 | 58 | func channelMap(cfg *configs.Config, sourceChain, destChain repostitory.IChain, logger *log.Logger) map[string]channels.IChannel { 59 | 60 | metricsModel := metricsmodel.NewMetric(sourceChain.ChainName(), destChain.ChainName()) 61 | // init source chain channel 62 | sourceChannel := channel(cfg, sourceChain, destChain, TypSource, logger) 63 | 64 | // add error_handler mw 65 | sourceChannel = channels.NewWriterMW( 66 | sourceChannel, sourceChain.ChainName(), logger, 67 | tools.DefaultHomePath, tools.DefaultCacheDirName, cfg.Chain.Source.Cache.Filename, 68 | ) 69 | 70 | // add metric mw 71 | 72 | sourceChannel = channels.NewMetricMW(sourceChannel, metricsModel) 73 | 74 | // init dest chain channel 75 | destChannel := channel(cfg, destChain, sourceChain, TypDest, logger) 76 | 77 | // add error_handler mw 78 | destChannel = channels.NewWriterMW( 79 | destChannel, destChain.ChainName(), logger, 80 | tools.DefaultHomePath, tools.DefaultCacheDirName, cfg.Chain.Dest.Cache.Filename, 81 | ) 82 | 83 | // add metric mw 84 | 85 | destChannel = channels.NewMetricMW(destChannel, metricsModel) 86 | channelMap := map[string]channels.IChannel{} 87 | if cfg.Chain.Source.Enabled { 88 | channelMap[sourceChain.ChainName()] = sourceChannel 89 | } 90 | 91 | if cfg.Chain.Dest.Enabled { 92 | channelMap[destChain.ChainName()] = destChannel 93 | } 94 | 95 | if !cfg.Chain.Source.Enabled && !cfg.Chain.Dest.Enabled { 96 | logger.Fatal("cfg.Chain.Source.Enabled and cfg.Chain.Dest.Enabled Cannot be false at the same time") 97 | } 98 | 99 | return channelMap 100 | } 101 | 102 | func channel(cfg *configs.Config, sourceChain, destChain repostitory.IChain, typ string, logger *log.Logger) channels.IChannel { 103 | 104 | var channel channels.IChannel 105 | var channelErr error 106 | var filename string 107 | switch typ { 108 | case TypSource: 109 | filename = path.Join(tools.DefaultHomePath, tools.DefaultCacheDirName, cfg.Chain.Source.Cache.Filename) 110 | case TypDest: 111 | filename = path.Join(tools.DefaultHomePath, tools.DefaultCacheDirName, cfg.Chain.Dest.Cache.Filename) 112 | } 113 | 114 | if _, err := os.Stat(filename); os.IsNotExist(err) { 115 | // If the file does not exist, the initial height is the startHeight in the configuration 116 | switch typ { 117 | case TypSource: 118 | channel, channelErr = channels.NewChannel(sourceChain, destChain, cfg.Chain.Source.Cache.StartHeight, logger) 119 | case TypDest: 120 | channel, channelErr = channels.NewChannel(sourceChain, destChain, cfg.Chain.Dest.Cache.StartHeight, logger) 121 | } 122 | 123 | } else { 124 | // If the file exists, the initial height is the latest_height in the file 125 | file, err := os.Open(filename) 126 | if err != nil { 127 | logger.Fatal("read cache file err: ", err) 128 | } 129 | defer file.Close() 130 | 131 | content, err := ioutil.ReadAll(file) 132 | if err != nil { 133 | logger.Fatal("read cache file err: ", err) 134 | } 135 | 136 | cacheData := &cache.Data{} 137 | err = json.Unmarshal(content, cacheData) 138 | if err != nil { 139 | logger.Fatal("read cache file unmarshal err: ", err) 140 | } 141 | channel, channelErr = channels.NewChannel(sourceChain, destChain, cacheData.LatestHeight, logger) 142 | } 143 | if channelErr != nil { 144 | logger.Fatal("failed to init channel err: ", channelErr) 145 | } 146 | 147 | return channel 148 | } 149 | -------------------------------------------------------------------------------- /internal/pkg/initialization/eth.go: -------------------------------------------------------------------------------- 1 | package initialization 2 | 3 | import ( 4 | log "github.com/sirupsen/logrus" 5 | 6 | "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/repostitory" 7 | repoeth "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/repostitory/eth" 8 | "github.com/bianjieai/tibc-relayer-go/internal/pkg/configs" 9 | "github.com/bianjieai/tibc-relayer-go/internal/pkg/types/constant" 10 | ) 11 | 12 | func ethChain(cfg *configs.ChainCfg, logger *log.Logger) repostitory.IChain { 13 | loggerEntry := logger.WithFields(log.Fields{ 14 | "chain_name": cfg.Eth.ChainName, 15 | }) 16 | 17 | loggerEntry.Info(" init eth chain start") 18 | 19 | contractCfgGroup := repoeth.NewContractCfgGroup() 20 | contractCfgGroup.Packet.Addr = cfg.Eth.Contracts.Packet.Addr 21 | contractCfgGroup.Packet.Topic = cfg.Eth.Contracts.Packet.Topic 22 | contractCfgGroup.Packet.OptPrivKey = cfg.Eth.Contracts.Packet.OptPrivKey 23 | 24 | contractCfgGroup.AckPacket.Addr = cfg.Eth.Contracts.AckPacket.Addr 25 | contractCfgGroup.AckPacket.Topic = cfg.Eth.Contracts.AckPacket.Topic 26 | contractCfgGroup.CleanPacket.Addr = cfg.Eth.Contracts.CleanPacket.Addr 27 | contractCfgGroup.CleanPacket.Topic = cfg.Eth.Contracts.CleanPacket.Topic 28 | 29 | contractCfgGroup.Client.Addr = cfg.Eth.Contracts.Client.Addr 30 | contractCfgGroup.Client.Topic = cfg.Eth.Contracts.Client.Topic 31 | contractCfgGroup.Client.OptPrivKey = cfg.Eth.Contracts.Client.OptPrivKey 32 | 33 | contractBindOptsCfg := repoeth.NewContractBindOptsCfg() 34 | contractBindOptsCfg.ChainID = cfg.Eth.ChainID 35 | contractBindOptsCfg.ClientPrivKey = cfg.Eth.Contracts.Client.OptPrivKey 36 | contractBindOptsCfg.PacketPrivKey = cfg.Eth.Contracts.Packet.OptPrivKey 37 | contractBindOptsCfg.GasLimit = cfg.Eth.GasLimit 38 | contractBindOptsCfg.MaxGasPrice = cfg.Eth.MaxGasPrice 39 | 40 | ethChainCfg := repoeth.NewChainConfig() 41 | ethChainCfg.ContractCfgGroup = contractCfgGroup 42 | ethChainCfg.ContractBindOptsCfg = contractBindOptsCfg 43 | 44 | ethChainCfg.ChainType = constant.ETH 45 | ethChainCfg.ChainName = cfg.Eth.ChainName 46 | ethChainCfg.ChainID = cfg.Eth.ChainID 47 | ethChainCfg.ChainURI = cfg.Eth.URI 48 | ethChainCfg.Slot = cfg.Eth.CommentSlot 49 | ethChainCfg.UpdateClientFrequency = cfg.Eth.UpdateClientFrequency 50 | ethChainCfg.TipCoefficient = cfg.Eth.TipCoefficient 51 | 52 | ethRepo, err := repoeth.NewEth(ethChainCfg) 53 | if err != nil { 54 | loggerEntry.WithFields(log.Fields{ 55 | "err_msg": err, 56 | }).Fatal("failed to init chain") 57 | } 58 | 59 | return ethRepo 60 | } 61 | -------------------------------------------------------------------------------- /internal/pkg/initialization/ethermint.go: -------------------------------------------------------------------------------- 1 | package initialization 2 | 3 | import ( 4 | "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/repostitory" 5 | repoethermint "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/repostitory/ethermint" 6 | "github.com/bianjieai/tibc-relayer-go/internal/pkg/configs" 7 | "github.com/bianjieai/tibc-relayer-go/internal/pkg/types/constant" 8 | coretypes "github.com/irisnet/core-sdk-go/types" 9 | corestore "github.com/irisnet/core-sdk-go/types/store" 10 | log "github.com/sirupsen/logrus" 11 | ) 12 | 13 | func ethermintChain(cfg *configs.ChainCfg, logger *log.Logger) repostitory.IChain { 14 | logger.WithFields(log.Fields{ 15 | "chain_name": cfg.Ethermint.ChainName, 16 | }).Info(" init chain start") 17 | 18 | ethermintCfg := repoethermint.NewConfig() 19 | 20 | // Tendermint 21 | tendermintCfg := repoethermint.NewTendermintConfig() 22 | tendermintCfg.ChainID = cfg.Ethermint.TendermintChainID 23 | tendermintCfg.GrpcAddr = cfg.Ethermint.GrpcAddr 24 | tendermintCfg.RPCAddr = cfg.Ethermint.RPCAddr 25 | options := []coretypes.Option{ 26 | coretypes.KeyDAOOption(corestore.NewMemory(corestore.NewMemory(nil))), 27 | coretypes.TimeoutOption(cfg.Ethermint.RequestTimeout), 28 | coretypes.ModeOption(coretypes.Commit), 29 | coretypes.GasOption(cfg.Ethermint.Gas), 30 | coretypes.CachedOption(true), 31 | } 32 | if cfg.Ethermint.Algo != "" { 33 | options = append(options, coretypes.AlgoOption(cfg.Ethermint.Algo)) 34 | } 35 | tendermintCfg.Options = options 36 | 37 | ethermintCfg.Tendermint = tendermintCfg 38 | 39 | // Eth 40 | contractCfgGroup := repoethermint.NewContractCfgGroup() 41 | contractCfgGroup.Packet.Addr = cfg.Ethermint.Contracts.Packet.Addr 42 | contractCfgGroup.Packet.Topic = cfg.Ethermint.Contracts.Packet.Topic 43 | contractCfgGroup.Packet.OptPrivKey = cfg.Ethermint.Contracts.Packet.OptPrivKey 44 | 45 | contractCfgGroup.AckPacket.Addr = cfg.Ethermint.Contracts.AckPacket.Addr 46 | contractCfgGroup.AckPacket.Topic = cfg.Ethermint.Contracts.AckPacket.Topic 47 | contractCfgGroup.CleanPacket.Addr = cfg.Ethermint.Contracts.CleanPacket.Addr 48 | contractCfgGroup.CleanPacket.Topic = cfg.Ethermint.Contracts.CleanPacket.Topic 49 | 50 | contractCfgGroup.Client.Addr = cfg.Ethermint.Contracts.Client.Addr 51 | contractCfgGroup.Client.Topic = cfg.Ethermint.Contracts.Client.Topic 52 | contractCfgGroup.Client.OptPrivKey = cfg.Ethermint.Contracts.Client.OptPrivKey 53 | 54 | contractBindOptsCfg := repoethermint.NewContractBindOptsCfg() 55 | contractBindOptsCfg.ChainID = cfg.Ethermint.EthChainID 56 | contractBindOptsCfg.ClientPrivKey = cfg.Ethermint.Contracts.Client.OptPrivKey 57 | contractBindOptsCfg.PacketPrivKey = cfg.Ethermint.Contracts.Packet.OptPrivKey 58 | contractBindOptsCfg.GasLimit = cfg.Ethermint.GasLimit 59 | contractBindOptsCfg.MaxGasPrice = cfg.Ethermint.MaxGasPrice 60 | 61 | ethChainCfg := repoethermint.NewEthChainConfig() 62 | ethChainCfg.ContractCfgGroup = contractCfgGroup 63 | ethChainCfg.ContractBindOptsCfg = contractBindOptsCfg 64 | 65 | ethChainCfg.ChainURI = cfg.Ethermint.URI 66 | ethChainCfg.Slot = cfg.Ethermint.CommentSlot 67 | ethChainCfg.TipCoefficient = cfg.Ethermint.TipCoefficient 68 | ethermintCfg.Eth = ethChainCfg 69 | 70 | chainRepo, err := repoethermint.NewEthermintClient( 71 | constant.Ethermint, 72 | cfg.Ethermint.ChainName, 73 | cfg.Ethermint.UpdateClientFrequency, 74 | ethermintCfg, 75 | ) 76 | if err != nil { 77 | logger.WithFields(log.Fields{ 78 | "chain_name": cfg.Tendermint.ChainName, 79 | "err_msg": err, 80 | }).Fatal("failed to init chain") 81 | } 82 | 83 | return chainRepo 84 | } 85 | -------------------------------------------------------------------------------- /internal/pkg/initialization/logger.go: -------------------------------------------------------------------------------- 1 | package initialization 2 | 3 | import ( 4 | log "github.com/sirupsen/logrus" 5 | 6 | "github.com/bianjieai/tibc-relayer-go/internal/pkg/configs" 7 | ) 8 | 9 | func Logger(cfg *configs.Config) *log.Logger { 10 | logger := log.New() 11 | if cfg.App.Env == "prod" { 12 | logger.SetFormatter(&log.JSONFormatter{}) 13 | } else { 14 | logger.SetFormatter(&log.TextFormatter{ 15 | TimestampFormat: "2006-01-02 15:04:05", 16 | FullTimestamp: true, 17 | }) 18 | } 19 | switch cfg.App.LogLevel { 20 | case "debug": 21 | logger.SetLevel(log.DebugLevel) 22 | case "error": 23 | logger.SetLevel(log.ErrorLevel) 24 | case "warn": 25 | logger.SetLevel(log.WarnLevel) 26 | default: 27 | logger.SetLevel(log.InfoLevel) 28 | } 29 | return logger 30 | } 31 | -------------------------------------------------------------------------------- /internal/pkg/initialization/tendermint.go: -------------------------------------------------------------------------------- 1 | package initialization 2 | 3 | import ( 4 | coretypes "github.com/irisnet/core-sdk-go/types" 5 | corestore "github.com/irisnet/core-sdk-go/types/store" 6 | log "github.com/sirupsen/logrus" 7 | 8 | "github.com/bianjieai/tibc-relayer-go/internal/app/relayer/repostitory" 9 | "github.com/bianjieai/tibc-relayer-go/internal/pkg/configs" 10 | "github.com/bianjieai/tibc-relayer-go/internal/pkg/types/constant" 11 | ) 12 | 13 | func tendermintChain(cfg *configs.ChainCfg, logger *log.Logger) repostitory.IChain { 14 | 15 | logger.WithFields(log.Fields{ 16 | "chain_name": cfg.Tendermint.ChainName, 17 | }).Info(" init chain start") 18 | 19 | chainCfg := repostitory.NewTerndermintConfig() 20 | chainCfg.ChainID = cfg.Tendermint.ChainID 21 | chainCfg.GrpcAddr = cfg.Tendermint.GrpcAddr 22 | chainCfg.RPCAddr = cfg.Tendermint.RPCAddr 23 | 24 | fee := coretypes.NewDecCoins( 25 | coretypes.NewDecCoin( 26 | cfg.Tendermint.Fee.Denom, 27 | coretypes.NewInt(cfg.Tendermint.Fee.Amount))) 28 | 29 | chainCfg.BaseTx = coretypes.BaseTx{ 30 | From: cfg.Tendermint.Key.Name, 31 | Password: cfg.Tendermint.Key.Password, 32 | Gas: cfg.Tendermint.Gas, 33 | Mode: coretypes.Commit, 34 | Fee: fee, 35 | SimulateAndExecute: false, 36 | GasAdjustment: 1.5, 37 | } 38 | chainCfg.Name = cfg.Tendermint.Key.Name 39 | chainCfg.Password = cfg.Tendermint.Key.Password 40 | chainCfg.PrivKeyArmor = cfg.Tendermint.Key.PrivKeyArmor 41 | options := []coretypes.Option{ 42 | coretypes.KeyDAOOption(corestore.NewMemory(corestore.NewMemory(nil))), 43 | coretypes.TimeoutOption(cfg.Tendermint.RequestTimeout), 44 | coretypes.ModeOption(coretypes.Commit), 45 | coretypes.GasOption(cfg.Tendermint.Gas), 46 | coretypes.CachedOption(true), 47 | } 48 | if cfg.Tendermint.Algo != "" { 49 | options = append(options, coretypes.AlgoOption(cfg.Tendermint.Algo)) 50 | } 51 | chainCfg.Options = options 52 | 53 | allowMapSender := map[string][]string{} 54 | for _, allow := range cfg.Tendermint.Allows { 55 | allowMapSender[allow.ContractAddr] = allow.Senders 56 | } 57 | 58 | chainRepo, err := repostitory.NewTendermintClient( 59 | constant.Tendermint, 60 | cfg.Tendermint.ChainName, 61 | cfg.Tendermint.UpdateClientFrequency, 62 | allowMapSender, 63 | cfg.Tendermint.CleanPacketEnabled, 64 | chainCfg, 65 | ) 66 | if err != nil { 67 | logger.WithFields(log.Fields{ 68 | "chain_name": cfg.Tendermint.ChainName, 69 | "err_msg": err, 70 | }).Fatal("failed to init chain") 71 | } 72 | 73 | return chainRepo 74 | } 75 | -------------------------------------------------------------------------------- /internal/pkg/types/cache/cache.go: -------------------------------------------------------------------------------- 1 | package cache 2 | 3 | type Data struct { 4 | LatestHeight uint64 `json:"latest_height"` 5 | } 6 | -------------------------------------------------------------------------------- /internal/pkg/types/constant/const.go: -------------------------------------------------------------------------------- 1 | package constant 2 | 3 | const ( 4 | Tendermint = "tendermint" 5 | BSC = "bsc" 6 | ETH = "eth" 7 | Ethermint = "ethermint" 8 | 9 | //ChannelTendermintToTendermint = "tendermint,tendermint" 10 | //ChannelTendermintToEth = "tendermint,eth" 11 | //ChannelEthToTendermint = "eth,tendermint" 12 | ) 13 | -------------------------------------------------------------------------------- /internal/pkg/types/errors/error.go: -------------------------------------------------------------------------------- 1 | package errors 2 | 3 | import "fmt" 4 | 5 | const RootCodeSpace = "relayer" 6 | 7 | var ( 8 | ErrInternal = Register(RootCodeSpace, 1, "internal") 9 | ErrChainConn = Register(RootCodeSpace, 2, "connection chain failed") 10 | ErrGetLightClientState = Register(RootCodeSpace, 3, "failed to get light client state") 11 | ErrGetBlockHeader = Register(RootCodeSpace, 4, "failed to get block header") 12 | ErrUpdateClient = Register(RootCodeSpace, 5, "failed to update client") 13 | ErrGetPackets = Register(RootCodeSpace, 6, "failed to get packets") 14 | ErrGetCommitmentPacket = Register(RootCodeSpace, 7, "failed to get commitment packet") 15 | ErrGetAckPacket = Register(RootCodeSpace, 8, "failed to get ack packet") 16 | ErrGetReceiptPacket = Register(RootCodeSpace, 9, "failed to get receipt packet") 17 | ErrGetProof = Register(RootCodeSpace, 10, "failed to get proof") 18 | ErrGetLatestHeight = Register(RootCodeSpace, 11, "failed to get latest height") 19 | ErrRecvPacket = Register(RootCodeSpace, 12, "failed to recv packet") 20 | ErrNotProduced = Register(RootCodeSpace, 13, "failed to not produced") 21 | ErrDelayTime = Register(RootCodeSpace, 14, "failed to get delay time") 22 | ErrDelayHeight = Register(RootCodeSpace, 15, "failed to get delay height") 23 | ErrCurBlockTime = Register(RootCodeSpace, 16, "failed to get current block time") 24 | ErrUnknownMsg = Register(RootCodeSpace, 17, "failed to unknown msg type") 25 | ) 26 | 27 | var usedCodes = map[string]*Error{} 28 | 29 | func getUsed(codespace string, code uint32) *Error { 30 | return usedCodes[errorID(codespace, code)] 31 | } 32 | 33 | func setUsed(err *Error) { 34 | usedCodes[errorID(err.codeSpace, err.code)] = err 35 | } 36 | 37 | func errorID(codespace string, code uint32) string { 38 | return fmt.Sprintf("%s:%d", codespace, code) 39 | } 40 | 41 | type IError interface { 42 | error 43 | Code() uint32 44 | CodeSpace() string 45 | } 46 | 47 | type Error struct { 48 | codeSpace string 49 | code uint32 50 | desc string 51 | } 52 | 53 | func New(codeSpace string, code uint32, desc string) *Error { 54 | return &Error{codeSpace: codeSpace, code: code, desc: desc} 55 | } 56 | 57 | func (e Error) Error() string { 58 | return e.desc 59 | } 60 | 61 | func (e Error) Code() uint32 { 62 | return e.code 63 | } 64 | 65 | func (e Error) CodeSpace() string { 66 | return e.codeSpace 67 | } 68 | 69 | func Register(codespace string, code uint32, description string) *Error { 70 | if e := getUsed(codespace, code); e != nil { 71 | panic(fmt.Sprintf("error with code %d is already registered: %q", code, e.desc)) 72 | } 73 | 74 | err := New(codespace, code, description) 75 | setUsed(err) 76 | 77 | return err 78 | } 79 | -------------------------------------------------------------------------------- /internal/pkg/types/mertics/metric.go: -------------------------------------------------------------------------------- 1 | package mertics 2 | 3 | import ( 4 | metricsprometheus "github.com/go-kit/kit/metrics/prometheus" 5 | "github.com/prometheus/client_golang/prometheus" 6 | ) 7 | 8 | type Model struct { 9 | Sys *metricsprometheus.Gauge 10 | Chain *metricsprometheus.Gauge 11 | 12 | sourceChainName string 13 | destChainName string 14 | } 15 | 16 | func NewMetric(sourceChainName, destChainName string) *Model { 17 | sysMetric := metricsprometheus.NewGaugeFrom(prometheus.GaugeOpts{ 18 | Subsystem: "relayer", 19 | Name: "system", 20 | Help: "system status", 21 | }, []string{"chain_name"}) 22 | 23 | chainMetric := metricsprometheus.NewGaugeFrom(prometheus.GaugeOpts{ 24 | Subsystem: "relayer", 25 | Name: "chain", 26 | Help: "chain status", 27 | }, []string{"chain_name", "option"}) 28 | 29 | model := &Model{ 30 | Sys: sysMetric, 31 | Chain: chainMetric, 32 | sourceChainName: sourceChainName, 33 | destChainName: destChainName, 34 | } 35 | model.initMetric() 36 | 37 | return model 38 | } 39 | 40 | func (m *Model) initMetric() { 41 | sourceSysLabels := []string{"chain_name", m.sourceChainName} 42 | m.Sys.With(sourceSysLabels...).Set(1) 43 | destSysLabels := []string{"chain_name", m.destChainName} 44 | m.Sys.With(destSysLabels...).Set(1) 45 | 46 | sourceConnChainLabels := []string{"chain_name", m.sourceChainName, "option", "connection"} 47 | sourceGetClientStatusLabels := []string{"chain_name", m.sourceChainName, "option", "client_get_client_status"} 48 | sourceUpdateClientLabels := []string{"chain_name", m.sourceChainName, "option", "client_update_client_status"} 49 | sourceRecvPacketLabels := []string{"chain_name", m.sourceChainName, "option", "packet_recv_packet"} 50 | sourceGetPacketLabels := []string{"chain_name", m.sourceChainName, "option", "packet_get_packet"} 51 | sourceGetCommitmentLabels := []string{"chain_name", m.sourceChainName, "option", "packet_get_commitment"} 52 | sourceGetProofLabels := []string{"chain_name", m.sourceChainName, "option", "packet_get_proof"} 53 | sourceGetReceiptLabels := []string{"chain_name", m.sourceChainName, "option", "packet_get_receipt"} 54 | 55 | destConnChainLabels := []string{"chain_name", m.destChainName, "option", "connection"} 56 | destGetClientStatusLabels := []string{"chain_name", m.destChainName, "option", "client_get_client_status"} 57 | destUpdateClientLabels := []string{"chain_name", m.destChainName, "option", "client_update_client_status"} 58 | destRecvPacketLabels := []string{"chain_name", m.destChainName, "option", "packet_recv_packet"} 59 | destGetPacketLabels := []string{"chain_name", m.destChainName, "option", "packet_get_packet"} 60 | destGetCommitmentLabels := []string{"chain_name", m.destChainName, "option", "packet_get_commitment"} 61 | destGetProofLabels := []string{"chain_name", m.destChainName, "option", "packet_get_proof"} 62 | destGetReceiptLabels := []string{"chain_name", m.destChainName, "option", "packet_get_receipt"} 63 | 64 | m.Chain.With(sourceConnChainLabels...).Set(1) 65 | m.Chain.With(sourceGetClientStatusLabels...).Set(1) 66 | m.Chain.With(sourceUpdateClientLabels...).Set(1) 67 | m.Chain.With(sourceRecvPacketLabels...).Set(1) 68 | m.Chain.With(sourceGetPacketLabels...).Set(1) 69 | m.Chain.With(sourceGetCommitmentLabels...).Set(1) 70 | m.Chain.With(sourceGetProofLabels...).Set(1) 71 | m.Chain.With(sourceGetReceiptLabels...).Set(1) 72 | 73 | m.Chain.With(destConnChainLabels...).Set(1) 74 | m.Chain.With(destGetClientStatusLabels...).Set(1) 75 | m.Chain.With(destUpdateClientLabels...).Set(1) 76 | m.Chain.With(destRecvPacketLabels...).Set(1) 77 | m.Chain.With(destGetPacketLabels...).Set(1) 78 | m.Chain.With(destGetCommitmentLabels...).Set(1) 79 | m.Chain.With(destGetProofLabels...).Set(1) 80 | m.Chain.With(destGetReceiptLabels...).Set(1) 81 | } 82 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "github.com/bianjieai/tibc-relayer-go/cmd" 4 | 5 | func main() { 6 | cmd.Execute() 7 | } 8 | -------------------------------------------------------------------------------- /tools/global.go: -------------------------------------------------------------------------------- 1 | package tools 2 | 3 | import ( 4 | "os" 5 | "path/filepath" 6 | ) 7 | 8 | const DefaultHomeDirName = ".tibc-relayer" 9 | const DefaultConfigDirName = "configs" 10 | const DefaultConfigName = "config.toml" 11 | const DefaultCacheDirName = "cache" 12 | 13 | var ( 14 | UserDir, _ = os.UserHomeDir() 15 | DefaultHomePath = filepath.Join(UserDir, DefaultHomeDirName) 16 | ) 17 | -------------------------------------------------------------------------------- /tools/keys.go: -------------------------------------------------------------------------------- 1 | package tools 2 | 3 | import ( 4 | "math/big" 5 | 6 | "github.com/ethereum/go-ethereum/common" 7 | "github.com/ethereum/go-ethereum/crypto" 8 | ) 9 | 10 | type ProofKeyConstructor struct { 11 | sourceChain string 12 | destChain string 13 | sequence uint64 14 | } 15 | 16 | func NewProofKeyConstructor(sourceChain string, destChain string, sequence uint64) ProofKeyConstructor { 17 | return ProofKeyConstructor{ 18 | sourceChain: sourceChain, 19 | destChain: destChain, 20 | sequence: sequence, 21 | } 22 | } 23 | 24 | func (k ProofKeyConstructor) GetPacketCommitmentProofKey(slot int64) []byte { 25 | hash := crypto.Keccak256Hash( 26 | PacketCommitmentKey(k.sourceChain, k.destChain, k.sequence), 27 | common.LeftPadBytes(big.NewInt(slot).Bytes(), 32), 28 | ) 29 | return hash.Bytes() 30 | } 31 | 32 | func (k ProofKeyConstructor) GetAckProofKey(slot int64) []byte { 33 | hash := crypto.Keccak256Hash( 34 | PacketAcknowledgementKey(k.sourceChain, k.destChain, k.sequence), 35 | common.LeftPadBytes(big.NewInt(slot).Bytes(), 32), 36 | ) 37 | return hash.Bytes() 38 | } 39 | 40 | func (k ProofKeyConstructor) GetCleanPacketCommitmentProofKey(slot int64) []byte { 41 | hash := crypto.Keccak256Hash( 42 | CleanPacketCommitmentKey(k.sourceChain, k.destChain), 43 | common.LeftPadBytes(big.NewInt(slot).Bytes(), 32), 44 | ) 45 | return hash.Bytes() 46 | } 47 | -------------------------------------------------------------------------------- /tools/paths.go: -------------------------------------------------------------------------------- 1 | package tools 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | // KVStore key prefixes for IBC 8 | const ( 9 | KeySequencePrefix = "sequences" 10 | KeyNextSeqSendPrefix = "nextSequenceSend" 11 | KeyPacketCommitmentPrefix = "commitments" 12 | KeyPacketAckPrefix = "acks" 13 | KeyPacketReceiptPrefix = "receipts" 14 | KeyCleanPacketCommitmentPrefix = "clean" 15 | ) 16 | 17 | // NextSequenceSendPath defines the next send sequence counter store path 18 | func NextSequenceSendPath(sourceChain, destChain string) string { 19 | return fmt.Sprintf("%s/%s", KeyNextSeqSendPrefix, packetPath(sourceChain, destChain)) 20 | } 21 | 22 | // NextSequenceSendKey returns the store key for the send sequence of a particular 23 | // channel binded to a specific port. 24 | func NextSequenceSendKey(sourceChain, destChain string) []byte { 25 | return []byte(NextSequenceSendPath(sourceChain, destChain)) 26 | } 27 | 28 | // PacketCommitmentPath defines the commitments to packet data fields store path 29 | func PacketCommitmentPath(sourceChain, destinationChain string, sequence uint64) string { 30 | return fmt.Sprintf("%s/%d", PacketCommitmentPrefixPath(sourceChain, destinationChain), sequence) 31 | } 32 | 33 | // PacketCommitmentKey returns the store key of under which a packet commitment 34 | // is stored 35 | func PacketCommitmentKey(sourceChain, destinationChain string, sequence uint64) []byte { 36 | return []byte(PacketCommitmentPath(sourceChain, destinationChain, sequence)) 37 | } 38 | 39 | // PacketCommitmentPrefixPath defines the prefix for commitments to packet data fields store path. 40 | func PacketCommitmentPrefixPath(sourceChain, destinationChain string) string { 41 | return fmt.Sprintf("%s/%s/%s", KeyPacketCommitmentPrefix, packetPath(sourceChain, destinationChain), KeySequencePrefix) 42 | } 43 | 44 | // PacketAcknowledgementPath defines the packet acknowledgement store path 45 | func PacketAcknowledgementPath(sourceChain, destinationChain string, sequence uint64) string { 46 | return fmt.Sprintf("%s/%d", PacketAcknowledgementPrefixPath(sourceChain, destinationChain), sequence) 47 | } 48 | 49 | // PacketAcknowledgementKey returns the store key of under which a packet 50 | // acknowledgement is stored 51 | func PacketAcknowledgementKey(sourceChain, destinationChain string, sequence uint64) []byte { 52 | return []byte(PacketAcknowledgementPath(sourceChain, destinationChain, sequence)) 53 | } 54 | 55 | // PacketAcknowledgementPrefixPath defines the prefix for commitments to packet data fields store path. 56 | func PacketAcknowledgementPrefixPath(sourceChain, destinationChain string) string { 57 | return fmt.Sprintf("%s/%s/%s", KeyPacketAckPrefix, packetPath(sourceChain, destinationChain), KeySequencePrefix) 58 | } 59 | 60 | // PacketReceiptPath defines the packet receipt store path 61 | func PacketReceiptPath(sourceChain, destinationChain string, sequence uint64) string { 62 | return fmt.Sprintf("%s/%d", PacketReceiptPrefixPath(sourceChain, destinationChain), sequence) 63 | } 64 | 65 | // PacketReceiptKey returns the store key of under which a packet 66 | // receipt is stored 67 | func PacketReceiptKey(sourceChain, destinationChain string, sequence uint64) []byte { 68 | return []byte(PacketReceiptPath(sourceChain, destinationChain, sequence)) 69 | } 70 | 71 | // PacketReceiptKey returns the store key of under which a packet 72 | // receipt is stored 73 | func PacketReceiptPrefixPath(sourceChain, destinationChain string) string { 74 | return fmt.Sprintf("%s/%s/%s", KeyPacketReceiptPrefix, packetPath(sourceChain, destinationChain), KeySequencePrefix) 75 | } 76 | 77 | func packetPath(sourceChain, destinationChain string) string { 78 | return fmt.Sprintf("%s/%s", sourceChain, destinationChain) 79 | } 80 | 81 | // CleanPacketCommitmentKey returns the store key of under which a clean packet commitment 82 | // is stored 83 | func CleanPacketCommitmentKey(sourceChain, destinationChain string) []byte { 84 | return []byte(CleanPacketCommitmentPath(sourceChain, destinationChain)) 85 | } 86 | 87 | // CleanPacketCommitmentPrefixPath defines the prefix for commitments to packet data fields store path. 88 | func CleanPacketCommitmentPath(sourceChain, destinationChain string) string { 89 | return fmt.Sprintf("%s/%s", KeyCleanPacketCommitmentPrefix, packetPath(sourceChain, destinationChain)) 90 | } 91 | --------------------------------------------------------------------------------