├── .github ├── dependabot.yml └── workflows │ ├── deny.yml │ ├── lint.yml │ └── rust.yml ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── deny.toml ├── ethereum-proxy ├── Cargo.toml ├── plugins │ └── accounts │ │ ├── Cargo.toml │ │ ├── src │ │ ├── config.rs │ │ └── lib.rs │ │ └── transaction │ │ ├── Cargo.toml │ │ └── src │ │ └── lib.rs └── src │ ├── cli.yml │ └── main.rs ├── examples ├── cache.json ├── permissions.json └── upstream.json ├── generic-proxy ├── Cargo.toml ├── bin │ ├── cli.yml │ └── rpc-proxy.rs └── src │ └── lib.rs ├── overview.svg ├── plugins ├── permissioning │ ├── Cargo.toml │ └── src │ │ ├── config.rs │ │ └── lib.rs ├── simple-cache │ ├── Cargo.toml │ └── src │ │ ├── config.rs │ │ └── lib.rs ├── upstream │ ├── Cargo.toml │ └── src │ │ ├── config.rs │ │ ├── helpers.rs │ │ ├── lib.rs │ │ └── shared.rs └── ws-upstream │ ├── Cargo.toml │ └── src │ ├── config.rs │ └── lib.rs ├── proxy ├── cli-params │ ├── Cargo.toml │ └── src │ │ └── lib.rs ├── cli │ ├── Cargo.toml │ └── src │ │ └── lib.rs └── transports │ ├── Cargo.toml │ └── src │ ├── http.rs │ ├── ipc.rs │ ├── lib.rs │ ├── tcp.rs │ └── ws.rs ├── rustfmt.toml └── substrate-proxy ├── Cargo.toml └── src ├── cli.yml └── main.rs /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: cargo 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | open-pull-requests-limit: 10 8 | ignore: 9 | - dependency-name: jsonrpc-ipc-server 10 | versions: 11 | - 17.0.0 12 | -------------------------------------------------------------------------------- /.github/workflows/deny.yml: -------------------------------------------------------------------------------- 1 | name: Cargo deny 2 | 3 | on: 4 | pull_request: 5 | schedule: 6 | - cron: '0 0 * * *' 7 | push: 8 | branches: 9 | - master 10 | tags: 11 | - v* 12 | paths-ignore: 13 | - 'README.md' 14 | jobs: 15 | cargo-deny: 16 | runs-on: ubuntu-latest 17 | steps: 18 | - name: Cancel Previous Runs 19 | uses: styfle/cancel-workflow-action@0.4.1 20 | with: 21 | access_token: ${{ github.token }} 22 | - name: Checkout sources & submodules 23 | uses: actions/checkout@master 24 | with: 25 | fetch-depth: 5 26 | submodules: recursive 27 | - name: Cargo deny 28 | uses: EmbarkStudios/cargo-deny-action@v1 29 | with: 30 | command: "check --hide-inclusion-graph" 31 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: Check style 2 | 3 | on: 4 | pull_request: 5 | push: 6 | branches: 7 | - master 8 | tags: 9 | - v* 10 | paths-ignore: 11 | - 'README.md' 12 | jobs: 13 | ## Check stage 14 | check-fmt: 15 | name: Check RustFmt 16 | runs-on: ubuntu-latest 17 | env: 18 | RUST_BACKTRACE: full 19 | steps: 20 | - name: Cancel Previous Runs 21 | uses: styfle/cancel-workflow-action@0.4.1 22 | with: 23 | access_token: ${{ github.token }} 24 | - name: Checkout sources & submodules 25 | uses: actions/checkout@master 26 | with: 27 | fetch-depth: 5 28 | submodules: recursive 29 | - name: Add rustfmt 30 | run: rustup component add rustfmt 31 | - name: rust-fmt check 32 | uses: actions-rs/cargo@master 33 | with: 34 | command: fmt 35 | args: --all -- --check --config merge_imports=true 36 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Compilation and Testing Suite 2 | 3 | on: 4 | pull_request: 5 | push: 6 | branches: 7 | - master 8 | tags: 9 | - v* 10 | paths-ignore: 11 | - 'README.md' 12 | jobs: 13 | 14 | check-test-build: 15 | name: Check, test and build 16 | runs-on: ubuntu-latest 17 | env: 18 | RUST_BACKTRACE: full 19 | steps: 20 | - name: Cancel Previous Runs 21 | uses: styfle/cancel-workflow-action@0.4.1 22 | with: 23 | access_token: ${{ github.token }} 24 | - name: Checkout sources & submodules 25 | uses: actions/checkout@master 26 | with: 27 | fetch-depth: 5 28 | submodules: recursive 29 | ## Check Stage 30 | - name: Checking rust-stable 31 | uses: actions-rs/cargo@master 32 | with: 33 | command: check 34 | toolchain: stable 35 | args: --all --verbose 36 | 37 | ## Test Stage 38 | - name: Testing rust-stable 39 | uses: actions-rs/cargo@master 40 | with: 41 | command: test 42 | toolchain: stable 43 | args: --all --verbose 44 | 45 | ## Build Stage 46 | - name: Building rust-stable 47 | uses: actions-rs/cargo@master 48 | if: github.ref == 'refs/heads/master' 49 | with: 50 | command: build 51 | toolchain: stable 52 | args: --all --verbose 53 | 54 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | /target 3 | **/*.rs.bk 4 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = [ 3 | "ethereum-proxy", 4 | "generic-proxy", 5 | "plugins/permissioning", 6 | "plugins/simple-cache", 7 | "plugins/upstream", 8 | "plugins/ws-upstream", 9 | "proxy/cli", 10 | "proxy/cli-params", 11 | "proxy/transports", 12 | "substrate-proxy", 13 | "ethereum-proxy/plugins/accounts/transaction" 14 | ] 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | 676 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | jsonrpc-proxy 2 | ================================= 3 | # Status 4 | 5 | This library has not been updated in a while and is here just for archive purposes. You might consider looking at https://github.com/AcalaNetwork/subway which is supposed to serve the same purpose and is way more recent. 6 | 7 | # Overview 8 | 9 | The proxy has a pluggable architecture of middlewares. Each middleware receives every RPC call and can decide to either terminate it (return a response) or pass it forward to the next middleware. Middlewares are also able to modify the response object. 10 | 11 | As the last middleware we are using `Upstream` middleware, which is responsible for calling the target node. 12 | 13 | Middlewares included in this repo: 14 | 15 | - Simple caching middleware 16 | - Simple permissioning middleware 17 | - WebSockets upstream middleware 18 | 19 | Similarly pluggable are JSON-RPC transports that the proxy exposes. Currently supported: 20 | - TCP server 21 | - HTTP server 22 | - IPC server 23 | - WebSockets server 24 | 25 | ![Proxy Overview](./overview.svg) 26 | 27 | # Ideas 28 | 29 | - [ ] Rate Limitting 30 | - [ ] Fail over 31 | - [ ] Load balancing 32 | 33 | # Usage 34 | 35 | ``` 36 | rpc-proxy 0.1 37 | Parity Technologies Ltd 38 | Generic RPC proxy, featuring caching and load balancing. 39 | 40 | USAGE: 41 | rpc-proxy [OPTIONS] 42 | 43 | FLAGS: 44 | -h, --help Prints help information 45 | -V, --version Prints version information 46 | 47 | OPTIONS: 48 | --cached-methods-path 49 | A path to a JSON file containing a list of methods that should be 50 | cached. See examples for the file schema. [default: -] 51 | --http-cors 52 | Specify CORS header for HTTP JSON-RPC API responses.Special options: 53 | "all", "null", "none". [default: none] 54 | --http-cors-max-age 55 | Configures AccessControlMaxAge header value in milliseconds.Informs 56 | the client that the preflight request is not required for the 57 | specified time. Use 0 to disable. [default: 3600000] 58 | --http-hosts 59 | List of allowed Host header values. This option willvalidate the 60 | Host header sent by the browser, it isadditional security against 61 | some attack vectors. Specialoptions: "all", "none". [default: none] 62 | --http-ip 63 | Configures HTTP server interface. [default: 127.0.0.1] 64 | 65 | --http-max-payload 66 | Maximal HTTP server payload in Megabytes. [default: 5] 67 | 68 | --http-port 69 | Configures HTTP server listening port. [default: 9934] 70 | 71 | --http-rest-api 72 | Enables REST -> RPC converter for HTTP server. Allows you tocall RPC 73 | methods with `POST ///`.The "secure" 74 | option requires the `Content-Type: application/json`header to be 75 | sent with the request (even though the payload is ignored)to prevent 76 | accepting POST requests from any website (via form submission).The 77 | "unsecure" option does not require any `Content-Type`.Possible 78 | options: "unsecure", "secure", "disabled". [default: disabled] 79 | --http-threads 80 | Configures HTTP server threads. [default: 4] 81 | 82 | --ipc-path 83 | Configures IPC server socket path. [default: ./jsonrpc.ipc] 84 | 85 | --ipc-request-separator 86 | Configures TCP server request separator (single byte). If "none" the 87 | parser will try to figure out requests boundaries. [default: none] 88 | --tcp-ip 89 | Configures TCP server interface. [default: 127.0.0.1] 90 | 91 | --tcp-port 92 | Configures TCP server listening port. [default: 9955] 93 | 94 | --tcp-request-separator 95 | Configures TCP server request separator (single byte). If "none" the 96 | parser will try to figure out requests boundaries. Default is new 97 | line character. [default: 10] 98 | --upstream-ws 99 | Address of the parent WebSockets RPC server that we should connect 100 | to. [default: ws://127.0.0.1:9944] 101 | --websockets-hosts 102 | List of allowed Host header values. This option will validate the 103 | Host header sent by the browser, it is additional security against 104 | some attack vectors. Special options: "all", "none". [default: none] 105 | --websockets-ip 106 | Configures WebSockets server interface. [default: 127.0.0.1] 107 | 108 | --websockets-max-connections 109 | Maximum number of allowed concurrent WebSockets JSON-RPC 110 | connections. [default: 100] 111 | --websockets-origins 112 | Specify Origin header values allowed to connect. Special options: 113 | "all", "none". [default: none] 114 | --websockets-port 115 | Configures WebSockets server listening port. [default: 9945] 116 | ``` 117 | -------------------------------------------------------------------------------- /deny.toml: -------------------------------------------------------------------------------- 1 | # This template contains all of the possible sections and their default values 2 | 3 | # Note that all fields that take a lint level have these possible values: 4 | # * deny - An error will be produced and the check will fail 5 | # * warn - A warning will be produced, but the check will not fail 6 | # * allow - No warning or error will be produced, though in some cases a note will be 7 | 8 | # If 1 or more target triples (and optionally, target_features) are specified, only 9 | # the specified targets will be checked when running `cargo deny check`. This means, 10 | # if a particular package is only ever used as a target specific dependency, such 11 | # as, for example, the `nix` crate only being used via the `target_family = "unix"` 12 | # configuration, that only having windows targets in this list would mean the nix 13 | # crate, as well as any of its exclusive dependencies not shared by any other 14 | # crates, would be ignored, as the target list here is effectively saying which 15 | # targets you are building for. 16 | targets = [ 17 | # The triple can be any string, but only the target triples built in to 18 | # rustc (as of 1.40) can be checked against actual config expressions 19 | #{ triple = "x86_64-unknown-linux-musl" }, 20 | # You can also specify which target_features you promise are enabled for a particular 21 | # target. target_features are currently not validated against the actual valid 22 | # features supported by the target architecture. 23 | #{ triple = "wasm32-unknown-unknown", features = ["atomics"] }, 24 | ] 25 | 26 | # This section is considered when running `cargo deny check advisories` 27 | # More documentation for the advisories section can be found here: 28 | # https://github.com/EmbarkStudios/cargo-deny#the-advisories-section 29 | [advisories] 30 | # The path where the advisory database is cloned/fetched into 31 | db-path = "~/.cargo/advisory-db" 32 | # The url of the advisory database to use 33 | db-urls = ["https://github.com/rustsec/advisory-db"] 34 | # The lint level for security vulnerabilities 35 | vulnerability = "warn" 36 | # The lint level for unmaintained crates 37 | unmaintained = "warn" 38 | # The lint level for crates with security notices. Note that as of 39 | # 2019-12-17 there are no security notice advisories in https://github.com/rustsec/advisory-db 40 | notice = "warn" 41 | # A list of advisory IDs to ignore. Note that ignored advisories will still output 42 | # a note when they are encountered. 43 | ignore = [] 44 | # Threshold for security vulnerabilities, any vulnerability with a CVSS score 45 | # lower than the range specified will be ignored. Note that ignored advisories 46 | # will still output a note when they are encountered. 47 | # * None - CVSS Score 0.0 48 | # * Low - CVSS Score 0.1 - 3.9 49 | # * Medium - CVSS Score 4.0 - 6.9 50 | # * High - CVSS Score 7.0 - 8.9 51 | # * Critical - CVSS Score 9.0 - 10.0 52 | #severity-threshold = 53 | 54 | # This section is considered when running `cargo deny check licenses` 55 | # More documentation for the licenses section can be found here: 56 | # https://github.com/EmbarkStudios/cargo-deny#the-licenses-section 57 | [licenses] 58 | # The lint level for crates which do not have a detectable license 59 | unlicensed = "warn" 60 | # List of explictly allowed licenses 61 | # See https://spdx.org/licenses/ for list of possible licenses 62 | # [possible values: any SPDX 3.7 short identifier (+ optional exception)]. 63 | allow = [] 64 | # List of explictly disallowed licenses 65 | # See https://spdx.org/licenses/ for list of possible licenses 66 | # [possible values: any SPDX 3.7 short identifier (+ optional exception)]. 67 | deny = [] 68 | # The lint level for licenses considered copyleft 69 | copyleft = "allow" 70 | # Blanket approval or denial for OSI-approved or FSF Free/Libre licenses 71 | # * both - The license will only be approved if it is both OSI-approved *AND* FSF/Free 72 | # * either - The license will be approved if it is either OSI-approved *OR* FSF/Free 73 | # * osi-only - The license will be approved if is OSI-approved *AND NOT* FSF/Free 74 | # * fsf-only - The license will be approved if is FSF/Free *AND NOT* OSI-approved 75 | # * neither - The license will be denied if is FSF/Free *OR* OSI-approved 76 | allow-osi-fsf-free = "either" 77 | # The confidence threshold for detecting a license from license text. 78 | # The higher the value, the more closely the license text must be to the 79 | # canonical license text of a valid SPDX license file. 80 | # [possible values: any between 0.0 and 1.0]. 81 | confidence-threshold = 0.8 82 | 83 | # This section is considered when running `cargo deny check bans`. 84 | # More documentation about the 'bans' section can be found here: 85 | # https://github.com/EmbarkStudios/cargo-deny#crate-bans-cargo-deny-check-ban 86 | [bans] 87 | # Lint level for when multiple versions of the same crate are detected 88 | multiple-versions = "warn" 89 | # The graph highlighting used when creating dotgraphs for crates 90 | # with multiple versions 91 | # * lowest-version - The path to the lowest versioned duplicate is highlighted 92 | # * simplest-path - The path to the version with the fewest edges is highlighted 93 | # * all - Both lowest-version and simplest-path are used 94 | highlight = "all" 95 | # List of crates that are allowed. Use with care! 96 | allow = [ 97 | #{ name = "ansi_term", version = "=0.11.0" }, 98 | ] 99 | # List of crates to deny 100 | deny = [ 101 | # Each entry the name of a crate and a version range. If version is 102 | # not specified, all versions will be matched. 103 | #{ name = "ansi_term", version = "=0.11.0" }, 104 | ] 105 | # Certain crates/versions that will be skipped when doing duplicate detection. 106 | skip = [ 107 | #{ name = "ansi_term", version = "=0.11.0" }, 108 | ] 109 | # Similarly to `skip` allows you to skip certain crates during duplicate detection, 110 | # unlike skip, it also includes the entire tree of transitive dependencies starting at 111 | # the specified crate, up to a certain depth, which is by default infinite 112 | skip-tree = [ 113 | #{ name = "ansi_term", version = "=0.11.0", depth = 20 }, 114 | ] 115 | 116 | 117 | # This section is considered when running `cargo deny check sources`. 118 | # More documentation about the 'sources' section can be found here: 119 | # https://github.com/EmbarkStudios/cargo-deny#crate-sources-cargo-deny-check-sources 120 | [sources] 121 | # Lint level for what to happen when a crate from a crate registry that is not in the allow list is encountered 122 | unknown-registry = "warn" 123 | # Lint level for what to happen when a crate from a git repository that is not in the allow list is encountered 124 | unknown-git = "warn" 125 | # List of URLs for allowed crate registries, by default https://github.com/rust-lang/crates.io-index is included 126 | #allow-registry = [] 127 | # List of URLs for allowed Git repositories 128 | allow-git = [] 129 | -------------------------------------------------------------------------------- /ethereum-proxy/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ethereum-proxy" 3 | version = "0.1.0" 4 | authors = ["Tomasz Drwięga "] 5 | license = "GPL-3.0-or-later" 6 | edition = "2018" 7 | 8 | [dependencies] 9 | clap = { version = "2.33", features = ["yaml"] } 10 | cli = { path = "../proxy/cli" } 11 | cli-params = { path = "../proxy/cli-params" } 12 | ethereum-proxy-accounts = { path = "./plugins/accounts" } 13 | jsonrpc-core = "16.0" 14 | log = "0.4" 15 | rpc-proxy = { path = "../generic-proxy" } 16 | simple-cache = { path = "../plugins/simple-cache" } 17 | tokio = { version = "1.13", features = ["macros"] } 18 | upstream = { path = "../plugins/upstream" } 19 | -------------------------------------------------------------------------------- /ethereum-proxy/plugins/accounts/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ethereum-proxy-accounts" 3 | version = "0.1.0" 4 | authors = ["Tomasz Drwięga "] 5 | edition = "2018" 6 | license = "GPL-3.0-or-later" 7 | 8 | [dependencies] 9 | cli-params = { path = "../../../proxy/cli-params" } 10 | ethsign = "0.8" 11 | ethereum-transaction = { path = "./transaction" } 12 | jsonrpc-core = "16.0" 13 | log = "0.4" 14 | serde_json = "1.0" 15 | -------------------------------------------------------------------------------- /ethereum-proxy/plugins/accounts/src/config.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-2020 jsonrpc-proxy contributors. 2 | // 3 | // This file is part of jsonrpc-proxy 4 | // (see https://github.com/tomusdrw/jsonrpc-proxy). 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | //! CLI configuration for accounts. 19 | 20 | use cli_params; 21 | use ethsign::{KeyFile, Protected}; 22 | 23 | /// A configuration option to apply. 24 | pub enum Param { 25 | /// Account keyfile. 26 | Account(Option), 27 | /// Password to the keyfile. 28 | Pass(Protected), 29 | } 30 | 31 | /// Returns a list of supported configuration parameters. 32 | pub fn params() -> Vec> { 33 | vec![ 34 | cli_params::Param::new( 35 | "Password to the keyfile", 36 | "account-password", 37 | "A password to unlock the keyfile.", 38 | "", 39 | |pass: String| Ok(Param::Pass(pass.into())), 40 | ), 41 | cli_params::Param::new( 42 | "Account to unlock", 43 | "account-file", 44 | "A path to a JSON wallet with the account.", 45 | "-", 46 | |path: String| { 47 | if path == "-" { 48 | return Ok(Param::Account(None)); 49 | } 50 | 51 | let file = std::fs::File::open(path).map_err(to_str)?; 52 | let key: KeyFile = serde_json::from_reader(file).map_err(to_str)?; 53 | Ok(Param::Account(Some(key))) 54 | }, 55 | ), 56 | ] 57 | } 58 | 59 | fn to_str(e: E) -> String { 60 | format!("{}", e) 61 | } 62 | -------------------------------------------------------------------------------- /ethereum-proxy/plugins/accounts/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-2020 jsonrpc-proxy contributors. 2 | // 3 | // This file is part of jsonrpc-proxy 4 | // (see https://github.com/tomusdrw/jsonrpc-proxy). 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | //! A simplistic RPC cache. 19 | //! 20 | //! Caches the result of calling the RPC method and clears it 21 | //! depending on the cache eviction policy. 22 | 23 | #![warn(missing_docs)] 24 | 25 | use ethereum_transaction::{Bytes, SignTransaction, SignedTransaction, Transaction, U256}; 26 | use ethsign::{KeyFile, Protected, SecretKey}; 27 | use jsonrpc_core::{ 28 | self as rpc, 29 | futures::{ 30 | channel::oneshot, 31 | future::{self, Either}, 32 | Future, 33 | }, 34 | }; 35 | use std::sync::{ 36 | atomic::{self, AtomicUsize}, 37 | Arc, Mutex, 38 | }; 39 | 40 | pub mod config; 41 | 42 | type Upstream = Box Box> + Send + Unpin> + Send + Sync>; 43 | 44 | /// A middleware intercepting transaction requests and signing them locally. 45 | #[derive(Clone)] 46 | pub struct Middleware { 47 | secret: Option, 48 | upstream: Arc, 49 | id: Arc, 50 | lock: Arc>>>, 51 | } 52 | 53 | impl Middleware { 54 | /// Creates a new signing middleware. 55 | /// 56 | /// Intercepts calls to `eth_sendTransaction` and replaces them 57 | /// with `eth_sendRawTransaction`. 58 | pub fn new(upstream: Arc, params: &[config::Param]) -> Self { 59 | let mut key = None; 60 | let mut pass: Protected = "".into(); 61 | 62 | for p in params { 63 | match p { 64 | config::Param::Account(k) => key = k.clone(), 65 | config::Param::Pass(p) => pass = p.clone(), 66 | } 67 | } 68 | 69 | let secret = key.map(|key: KeyFile| { 70 | // TODO [ToDr] Panicking here is crap. 71 | key.to_secret_key(&pass).unwrap() 72 | }); 73 | 74 | Self { 75 | secret, 76 | upstream, 77 | id: Arc::new(AtomicUsize::new(10_000)), 78 | lock: Default::default(), 79 | } 80 | } 81 | } 82 | 83 | const PROOF: &str = "Output always produced for `MethodCall`"; 84 | 85 | impl rpc::Middleware for Middleware { 86 | type Future = rpc::middleware::NoopFuture; 87 | type CallFuture = Either>>; 88 | 89 | fn on_call(&self, mut call: rpc::Call, meta: M, next: F) -> Either 90 | where 91 | F: FnOnce(rpc::Call, M) -> X + Send, 92 | X: Future> + Send + 'static, 93 | { 94 | use rpc::futures::FutureExt; 95 | 96 | let secret = match self.secret.as_ref() { 97 | Some(secret) => secret.clone(), 98 | None => return Either::Right(next(call, meta)), 99 | }; 100 | let address = secret.public().address().to_vec(); 101 | let next_id = || { 102 | let id = self.id.fetch_add(1, atomic::Ordering::SeqCst); 103 | rpc::Id::Num(id as u64) 104 | }; 105 | 106 | log::trace!("Parsing call: {:?}", call); 107 | let (jsonrpc, id) = match call { 108 | rpc::Call::MethodCall(rpc::MethodCall { 109 | ref mut method, 110 | ref jsonrpc, 111 | ref mut id, 112 | .. 113 | }) if method == "eth_sendTransaction" || method == "parity_postTransaction" => { 114 | let orig_id = id.clone(); 115 | *method = "parity_composeTransaction".into(); 116 | *id = next_id(); 117 | (*jsonrpc, orig_id) 118 | } 119 | // prepend signing account to the accounts list. 120 | rpc::Call::MethodCall(rpc::MethodCall { ref mut method, .. }) if method == "eth_accounts" => { 121 | let res = next(call, meta).map(|mut output| { 122 | if let Some(rpc::Output::Success(ref mut s)) = output { 123 | let rpc::Success { ref mut result, .. } = s; 124 | if let rpc::Value::Array(ref mut vec) = result { 125 | vec.insert(0, serde_json::to_value(Bytes(address)).unwrap()); 126 | } 127 | } 128 | log::debug!("Returning accounts: {:?}", output); 129 | output 130 | }); 131 | return Either::Left(Either::Left(Box::pin(res))); 132 | } 133 | _ => return Either::Right(next(call, meta)), 134 | }; 135 | 136 | // Acquire lock to make sure we call it sequentially. 137 | let (tx, previous) = { 138 | let mut lock = self.lock.lock().unwrap(); 139 | let previous = lock.take(); 140 | let (tx, rx) = oneshot::channel(); 141 | *lock = Some(rx); 142 | (tx, previous) 143 | }; 144 | 145 | // Get composed transaction 146 | let chain_id = (self.upstream)(rpc::Call::MethodCall(rpc::MethodCall { 147 | jsonrpc, 148 | id: next_id(), 149 | method: "eth_chainId".into(), 150 | params: rpc::Params::Array(vec![]), 151 | })); 152 | let upstream = self.upstream.clone(); 153 | let upstream2 = upstream.clone(); 154 | let transaction_request = match previous { 155 | Some(prev) => Either::Left(prev.then(move |_| upstream2(call))), 156 | None => Either::Right(upstream2(call)), 157 | }; 158 | 159 | let res = async move { 160 | let request = transaction_request.await; 161 | let chain_id = chain_id.await; 162 | 163 | log::trace!("Got results, parsing composed transaction and chain_id"); 164 | let err = |id, msg: &str| { 165 | Either::Left(future::ready(Some(rpc::Output::Failure(rpc::Failure { 166 | jsonrpc, 167 | id, 168 | error: rpc::Error { 169 | code: 1.into(), 170 | message: msg.into(), 171 | data: None, 172 | }, 173 | })))) 174 | }; 175 | let request = match request.expect(PROOF) { 176 | rpc::Output::Success(rpc::Success { result, .. }) => { 177 | log::debug!("Got composed: {:?}", result); 178 | match serde_json::from_value::(result) { 179 | Ok(tx) => tx, 180 | Err(e) => { 181 | log::error!("Unable to deserialize transaction request: {:?}", e); 182 | return err(id, "Unable to construct transaction"); 183 | } 184 | } 185 | } 186 | o => return Either::Left(future::ready(Some(o.into()))), 187 | }; 188 | let chain_id = match chain_id.expect(PROOF) { 189 | rpc::Output::Success(rpc::Success { result, .. }) => { 190 | log::debug!("Got chain_id: {:?}", result); 191 | match serde_json::from_value::(result) { 192 | Ok(id) => id.as_u64(), 193 | Err(e) => { 194 | log::error!("Unable to deserialize transaction request: {:?}", e); 195 | return err(id, "Unable to construct transaction"); 196 | } 197 | } 198 | } 199 | o => return Either::Left(future::ready(Some(o.into()))), 200 | }; 201 | // Verify from 202 | let public = secret.public(); 203 | let address = public.address(); 204 | let from = request.from; 205 | if from.as_bytes() != address { 206 | log::error!("Expected to send from {:?}, but only support {:?}", from, address); 207 | return err(id, "Invalid `from` address"); 208 | } 209 | // Calculate unsigned hash 210 | let hash = SignTransaction { 211 | transaction: std::borrow::Cow::Borrowed(&request), 212 | chain_id, 213 | } 214 | .hash(); 215 | // Sign replay-protected hash. 216 | let signature = secret.sign(&hash).unwrap(); 217 | // Construct signed RLP 218 | let signed = SignedTransaction::new( 219 | std::borrow::Cow::Owned(request), 220 | chain_id, 221 | signature.v, 222 | signature.r, 223 | signature.s, 224 | ); 225 | let rlp = Bytes(signed.to_rlp()); 226 | 227 | Either::Right((upstream)(rpc::Call::MethodCall(rpc::MethodCall { 228 | jsonrpc, 229 | id, 230 | method: "eth_sendRawTransaction".into(), 231 | params: rpc::Params::Array(vec![serde_json::to_value(rlp).unwrap()]), 232 | }))) 233 | } 234 | .then(move |x| { 235 | let _ = tx.send(()); 236 | x 237 | }); 238 | Either::Left(Either::Left(Box::pin(res))) 239 | } 240 | } 241 | -------------------------------------------------------------------------------- /ethereum-proxy/plugins/accounts/transaction/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ethereum-transaction" 3 | description = "A set of primitives to compose ethereum transactions." 4 | repository = "https://github.com/tomusdrw/jsonrpc-proxy" 5 | version = "0.6.0" 6 | authors = ["Tomasz Drwięga "] 7 | edition = "2018" 8 | license = "GPL-3.0-or-later" 9 | 10 | [dependencies] 11 | ethereum-types = "0.12" 12 | impl-serde = { version = "0.3" } 13 | log = "0.4" 14 | rlp = "0.5" 15 | serde = { version = "1.0", features = ["derive"] } 16 | tiny-keccak = "2.0" 17 | -------------------------------------------------------------------------------- /ethereum-proxy/plugins/accounts/transaction/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-2020 jsonrpc-proxy contributors. 2 | // 3 | // This file is part of jsonrpc-proxy 4 | // (see https://github.com/tomusdrw/jsonrpc-proxy). 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | //! A set of primitives to construct ethereum transactions. 19 | 20 | use impl_serde::serialize as bytes; 21 | use rlp::RlpStream; 22 | use serde::{Deserialize, Serialize}; 23 | use std::borrow::Cow; 24 | use tiny_keccak::{Hasher, Keccak}; 25 | 26 | pub use ethereum_types::{Address, U256}; 27 | 28 | /// Hex-serialized shim for `Vec`. 29 | #[derive(Serialize, Deserialize, Debug, Hash, PartialOrd, Ord, PartialEq, Eq, Clone, Default)] 30 | pub struct Bytes(#[serde(with = "bytes")] pub Vec); 31 | impl From> for Bytes { 32 | fn from(s: Vec) -> Self { 33 | Bytes(s) 34 | } 35 | } 36 | 37 | impl std::ops::Deref for Bytes { 38 | type Target = [u8]; 39 | fn deref(&self) -> &[u8] { 40 | &self.0[..] 41 | } 42 | } 43 | 44 | #[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Hash, Debug, Default)] 45 | #[serde(rename_all = "camelCase")] 46 | pub struct Transaction { 47 | pub from: Address, 48 | pub to: Option
, 49 | pub nonce: U256, 50 | pub gas: U256, 51 | pub gas_price: U256, 52 | pub value: U256, 53 | pub data: Bytes, 54 | } 55 | 56 | #[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Hash, Debug)] 57 | #[serde(rename_all = "camelCase")] 58 | pub struct SignTransaction<'a> { 59 | pub transaction: Cow<'a, Transaction>, 60 | pub chain_id: u64, 61 | } 62 | 63 | impl<'a> SignTransaction<'a> { 64 | pub fn owned(tx: Transaction, chain_id: u64) -> Self { 65 | Self { 66 | transaction: Cow::Owned(tx), 67 | chain_id, 68 | } 69 | } 70 | 71 | pub fn hash(&self) -> [u8; 32] { 72 | SignedTransaction { 73 | transaction: Cow::Borrowed(&*self.transaction), 74 | v: self.chain_id, 75 | r: 0.into(), 76 | s: 0.into(), 77 | } 78 | .hash() 79 | } 80 | } 81 | 82 | #[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Hash, Debug)] 83 | #[serde(rename_all = "camelCase")] 84 | pub struct SignedTransaction<'a> { 85 | pub transaction: Cow<'a, Transaction>, 86 | pub v: u64, 87 | pub r: U256, 88 | pub s: U256, 89 | } 90 | 91 | impl<'a> rlp::Decodable for SignedTransaction<'a> { 92 | fn decode(d: &rlp::Rlp) -> Result { 93 | if d.item_count()? != 9 { 94 | return Err(rlp::DecoderError::RlpIncorrectListLen); 95 | } 96 | 97 | Ok(SignedTransaction { 98 | transaction: Cow::Owned(Transaction { 99 | nonce: d.val_at(0).map_err(|e| debug("nonce", e))?, 100 | gas_price: d.val_at(1).map_err(|e| debug("gas_price", e))?, 101 | gas: d.val_at(2).map_err(|e| debug("gas", e))?, 102 | to: { 103 | let to = d.at(3).map_err(|e| debug("to", e))?; 104 | if to.is_empty() { 105 | if to.is_data() { 106 | None 107 | } else { 108 | return Err(rlp::DecoderError::RlpExpectedToBeData); 109 | } 110 | } else { 111 | Some(to.as_val().map_err(|e| debug("to", e))?) 112 | } 113 | }, 114 | from: Default::default(), 115 | value: d.val_at(4).map_err(|e| debug("value", e))?, 116 | data: d.val_at::>(5).map_err(|e| debug("data", e))?.into(), 117 | }), 118 | v: d.val_at(6).map_err(|e| debug("v", e))?, 119 | r: d.val_at(7).map_err(|e| debug("r", e))?, 120 | s: d.val_at(8).map_err(|e| debug("s", e))?, 121 | }) 122 | } 123 | } 124 | 125 | fn debug(s: &str, err: rlp::DecoderError) -> rlp::DecoderError { 126 | log::error!("Error decoding field: {}: {:?}", s, err); 127 | err 128 | } 129 | 130 | impl<'a> rlp::Encodable for SignedTransaction<'a> { 131 | fn rlp_append(&self, s: &mut RlpStream) { 132 | s.begin_list(9); 133 | s.append(&self.transaction.nonce); 134 | s.append(&self.transaction.gas_price); 135 | s.append(&self.transaction.gas); 136 | match self.transaction.to.as_ref() { 137 | None => s.append(&""), 138 | Some(addr) => s.append(addr), 139 | }; 140 | s.append(&self.transaction.value); 141 | s.append(&self.transaction.data.0); 142 | s.append(&self.v); 143 | s.append(&self.r); 144 | s.append(&self.s); 145 | } 146 | } 147 | 148 | impl<'a> SignedTransaction<'a> { 149 | pub fn new(transaction: Cow<'a, Transaction>, chain_id: u64, v: u8, r: [u8; 32], s: [u8; 32]) -> Self { 150 | let v = replay_protection::add(v, chain_id); 151 | let r = U256::from_big_endian(&r); 152 | let s = U256::from_big_endian(&s); 153 | 154 | Self { transaction, v, r, s } 155 | } 156 | 157 | pub fn standard_v(&self) -> u8 { 158 | match self.v { 159 | v if v == 27 => 0, 160 | v if v == 28 => 1, 161 | v if v >= 35 => ((v - 1) % 2) as u8, 162 | _ => 4, 163 | } 164 | } 165 | 166 | pub fn chain_id(&self) -> Option { 167 | replay_protection::chain_id(self.v) 168 | } 169 | 170 | pub fn hash(&self) -> [u8; 32] { 171 | self.with_rlp(|s| { 172 | let mut output = [0_u8; 32]; 173 | let mut k = Keccak::v256(); 174 | k.update(s.as_raw()); 175 | k.finalize(&mut output); 176 | output 177 | }) 178 | } 179 | 180 | pub fn bare_hash(&self) -> [u8; 32] { 181 | let chain_id = self.chain_id().unwrap_or_default(); 182 | 183 | SignTransaction { 184 | transaction: std::borrow::Cow::Borrowed(&self.transaction), 185 | chain_id, 186 | } 187 | .hash() 188 | } 189 | 190 | pub fn to_rlp(&self) -> Vec { 191 | self.with_rlp(|s| s.out().to_vec()) 192 | } 193 | 194 | fn with_rlp(&self, f: impl FnOnce(RlpStream) -> R) -> R { 195 | let mut s = RlpStream::new(); 196 | rlp::Encodable::rlp_append(self, &mut s); 197 | f(s) 198 | } 199 | } 200 | 201 | mod replay_protection { 202 | /// Adds chain id into v 203 | pub fn add(v: u8, chain_id: u64) -> u64 { 204 | v as u64 + 35 + chain_id * 2 205 | } 206 | 207 | /// Extracts chain_id from v 208 | pub fn chain_id(v: u64) -> Option { 209 | match v { 210 | v if v >= 35 => Some((v - 35) / 2), 211 | _ => None, 212 | } 213 | } 214 | } 215 | 216 | #[cfg(test)] 217 | mod tests { 218 | use super::*; 219 | 220 | #[test] 221 | fn transaction_rlp_round_trip() { 222 | let transaction = Transaction { 223 | from: Default::default(), 224 | to: None, 225 | nonce: 5.into(), 226 | gas_price: 15.into(), 227 | gas: 69.into(), 228 | data: Default::default(), 229 | value: 1_000.into(), 230 | }; 231 | let t = SignedTransaction::new(Cow::Owned(transaction), 105, 0, [1; 32], [1; 32]); 232 | 233 | let encoded = rlp::encode(&t); 234 | let decoded: SignedTransaction = rlp::decode(&encoded).unwrap(); 235 | 236 | assert_eq!(t, decoded); 237 | } 238 | 239 | #[test] 240 | fn transaction_rlp_round_trip2() { 241 | let transaction = Transaction { 242 | from: Default::default(), 243 | to: Some(ethereum_types::H160::repeat_byte(5)), 244 | nonce: 5.into(), 245 | gas_price: 15.into(), 246 | gas: 69.into(), 247 | data: Default::default(), 248 | value: 1_000.into(), 249 | }; 250 | let t = SignedTransaction::new(Cow::Owned(transaction), 105, 0, [1; 32], [1; 32]); 251 | 252 | let encoded = rlp::encode(&t); 253 | let decoded: SignedTransaction = rlp::decode(&encoded).unwrap(); 254 | 255 | assert_eq!(t, decoded); 256 | } 257 | } 258 | -------------------------------------------------------------------------------- /ethereum-proxy/src/cli.yml: -------------------------------------------------------------------------------- 1 | ## 2 | ## Copyright (c) 2018-2020 jsonrpc-proxy contributors. 3 | ## 4 | ## This file is part of jsonrpc-proxy 5 | ## (see https://github.com/tomusdrw/jsonrpc-proxy). 6 | ## 7 | ## This program is free software: you can redistribute it and/or modify 8 | ## it under the terms of the GNU General Public License as published by 9 | ## the Free Software Foundation, either version 3 of the License, or 10 | ## (at your option) any later version. 11 | ## 12 | ## This program is distributed in the hope that it will be useful, 13 | ## but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ## GNU General Public License for more details. 16 | ## 17 | ## You should have received a copy of the GNU General Public License 18 | ## along with this program. If not, see . 19 | ## 20 | name: ethereum-proxy 21 | version: "0.1" 22 | about: Ethereum JSON-RPC proxy. 23 | author: Parity Technologies Ltd 24 | 25 | -------------------------------------------------------------------------------- /ethereum-proxy/src/main.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-2020 jsonrpc-proxy contributors. 2 | // 3 | // This file is part of jsonrpc-proxy 4 | // (see https://github.com/tomusdrw/jsonrpc-proxy). 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | //! JSON-RPC proxy suitable for Ethereum nodes. 19 | //! 20 | //! The proxy contains a pre-configured list of cacheable methods and upstream subscriptions. 21 | 22 | #![warn(missing_docs)] 23 | 24 | use ethereum_proxy_accounts as accounts; 25 | 26 | #[tokio::main] 27 | async fn main() { 28 | let yml = clap::load_yaml!("./cli.yml"); 29 | let app = clap::App::from_yaml(yml).set_term_width(80); 30 | 31 | generic_proxy::run_app( 32 | app, 33 | vec![ 34 | // eth 35 | cache("eth_protocolVersion"), 36 | cache("eth_syncing"), 37 | cache("eth_mining"), 38 | cache("eth_gasPrice"), 39 | cache("eth_blockNumber"), 40 | cache("eth_getBalance"), 41 | cache("eth_getStorageAt"), 42 | cache("eth_getBlockByHash"), 43 | cache("eth_getBlockByNumber"), 44 | cache("eth_getTransactionCount"), 45 | cache("eth_getBlockTransactionCountByHash"), 46 | cache("eth_getBlockTransactionCountByNumber"), 47 | cache("eth_getUncleCountByBlockHash"), 48 | cache("eth_getUncleCountByBlockNumber"), 49 | cache("eth_getCode"), 50 | cache("eth_call"), 51 | cache("eth_estimateGas"), 52 | cache("eth_getTransactionByHash"), 53 | cache("eth_getTransactionByBlockHashAndIndex"), 54 | cache("eth_getTransactionByBlockNumberAndIndex"), 55 | cache("eth_getTransactionReceipt"), 56 | cache("eth_getUncleByBlockHashAndIndex"), 57 | cache("eth_getUncleByBlockNumberAndIndex"), 58 | cache("eth_getCompilers"), 59 | cache("eth_getLogs"), 60 | // net 61 | cache("net_version"), 62 | cache("net_peerCount"), 63 | cache("net_listening"), 64 | // parity 65 | cache("parity_transactionsLimit"), 66 | cache("parity_extraData"), 67 | cache("parity_gasFloorTarget"), 68 | cache("parity_gasCeilTarget"), 69 | cache("parity_minGasPrice"), 70 | cache("parity_netChain"), 71 | cache("parity_netPort"), 72 | cache("parity_rpcSettings"), 73 | cache("parity_nodeName"), 74 | cache("parity_defaultExtraData"), 75 | cache("parity_gasPriceHistogram"), 76 | cache("parity_phraseToAddress"), 77 | cache("parity_registryAddress"), 78 | cache("parity_wsUrl"), 79 | cache("parity_chainId"), 80 | cache("parity_chain"), 81 | cache("parity_enode"), 82 | cache("parity_versionInfo"), 83 | cache("parity_releaseInfo"), 84 | cache("parity_chainStatus"), 85 | cache("parity_getBlockHeaderByNumber"), 86 | cache("parity_cidV0"), 87 | // web3 88 | cache("web3_clientVersion"), 89 | cache("web3_sha3"), 90 | ], 91 | vec![ 92 | upstream::Subscription { 93 | subscribe: "eth_subscribe".into(), 94 | unsubscribe: "eth_unsubscribe".into(), 95 | name: "eth_subscription".into(), 96 | }, 97 | upstream::Subscription { 98 | subscribe: "parity_subscribe".into(), 99 | unsubscribe: "parity_unsubscribe".into(), 100 | name: "parity_subscription".into(), 101 | }, 102 | upstream::Subscription { 103 | subscribe: "signer_subscribePending".into(), 104 | unsubscribe: "signer_unsubscribePending".into(), 105 | name: "signer_pending".into(), 106 | }, 107 | ], 108 | Extension::default(), 109 | ) 110 | } 111 | 112 | fn cache(name: &str) -> simple_cache::Method { 113 | simple_cache::Method::new( 114 | name, 115 | simple_cache::CacheEviction::Time(::std::time::Duration::from_secs(3)), 116 | ) 117 | } 118 | 119 | #[derive(Default)] 120 | struct Extension { 121 | params: Vec>, 122 | } 123 | 124 | impl generic_proxy::Extension for Extension { 125 | type Middleware = accounts::Middleware; 126 | 127 | fn configure_app<'a, 'b>(&'a mut self, app: clap::App<'a, 'b>) -> clap::App<'a, 'b> { 128 | self.params = accounts::config::params(); 129 | cli::configure_app(app, &self.params) 130 | } 131 | 132 | fn parse_matches(matches: &clap::ArgMatches, upstream: impl upstream::Transport) -> Self::Middleware { 133 | use jsonrpc_core::futures::{FutureExt, TryFutureExt}; 134 | let all_params = accounts::config::params(); 135 | 136 | let params = cli::parse_matches(matches, &all_params).ok().unwrap_or_else(Vec::new); 137 | let call = move |call: jsonrpc_core::Call| { 138 | Box::new( 139 | upstream 140 | .send(call) 141 | .map_err(|e| log::error!("Upstream error: {:?}", e)) 142 | .map(|res| res.unwrap_or(None)), 143 | ) as _ 144 | }; 145 | accounts::Middleware::new(std::sync::Arc::new(Box::new(call)), ¶ms) 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /examples/cache.json: -------------------------------------------------------------------------------- 1 | { 2 | "enabled": true, 3 | "methods": [ 4 | { 5 | "name": "chain_getBlock", 6 | "eviction": { 7 | "time": { 8 | "secs": 50000, 9 | "nanos": 0 10 | } 11 | } 12 | } 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /examples/permissions.json: -------------------------------------------------------------------------------- 1 | { 2 | "policy": "deny", 3 | "methods": [ 4 | { 5 | "name": "state_getStorage", 6 | "policy": "allow" 7 | } 8 | ] 9 | } 10 | -------------------------------------------------------------------------------- /examples/upstream.json: -------------------------------------------------------------------------------- 1 | { 2 | "pubsubMethods": [{ 3 | "subscribe": "state_subscribeStorage", 4 | "unsubscribe": "state_unsubscibeStorage", 5 | "name": "state_storage" 6 | }] 7 | } 8 | -------------------------------------------------------------------------------- /generic-proxy/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rpc-proxy" 3 | version = "0.1.0" 4 | authors = ["Tomasz Drwięga "] 5 | license = "GPL-3.0-or-later" 6 | edition = "2018" 7 | 8 | [dependencies] 9 | clap = { version = "2.33", features = ["yaml"] } 10 | cli = { path = "../proxy/cli" } 11 | env_logger = "0.9" 12 | jsonrpc-core = "16.0" 13 | jsonrpc-pubsub = "18.0" 14 | tokio = { version = "1.13", features = ["full"] } 15 | permissioning = { path = "../plugins/permissioning" } 16 | simple-cache = { path = "../plugins/simple-cache" } 17 | transports = { path = "../proxy/transports" } 18 | upstream = { path = "../plugins/upstream" } 19 | ws-upstream = { path = "../plugins/ws-upstream" } 20 | 21 | [[bin]] 22 | name = "rpc-proxy" 23 | path = "bin/rpc-proxy.rs" 24 | 25 | [lib] 26 | name = "generic_proxy" 27 | path = "src/lib.rs" 28 | -------------------------------------------------------------------------------- /generic-proxy/bin/cli.yml: -------------------------------------------------------------------------------- 1 | ## 2 | ## Copyright (c) 2018-2020 jsonrpc-proxy contributors. 3 | ## 4 | ## This file is part of jsonrpc-proxy 5 | ## (see https://github.com/tomusdrw/jsonrpc-proxy). 6 | ## 7 | ## This program is free software: you can redistribute it and/or modify 8 | ## it under the terms of the GNU General Public License as published by 9 | ## the Free Software Foundation, either version 3 of the License, or 10 | ## (at your option) any later version. 11 | ## 12 | ## This program is distributed in the hope that it will be useful, 13 | ## but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ## GNU General Public License for more details. 16 | ## 17 | ## You should have received a copy of the GNU General Public License 18 | ## along with this program. If not, see . 19 | ## 20 | name: rpc-proxy 21 | version: "0.1" 22 | about: Generic RPC proxy, featuring caching and load balancing. 23 | author: Parity Technologies Ltd 24 | 25 | # settings: 26 | # - ArgRequiredElseHelp 27 | -------------------------------------------------------------------------------- /generic-proxy/bin/rpc-proxy.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-2020 jsonrpc-proxy contributors. 2 | // 3 | // This file is part of jsonrpc-proxy 4 | // (see https://github.com/tomusdrw/jsonrpc-proxy). 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | //! Generic RPC proxy with default set of plugins. 19 | //! 20 | //! - Allows configuration to be passed via CLI options or a yaml file. 21 | //! - Supports simple time-based cache 22 | 23 | #![warn(missing_docs)] 24 | 25 | #[tokio::main] 26 | async fn main() { 27 | let yml = clap::load_yaml!("./cli.yml"); 28 | let app = clap::App::from_yaml(yml).set_term_width(80); 29 | 30 | generic_proxy::run_app(app, vec![], vec![], ()) 31 | } 32 | -------------------------------------------------------------------------------- /generic-proxy/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-2020 jsonrpc-proxy contributors. 2 | // 3 | // This file is part of jsonrpc-proxy 4 | // (see https://github.com/tomusdrw/jsonrpc-proxy). 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | //! Generic RPC proxy with default set of plugins. 19 | //! 20 | //! - Allows configuration to be passed via CLI options or a yaml file. 21 | //! - Supports simple time-based cache 22 | 23 | #![warn(missing_docs)] 24 | 25 | use jsonrpc_core as rpc; 26 | 27 | use clap::App; 28 | use std::sync::Arc; 29 | 30 | /// A generic proxy metadata. 31 | pub type Metadata = Option>; 32 | 33 | type Middleware = ( 34 | permissioning::Middleware, 35 | simple_cache::Middleware, 36 | E, 37 | upstream::Middleware, 38 | ); 39 | 40 | fn handler>( 41 | transport: T, 42 | extra: E, 43 | cache_params: &[simple_cache::config::Param], 44 | permissioning_params: &[permissioning::config::Param], 45 | upstream_params: &[upstream::config::Param], 46 | ) -> rpc::MetaIoHandler> { 47 | rpc::MetaIoHandler::with_middleware(( 48 | permissioning::Middleware::new(permissioning_params), 49 | simple_cache::Middleware::new(cache_params), 50 | extra, 51 | upstream::Middleware::new(transport, upstream_params), 52 | )) 53 | } 54 | 55 | /// TODO [ToDr] The whole thing is really shit. 56 | pub trait Extension { 57 | /// Middleware type. 58 | type Middleware: rpc::Middleware + Clone; 59 | 60 | /// Configure clap application with parameters. 61 | fn configure_app<'a, 'b>(&'a mut self, app: clap::App<'a, 'b>) -> clap::App<'a, 'b>; 62 | 63 | /// Parse matches and create the middleware. 64 | fn parse_matches(matches: &clap::ArgMatches, upstream: impl upstream::Transport) -> Self::Middleware; 65 | } 66 | 67 | impl Extension for () { 68 | type Middleware = rpc::NoopMiddleware; 69 | 70 | fn configure_app<'a, 'b>(&'a mut self, app: clap::App<'a, 'b>) -> clap::App<'a, 'b> { 71 | app 72 | } 73 | 74 | fn parse_matches(_matches: &clap::ArgMatches, _upstream: impl upstream::Transport) -> Self::Middleware { 75 | Default::default() 76 | } 77 | } 78 | 79 | /// Run app with additional cache methods and upstream subscriptions. 80 | pub fn run_app( 81 | app: App, 82 | simple_cache_methods: Vec, 83 | upstream_subscriptions: Vec, 84 | mut extension: E, 85 | ) where 86 | >::Future: Unpin, 87 | >::CallFuture: Unpin, 88 | { 89 | env_logger::init(); 90 | let args = ::std::env::args_os(); 91 | 92 | let ws_params = transports::ws::params(); 93 | let app = cli::configure_app(app, &ws_params); 94 | let http_params = transports::http::params(); 95 | let app = cli::configure_app(app, &http_params); 96 | let tcp_params = transports::tcp::params(); 97 | let app = cli::configure_app(app, &tcp_params); 98 | let ipc_params = transports::ipc::params(); 99 | let app = cli::configure_app(app, &ipc_params); 100 | 101 | let upstream_params = upstream::config::params(); 102 | let app = cli::configure_app(app, &upstream_params); 103 | let ws_upstream_params = ws_upstream::config::params(); 104 | let app = cli::configure_app(app, &ws_upstream_params); 105 | 106 | let cache_params = simple_cache::config::params(); 107 | let app = cli::configure_app(app, &cache_params); 108 | 109 | let permissioning_params = permissioning::config::params(); 110 | let app = cli::configure_app(app, &permissioning_params); 111 | 112 | let app = extension.configure_app(app); 113 | 114 | // Parse matches 115 | let matches = app.get_matches_from(args); 116 | let ws_params = cli::parse_matches(&matches, &ws_params).unwrap(); 117 | let http_params = cli::parse_matches(&matches, &http_params).unwrap(); 118 | let tcp_params = cli::parse_matches(&matches, &tcp_params).unwrap(); 119 | let ipc_params = cli::parse_matches(&matches, &ipc_params).unwrap(); 120 | let mut upstream_params = cli::parse_matches(&matches, &upstream_params).unwrap(); 121 | upstream::config::add_subscriptions(&mut upstream_params, upstream_subscriptions); 122 | let ws_upstream_params = cli::parse_matches(&matches, &ws_upstream_params).unwrap(); 123 | let mut cache_params = cli::parse_matches(&matches, &cache_params).unwrap(); 124 | simple_cache::config::add_methods(&mut cache_params, simple_cache_methods); 125 | let permissioning_params = cli::parse_matches(&matches, &permissioning_params).unwrap(); 126 | 127 | // Actually run the damn thing. 128 | let transport = ws_upstream::WebSocket::new(ws_upstream_params, |fut| std::mem::drop(tokio::spawn(fut))).unwrap(); 129 | 130 | let extra = E::parse_matches(&matches, transport.clone()); 131 | let h = || { 132 | handler( 133 | transport.clone(), 134 | extra.clone(), 135 | &cache_params, 136 | &permissioning_params, 137 | &upstream_params, 138 | ) 139 | }; 140 | let server1 = transports::ws::start(ws_params, h()).unwrap(); 141 | let _server2 = transports::http::start(http_params, h()).unwrap(); 142 | let _server3 = transports::tcp::start(tcp_params, h()).unwrap(); 143 | let _server4 = transports::ipc::start(ipc_params, h()).unwrap(); 144 | 145 | server1.wait().unwrap(); 146 | } 147 | -------------------------------------------------------------------------------- /overview.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
7 |
8 | PROXY 9 |
10 |
11 |
12 | 13 | PROXY 14 | 15 |
16 | 17 | 18 | 19 |
20 |
21 | UPSTREAM 22 |
23 |
24 |
25 | 26 | UPSTREAM 27 | 28 |
29 | 30 | 31 | 32 |
33 |
34 | WS 35 |
36 |
37 |
38 | 39 | WS 40 | 41 |
42 | 43 | 44 | 45 | 46 | 47 |
48 |
49 | WS 50 |
51 |
52 |
53 |
54 | 55 | WS<br> 56 | 57 |
58 | 59 | 60 | 61 |
62 |
63 | HTTP 64 |
65 |
66 |
67 | 68 | HTTP 69 | 70 |
71 | 72 | 73 | 74 |
75 |
76 | IPC 77 |
78 |
79 |
80 | 81 | IPC 82 | 83 |
84 | 85 | 86 | 87 |
88 |
89 | TCP 90 |
91 |
92 |
93 | 94 | TCP 95 | 96 |
97 | 98 | 99 | 100 |
101 |
102 | Permissioning 103 |
104 | Middleware 105 |
106 |
107 |
108 |
109 | 110 | Permissioning<br>Middleware<br> 111 | 112 |
113 | 114 | 115 | 116 | 117 |
118 |
119 | REQUEST 120 |
121 |
122 |
123 | 124 | REQUEST 125 | 126 |
127 | 128 | 129 | 130 | 131 | 132 |
133 |
134 | Cache Middleware 135 |
136 |
137 |
138 |
139 | 140 | Cache Middleware<br> 141 | 142 |
143 | 144 | 145 | 146 | 147 | 148 |
149 |
150 | Custom 151 |
152 | Middleware 153 |
154 |
155 |
156 |
157 | 158 | Custom<br>Middleware<br> 159 | 160 |
161 | 162 | 163 | 164 | 165 |
166 |
167 | -------------------------------------------------------------------------------- /plugins/permissioning/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "permissioning" 3 | version = "0.1.0" 4 | authors = ["Tomasz Drwięga "] 5 | license = "GPL-3.0-or-later" 6 | 7 | [dependencies] 8 | cli-params = { path = "../../proxy/cli-params" } 9 | fnv = "1.0" 10 | jsonrpc-core = "16.0" 11 | log = "0.4" 12 | serde = "1.0" 13 | serde_json = "1.0" 14 | serde_derive = "1.0" 15 | -------------------------------------------------------------------------------- /plugins/permissioning/src/config.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-2020 jsonrpc-proxy contributors. 2 | // 3 | // This file is part of jsonrpc-proxy 4 | // (see https://github.com/tomusdrw/jsonrpc-proxy). 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | //! CLI configuration for permissioning. 19 | 20 | use cli_params; 21 | use serde_json; 22 | use std::{fs, io}; 23 | use Permissioning; 24 | 25 | /// A configuration option to apply. 26 | pub enum Param { 27 | /// Permissioning configuration 28 | Config(Permissioning), 29 | } 30 | 31 | /// Returns a list of supported configuration parameters. 32 | pub fn params() -> Vec> { 33 | vec![ 34 | cli_params::Param::new( 35 | "Permissioning", 36 | "permissioning-config", 37 | "A path to a JSON file containing a list of methods that should be permissioned. See examples for the file schema.", 38 | "-", 39 | |path: String| { 40 | if &path == "-" { 41 | return Ok(Param::Config(Default::default())) 42 | } 43 | 44 | let file = fs::File::open(&path).map_err(|e| format!("Can't open permissioning file at {}: {:?}", path, e))?; 45 | let buf_file = io::BufReader::new(file); 46 | let config: Permissioning = serde_json::from_reader(buf_file).map_err(|e| format!("Invalid JSON at {}: {:?}", path, e))?; 47 | Ok(Param::Config(config)) 48 | } 49 | ) 50 | ] 51 | } 52 | -------------------------------------------------------------------------------- /plugins/permissioning/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-2020 jsonrpc-proxy contributors. 2 | // 3 | // This file is part of jsonrpc-proxy 4 | // (see https://github.com/tomusdrw/jsonrpc-proxy). 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | //! A simple permissioning system. 19 | //! 20 | //! Allows you to turn off particular methods. 21 | 22 | #![warn(missing_docs)] 23 | #![warn(unused_extern_crates)] 24 | 25 | extern crate cli_params; 26 | extern crate fnv; 27 | extern crate jsonrpc_core as rpc; 28 | extern crate serde_json; 29 | 30 | #[macro_use] 31 | extern crate serde_derive; 32 | 33 | use fnv::FnvHashMap; 34 | use rpc::futures::{future::Either, Future}; 35 | 36 | pub mod config; 37 | 38 | /// Describes method access. 39 | #[derive(Clone, Debug, Deserialize)] 40 | #[serde(rename_all = "camelCase")] 41 | pub enum Access { 42 | /// Allow all access to that method 43 | Allow, 44 | /// Deny any access to that method 45 | Deny, 46 | // TODO [ToDr] Add other policies like: 47 | // 1. Require authorization header (fixed) 48 | // 2. Require HTTP basic credentials 49 | // 3. Allow only over specific transport 50 | // (All will require extending the metadata to contain this info) 51 | } 52 | 53 | /// Represents a managed method. 54 | /// 55 | /// Should know how to compute a hash that is used to compare requests. 56 | #[derive(Clone, Debug, Deserialize)] 57 | pub struct Method { 58 | /// Method name 59 | pub name: String, 60 | /// Method access details 61 | pub policy: Access, 62 | } 63 | 64 | /// Represents permissioning configuration 65 | #[derive(Clone, Debug, Deserialize)] 66 | pub struct Permissioning { 67 | /// Default (base) policy 68 | pub policy: Access, 69 | /// Method overrides 70 | pub methods: Vec, 71 | } 72 | 73 | impl Default for Permissioning { 74 | fn default() -> Self { 75 | Permissioning { 76 | policy: Access::Allow, 77 | methods: Default::default(), 78 | } 79 | } 80 | } 81 | 82 | /// Simple static permissioning scheme 83 | #[derive(Debug)] 84 | pub struct Middleware { 85 | base: Access, 86 | permissioned: FnvHashMap, 87 | } 88 | 89 | impl Middleware { 90 | /// Creates new permissioning middleware 91 | pub fn new(params: &[config::Param]) -> Self { 92 | let mut config = Permissioning::default(); 93 | for p in params { 94 | match p { 95 | config::Param::Config(ref m) => config = m.clone(), 96 | } 97 | } 98 | 99 | Middleware { 100 | base: config.policy, 101 | permissioned: config.methods.into_iter().map(|x| (x.name.clone(), x)).collect(), 102 | } 103 | } 104 | } 105 | 106 | impl rpc::Middleware for Middleware { 107 | type Future = rpc::middleware::NoopFuture; 108 | type CallFuture = rpc::futures::future::Ready>; 109 | 110 | fn on_call(&self, call: rpc::Call, meta: M, next: F) -> Either 111 | where 112 | F: Fn(rpc::Call, M) -> X + Send, 113 | X: Future> + Send + 'static, 114 | { 115 | enum Action { 116 | Next, 117 | Reject, 118 | } 119 | 120 | let to_action = |access: &Access| match *access { 121 | Access::Allow => Action::Next, 122 | Access::Deny => Action::Reject, 123 | }; 124 | 125 | let action = { 126 | match call { 127 | rpc::Call::MethodCall(rpc::MethodCall { ref method, .. }) => { 128 | if let Some(m) = self.permissioned.get(method) { 129 | to_action(&m.policy) 130 | } else { 131 | to_action(&self.base) 132 | } 133 | } 134 | _ => to_action(&self.base), 135 | } 136 | }; 137 | 138 | match action { 139 | Action::Next => Either::Right(next(call, meta)), 140 | Action::Reject => { 141 | let (version, id) = get_call_details(call); 142 | 143 | Either::Left(rpc::futures::future::ready(id.map(|id| { 144 | rpc::Output::Failure(rpc::Failure { 145 | jsonrpc: version, 146 | error: rpc::Error { 147 | code: rpc::ErrorCode::ServerError(-1), 148 | message: "You are not allowed to call that method.".into(), 149 | data: None, 150 | }, 151 | id, 152 | }) 153 | }))) 154 | } 155 | } 156 | } 157 | } 158 | 159 | fn get_call_details(call: rpc::Call) -> (Option, Option) { 160 | match call { 161 | rpc::Call::MethodCall(rpc::MethodCall { jsonrpc, id, .. }) => (jsonrpc, Some(id)), 162 | rpc::Call::Notification(rpc::Notification { jsonrpc, .. }) => (jsonrpc, None), 163 | rpc::Call::Invalid { id, .. } => (None, Some(id)), 164 | } 165 | } 166 | 167 | #[cfg(test)] 168 | mod tests { 169 | use super::*; 170 | use rpc::Middleware as MiddlewareTrait; 171 | use std::sync::{atomic, Arc}; 172 | 173 | trait FutExt: std::future::Future { 174 | fn wait(self) -> Self::Output; 175 | } 176 | 177 | impl FutExt for F 178 | where 179 | F: std::future::Future, 180 | { 181 | fn wait(self) -> Self::Output { 182 | rpc::futures::executor::block_on(self) 183 | } 184 | } 185 | 186 | fn callback() -> ( 187 | impl Fn(rpc::Call, ()) -> rpc::futures::future::Ready>, 188 | Arc, 189 | ) { 190 | let called = Arc::new(atomic::AtomicBool::new(false)); 191 | let called2 = called.clone(); 192 | let next = move |_, _| { 193 | called2.store(true, atomic::Ordering::SeqCst); 194 | rpc::futures::future::ready(None) 195 | }; 196 | 197 | (next, called) 198 | } 199 | 200 | fn method_call(name: &str) -> rpc::Call { 201 | rpc::Call::MethodCall(rpc::MethodCall { 202 | id: rpc::Id::Num(1), 203 | jsonrpc: Some(rpc::Version::V2), 204 | method: name.into(), 205 | params: rpc::Params::Array(vec![]), 206 | }) 207 | } 208 | 209 | fn middleware(config: Permissioning) -> Middleware { 210 | Middleware::new(&[config::Param::Config(config)]) 211 | } 212 | 213 | fn not_allowed() -> Option { 214 | Some(rpc::Output::Failure(rpc::Failure { 215 | id: rpc::Id::Num(1), 216 | error: rpc::Error { 217 | code: rpc::ErrorCode::ServerError(-1), 218 | message: "You are not allowed to call that method.".into(), 219 | data: None, 220 | }, 221 | jsonrpc: Some(rpc::Version::V2), 222 | })) 223 | } 224 | 225 | #[test] 226 | fn should_allow_method_by_global_policy() { 227 | // given 228 | let middleware = middleware(Default::default()); 229 | let (next, called) = callback(); 230 | 231 | // when 232 | let result = middleware.on_call(method_call("eth_getBlock"), (), next); 233 | 234 | // then 235 | assert_eq!(called.load(atomic::Ordering::SeqCst), true); 236 | assert_eq!(result.wait(), None); 237 | } 238 | 239 | #[test] 240 | fn should_deny_blacklisted_method() { 241 | // given 242 | let middleware = middleware(Permissioning { 243 | policy: Access::Allow, 244 | methods: vec![Method { 245 | name: "eth_getBlock".into(), 246 | policy: Access::Deny, 247 | }], 248 | }); 249 | let (next, called) = callback(); 250 | 251 | // when 252 | let result = middleware.on_call(method_call("eth_getBlock"), (), next); 253 | 254 | // then 255 | assert_eq!(called.load(atomic::Ordering::SeqCst), false); 256 | assert_eq!(result.wait(), not_allowed()); 257 | } 258 | 259 | #[test] 260 | fn should_deny_method_by_global_policy() { 261 | // given 262 | let middleware = middleware(Permissioning { 263 | policy: Access::Deny, 264 | methods: vec![], 265 | }); 266 | let (next, called) = callback(); 267 | 268 | // when 269 | let result = middleware.on_call(method_call("eth_getBlock"), (), next); 270 | 271 | // then 272 | assert_eq!(called.load(atomic::Ordering::SeqCst), false); 273 | assert_eq!(result.wait(), not_allowed()); 274 | } 275 | 276 | #[test] 277 | fn should_allow_whitelisted_method() { 278 | // given 279 | let middleware = middleware(Permissioning { 280 | policy: Access::Deny, 281 | methods: vec![Method { 282 | name: "eth_getBlock".into(), 283 | policy: Access::Allow, 284 | }], 285 | }); 286 | let (next, called) = callback(); 287 | 288 | // when 289 | let result = middleware.on_call(method_call("eth_getBlock"), (), next); 290 | 291 | // then 292 | assert_eq!(called.load(atomic::Ordering::SeqCst), true); 293 | assert_eq!(result.wait(), None); 294 | } 295 | } 296 | -------------------------------------------------------------------------------- /plugins/simple-cache/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "simple-cache" 3 | version = "0.1.0" 4 | authors = ["Tomasz Drwięga "] 5 | license = "GPL-3.0-or-later" 6 | 7 | [dependencies] 8 | cli-params = { path = "../../proxy/cli-params" } 9 | fnv = "1.0" 10 | jsonrpc-core = "16.0" 11 | parking_lot = "0.11" 12 | serde = "1.0" 13 | serde_json = "1.0" 14 | serde_derive = "1.0" 15 | twox-hash = "1.6" 16 | -------------------------------------------------------------------------------- /plugins/simple-cache/src/config.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-2020 jsonrpc-proxy contributors. 2 | // 3 | // This file is part of jsonrpc-proxy 4 | // (see https://github.com/tomusdrw/jsonrpc-proxy). 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | //! CLI configuration for simple cache. 19 | 20 | use cli_params; 21 | use serde_json; 22 | use std::{fs, io}; 23 | use Method; 24 | 25 | /// A configuration option to apply. 26 | pub enum Param { 27 | /// Methods that should be cached. 28 | Config(Cache), 29 | } 30 | 31 | /// Returns a list of supported configuration parameters. 32 | pub fn params() -> Vec> { 33 | vec![cli_params::Param::new( 34 | "Simple Cache", 35 | "simple-cache-config", 36 | "A path to a JSON file containing a list of methods that should be cached. See examples for the file schema.", 37 | "-", 38 | |path: String| { 39 | if &path == "-" { 40 | return Ok(Param::Config(Default::default())); 41 | } 42 | 43 | let file = fs::File::open(&path).map_err(|e| format!("Can't open cache file at {}: {:?}", path, e))?; 44 | let buf_file = io::BufReader::new(file); 45 | let methods: Cache = 46 | serde_json::from_reader(buf_file).map_err(|e| format!("Invalid JSON at {}: {:?}", path, e))?; 47 | Ok(Param::Config(methods)) 48 | }, 49 | )] 50 | } 51 | 52 | /// Add methods given as the first parameter to the config in one of the params. 53 | pub fn add_methods(params: &mut [Param], methods: Vec) { 54 | for p in params { 55 | match p { 56 | Param::Config(ref mut config) => { 57 | config.methods.extend(methods.clone()); 58 | } 59 | } 60 | } 61 | } 62 | 63 | /// Cache configuration 64 | #[derive(Clone, Deserialize)] 65 | pub struct Cache { 66 | /// If not enabled method definitions are ignored. 67 | pub enabled: bool, 68 | /// Per-method definitions 69 | pub methods: Vec, 70 | } 71 | impl Default for Cache { 72 | fn default() -> Self { 73 | Self { 74 | enabled: true, 75 | methods: Default::default(), 76 | } 77 | } 78 | } 79 | 80 | #[cfg(test)] 81 | mod tests { 82 | use super::*; 83 | 84 | #[test] 85 | fn should_deserialize_example() { 86 | let _m: Cache = serde_json::from_slice(include_bytes!("../../../examples/cache.json")).unwrap(); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /plugins/simple-cache/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-2020 jsonrpc-proxy contributors. 2 | // 3 | // This file is part of jsonrpc-proxy 4 | // (see https://github.com/tomusdrw/jsonrpc-proxy). 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | //! A simplistic RPC cache. 19 | //! 20 | //! Caches the result of calling the RPC method and clears it 21 | //! depending on the cache eviction policy. 22 | 23 | #![warn(missing_docs)] 24 | #![warn(unused_extern_crates)] 25 | 26 | extern crate cli_params; 27 | extern crate fnv; 28 | extern crate jsonrpc_core as rpc; 29 | extern crate parking_lot; 30 | extern crate serde_json; 31 | extern crate twox_hash; 32 | 33 | #[macro_use] 34 | extern crate serde_derive; 35 | 36 | use fnv::FnvHashMap; 37 | use parking_lot::RwLock; 38 | use rpc::futures::{ 39 | future::{self, Either}, 40 | Future, 41 | }; 42 | use std::{ 43 | hash::{Hash as HashTrait, Hasher}, 44 | io, 45 | sync::Arc, 46 | time, 47 | }; 48 | 49 | type Hash = u64; 50 | 51 | pub mod config; 52 | 53 | /// Cache eviction policy 54 | #[derive(Clone, Debug, Deserialize)] 55 | #[serde(rename_all = "camelCase")] 56 | pub enum CacheEviction { 57 | /// Time-based caching. The cache entry is discarded after given amount of time. 58 | Time(time::Duration), 59 | // TODO [ToDr] notification (via subscription) 60 | } 61 | 62 | /// Method metadata 63 | #[derive(Debug)] 64 | enum MethodMeta { 65 | Deadline(time::Instant), 66 | } 67 | 68 | /// Represents a cacheable method. 69 | /// 70 | /// Should know how to compute a hash that is used to compare requests. 71 | /// TODO [ToDr] Support different eviction policies. 72 | #[derive(Clone, Debug, Deserialize)] 73 | pub struct Method { 74 | name: String, 75 | eviction: CacheEviction, 76 | } 77 | 78 | impl Method { 79 | /// Create new method. 80 | pub fn new>(name: T, eviction: CacheEviction) -> Self { 81 | Method { 82 | name: name.into(), 83 | eviction, 84 | } 85 | } 86 | 87 | /// Returns a hash of parameters of this method. 88 | fn hash(&self, parameters: &rpc::Params) -> Hash { 89 | let mut hasher = twox_hash::XxHash::default(); 90 | self.name.hash(&mut hasher); 91 | serde_json::to_writer(HashWriter(&mut hasher), parameters).expect("HashWriter never fails."); 92 | hasher.finish() 93 | } 94 | 95 | /// Generates metadata that should be stored in the cache together with the value. 96 | fn meta(&self) -> MethodMeta { 97 | match self.eviction { 98 | CacheEviction::Time(duration) => MethodMeta::Deadline(time::Instant::now() + duration), 99 | } 100 | } 101 | 102 | /// Determines if the cached result is still ok to use. 103 | fn is_fresh(&self, meta: &MethodMeta) -> bool { 104 | match *meta { 105 | MethodMeta::Deadline(deadline) => time::Instant::now() < deadline, 106 | } 107 | } 108 | } 109 | 110 | /// Simple single-level caching middleware. 111 | /// 112 | /// Takes a list of cacheable methods as a parameter. Can construct multiple caches 113 | /// for single method, based on the parameters. 114 | #[derive(Debug)] 115 | pub struct Middleware { 116 | enabled: bool, 117 | cacheable: FnvHashMap, 118 | cached: Arc, MethodMeta)>>>, 119 | } 120 | 121 | impl Middleware { 122 | /// Creates new caching middleware given cacheable methods definitions. 123 | /// 124 | /// TODO [ToDr] Cache limits 125 | pub fn new(params: &[config::Param]) -> Self { 126 | let mut cache = config::Cache::default(); 127 | for p in params { 128 | match p { 129 | config::Param::Config(ref m) => cache = m.clone(), 130 | } 131 | } 132 | 133 | Middleware { 134 | enabled: cache.enabled, 135 | cacheable: cache.methods.into_iter().map(|x| (x.name.clone(), x)).collect(), 136 | cached: Default::default(), 137 | } 138 | } 139 | } 140 | 141 | impl rpc::Middleware for Middleware { 142 | type Future = rpc::middleware::NoopFuture; 143 | type CallFuture = Either>>; 144 | 145 | fn on_call(&self, call: rpc::Call, meta: M, next: F) -> Either 146 | where 147 | F: FnOnce(rpc::Call, M) -> X + Send, 148 | X: Future> + Send + 'static, 149 | { 150 | use rpc::futures::FutureExt; 151 | 152 | if !self.enabled { 153 | return Either::Right(next(call, meta)); 154 | } 155 | 156 | enum Action { 157 | Next, 158 | NextAndCache(Hash, MethodMeta), 159 | Return(Option), 160 | } 161 | 162 | let action = match call { 163 | rpc::Call::MethodCall(rpc::MethodCall { 164 | ref method, ref params, .. 165 | }) => { 166 | if let Some(method) = self.cacheable.get(method) { 167 | let hash = method.hash(params); 168 | if let Some((result, meta)) = self.cached.read().get(&hash) { 169 | if method.is_fresh(meta) { 170 | Action::Return(result.clone()) 171 | } else { 172 | Action::NextAndCache(hash, method.meta()) 173 | } 174 | } else { 175 | Action::NextAndCache(hash, method.meta()) 176 | } 177 | } else { 178 | Action::Next 179 | } 180 | } 181 | _ => Action::Next, 182 | }; 183 | 184 | match action { 185 | // Fallback 186 | Action::Next => Either::Right(next(call, meta)), 187 | // TODO [ToDr] Prevent multiple requests being made. 188 | Action::NextAndCache(hash, method_meta) => { 189 | let cached = self.cached.clone(); 190 | Either::Left(Either::Left(Box::pin(next(call, meta).map(move |result| { 191 | cached.write().insert(hash, (result.clone(), method_meta)); 192 | result 193 | })))) 194 | } 195 | Action::Return(result) => Either::Left(Either::Right(future::ready(result))), 196 | } 197 | } 198 | } 199 | 200 | struct HashWriter<'a, W: 'a>(&'a mut W); 201 | 202 | impl<'a, W: 'a + Hasher> io::Write for HashWriter<'a, W> { 203 | fn write(&mut self, buf: &[u8]) -> io::Result { 204 | buf.hash(self.0); 205 | Ok(buf.len()) 206 | } 207 | 208 | fn flush(&mut self) -> io::Result<()> { 209 | Ok(()) 210 | } 211 | } 212 | 213 | #[cfg(test)] 214 | mod tests { 215 | use super::*; 216 | use rpc::Middleware as MiddlewareTrait; 217 | use std::sync::{atomic, Arc}; 218 | 219 | trait FutExt: std::future::Future { 220 | fn wait(self) -> Self::Output; 221 | } 222 | 223 | impl FutExt for F 224 | where 225 | F: std::future::Future, 226 | { 227 | fn wait(self) -> Self::Output { 228 | rpc::futures::executor::block_on(self) 229 | } 230 | } 231 | 232 | fn callback() -> ( 233 | impl Fn(rpc::Call, ()) -> rpc::futures::future::Ready>, 234 | Arc, 235 | ) { 236 | let called = Arc::new(atomic::AtomicUsize::new(0)); 237 | let called2 = called.clone(); 238 | let next = move |_, _| { 239 | called2.fetch_add(1, atomic::Ordering::SeqCst); 240 | rpc::futures::future::ready(None) 241 | }; 242 | 243 | (next, called) 244 | } 245 | 246 | fn method_call(name: &str, param: &str) -> rpc::Call { 247 | rpc::Call::MethodCall(rpc::MethodCall { 248 | id: rpc::Id::Num(1), 249 | jsonrpc: Some(rpc::Version::V2), 250 | method: name.into(), 251 | params: rpc::Params::Array(vec![param.into()]), 252 | }) 253 | } 254 | 255 | fn middleware(config: config::Cache) -> Middleware { 256 | Middleware::new(&[config::Param::Config(config)]) 257 | } 258 | 259 | #[test] 260 | fn should_forward_if_cache_disabled() { 261 | // given 262 | let middleware = middleware(config::Cache { 263 | enabled: false, 264 | methods: vec![Method::new( 265 | "eth_getBlock", 266 | CacheEviction::Time(time::Duration::from_secs(1)), 267 | )], 268 | }); 269 | let (next, called) = callback(); 270 | 271 | // when 272 | let res1 = middleware.on_call(method_call("eth_getBlock", "xyz"), (), &next).wait(); 273 | let res2 = middleware.on_call(method_call("eth_getBlock", "xyz"), (), &next).wait(); 274 | 275 | // then 276 | assert_eq!(called.load(atomic::Ordering::SeqCst), 2); 277 | assert_eq!(res1, None); 278 | assert_eq!(res2, None); 279 | } 280 | 281 | #[test] 282 | fn should_return_cached_result() { 283 | // given 284 | let middleware = middleware(config::Cache { 285 | enabled: true, 286 | methods: vec![Method::new( 287 | "eth_getBlock", 288 | CacheEviction::Time(time::Duration::from_secs(1)), 289 | )], 290 | }); 291 | let (next, called) = callback(); 292 | 293 | // when 294 | let res1 = middleware.on_call(method_call("eth_getBlock", "xyz"), (), &next).wait(); 295 | let res2 = middleware.on_call(method_call("eth_getBlock", "xyz"), (), &next).wait(); 296 | 297 | // then 298 | assert_eq!(called.load(atomic::Ordering::SeqCst), 1); 299 | assert_eq!(res1, None); 300 | assert_eq!(res2, None); 301 | } 302 | 303 | #[test] 304 | fn should_not_cache_when_params_different() { 305 | // given 306 | let middleware = middleware(config::Cache { 307 | enabled: true, 308 | methods: vec![Method::new( 309 | "eth_getBlock", 310 | CacheEviction::Time(time::Duration::from_secs(1)), 311 | )], 312 | }); 313 | let (next, called) = callback(); 314 | 315 | // when 316 | let res1 = middleware 317 | .on_call(method_call("eth_getBlock", "xyz1"), (), &next) 318 | .wait(); 319 | let res2 = middleware 320 | .on_call(method_call("eth_getBlock", "xyz2"), (), &next) 321 | .wait(); 322 | 323 | // then 324 | assert_eq!(called.load(atomic::Ordering::SeqCst), 2); 325 | assert_eq!(res1, None); 326 | assert_eq!(res2, None); 327 | } 328 | 329 | #[test] 330 | fn should_invalidate_cache_after_specified_time() { 331 | // given 332 | let middleware = middleware(config::Cache { 333 | enabled: true, 334 | methods: vec![Method::new( 335 | "eth_getBlock", 336 | CacheEviction::Time(time::Duration::from_millis(1)), 337 | )], 338 | }); 339 | let (next, called) = callback(); 340 | 341 | // when 342 | let res1 = middleware.on_call(method_call("eth_getBlock", "xyz"), (), &next).wait(); 343 | let res2 = middleware.on_call(method_call("eth_getBlock", "xyz"), (), &next).wait(); 344 | ::std::thread::sleep(time::Duration::from_millis(2)); 345 | let res3 = middleware.on_call(method_call("eth_getBlock", "xyz"), (), &next).wait(); 346 | 347 | // then 348 | assert_eq!(called.load(atomic::Ordering::SeqCst), 2); 349 | assert_eq!(res1, None); 350 | assert_eq!(res2, None); 351 | assert_eq!(res3, None); 352 | } 353 | 354 | // TODO [ToDr] Implement me 355 | #[ignore] 356 | #[test] 357 | fn should_never_send_request_twice() { 358 | // given 359 | let middleware = middleware(config::Cache { 360 | enabled: true, 361 | methods: vec![Method::new( 362 | "eth_getBlock", 363 | CacheEviction::Time(time::Duration::from_secs(1)), 364 | )], 365 | }); 366 | let (next, called) = callback(); 367 | 368 | // when 369 | let res1 = middleware.on_call(method_call("eth_getBlock", "xyz"), (), &next); 370 | let res2 = middleware.on_call(method_call("eth_getBlock", "xyz"), (), &next); 371 | 372 | // then 373 | assert_eq!(called.load(atomic::Ordering::SeqCst), 1); 374 | assert_eq!(res1.wait(), None); 375 | assert_eq!(res2.wait(), None); 376 | } 377 | } 378 | -------------------------------------------------------------------------------- /plugins/upstream/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "upstream" 3 | version = "0.1.0" 4 | authors = ["Tomasz Drwięga "] 5 | license = "GPL-3.0-or-later" 6 | 7 | [dependencies] 8 | cli-params = { path = "../../proxy/cli-params" } 9 | fnv = "1.0" 10 | jsonrpc-core = "16.0" 11 | jsonrpc-pubsub = "18.0" 12 | log = "0.4" 13 | parking_lot = "0.11" 14 | serde = "1.0" 15 | serde_json = "1.0" 16 | serde_derive = "1.0" 17 | twox-hash = "1.6" 18 | websocket = { version = "0.26", default-features = false, features = ["async"] } 19 | -------------------------------------------------------------------------------- /plugins/upstream/src/config.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-2020 jsonrpc-proxy contributors. 2 | // 3 | // This file is part of jsonrpc-proxy 4 | // (see https://github.com/tomusdrw/jsonrpc-proxy). 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | //! Upstream configuration parameters. 19 | 20 | use cli_params; 21 | use serde_json; 22 | use std::{fs, io}; 23 | use Subscription; 24 | 25 | /// Configuration options of an upstream 26 | #[derive(Clone, Debug)] 27 | pub enum Param { 28 | /// PublishSubscribe methods 29 | PubSubMethods(Vec), 30 | } 31 | 32 | /// Returns all configuration parameters for WS upstream. 33 | pub fn params() -> Vec> { 34 | vec![cli_params::Param::new( 35 | "Upstream configuration", 36 | "upstream-config", 37 | "Configuration of the upstream. Should contain a list of supported pub-sub methods.", 38 | "-", 39 | move |path: String| { 40 | if &path == "-" { 41 | return Ok(Param::PubSubMethods(Default::default())); 42 | } 43 | 44 | let file = 45 | fs::File::open(&path).map_err(|e| format!("Can't open upstream config file at {}: {:?}", path, e))?; 46 | let buf_file = io::BufReader::new(file); 47 | let config: Upstream = 48 | serde_json::from_reader(buf_file).map_err(|e| format!("Invalid JSON at {}: {:?}", path, e))?; 49 | Ok(Param::PubSubMethods(config.pubsub_methods)) 50 | }, 51 | )] 52 | } 53 | 54 | /// Adds pubsub methods definitions to the existing parameter. 55 | pub fn add_subscriptions(params: &mut [Param], methods: Vec) { 56 | for p in params { 57 | match p { 58 | Param::PubSubMethods(ref mut m) => { 59 | m.extend(methods.clone()); 60 | } 61 | } 62 | } 63 | } 64 | 65 | #[derive(Deserialize)] 66 | #[serde(rename_all = "camelCase")] 67 | struct Upstream { 68 | pubsub_methods: Vec, 69 | } 70 | 71 | #[cfg(test)] 72 | mod tests { 73 | use super::*; 74 | 75 | #[test] 76 | fn should_deserialize_example_configuration() { 77 | let _m: Upstream = serde_json::from_slice(include_bytes!("../../../examples/upstream.json")).unwrap(); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /plugins/upstream/src/helpers.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-2020 jsonrpc-proxy contributors. 2 | // 3 | // This file is part of jsonrpc-proxy 4 | // (see https://github.com/tomusdrw/jsonrpc-proxy). 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | //! Request parsing helper methods. 19 | 20 | use pubsub; 21 | use rpc; 22 | use serde_json; 23 | 24 | /// Attempt to peek subscription id from the request given as bytes. 25 | /// 26 | /// TODO [ToDr] The implementation should deserialize only subscriptionId part, 27 | /// not the entire `Notification` 28 | pub fn peek_subscription_id(bytes: &[u8]) -> Option { 29 | serde_json::from_slice::(bytes) 30 | .ok() 31 | .and_then(|notification| { 32 | if let rpc::Params::Map(ref map) = notification.params { 33 | map.get("subscription") 34 | .and_then(|v| pubsub::SubscriptionId::parse_value(v)) 35 | } else { 36 | None 37 | } 38 | }) 39 | } 40 | 41 | /// Attempt to peek the result of a successful call. 42 | /// 43 | /// TODO [ToDr] The implementation should deserialize only result part, 44 | /// not the entire `rpc::Success` 45 | pub fn peek_result(bytes: &[u8]) -> Option { 46 | serde_json::from_slice::(bytes).ok().map(|res| res.result) 47 | } 48 | 49 | /// Attempt to peek the id of a call. 50 | /// 51 | /// TODO [ToDr] The implementation should deserialize only id part, 52 | /// not the entire `rpc::Call` 53 | pub fn peek_id(bytes: &[u8]) -> Option { 54 | serde_json::from_slice::(bytes) 55 | .ok() 56 | .and_then(|call| get_id(&call).cloned()) 57 | } 58 | 59 | /// Extract method name of given call. 60 | pub fn get_method_name(call: &rpc::Call) -> Option<&str> { 61 | match *call { 62 | rpc::Call::MethodCall(rpc::MethodCall { ref method, .. }) => Some(method), 63 | rpc::Call::Notification(rpc::Notification { ref method, .. }) => Some(method), 64 | rpc::Call::Invalid { .. } => None, 65 | } 66 | } 67 | 68 | /// Get id of given call. 69 | pub fn get_id(call: &rpc::Call) -> Option<&rpc::Id> { 70 | match *call { 71 | rpc::Call::MethodCall(rpc::MethodCall { ref id, .. }) => Some(id), 72 | rpc::Call::Notification(_) => None, 73 | rpc::Call::Invalid { ref id, .. } => Some(id), 74 | } 75 | } 76 | 77 | /// Extract the first parameter of a call and parse it as subscription id. 78 | pub fn get_unsubscribe_id(call: &rpc::Call) -> Option { 79 | match *call { 80 | rpc::Call::MethodCall(rpc::MethodCall { ref params, .. }) 81 | | rpc::Call::Notification(rpc::Notification { ref params, .. }) => match params { 82 | rpc::Params::Array(ref vec) if !vec.is_empty() => pubsub::SubscriptionId::parse_value(&vec[0]), 83 | _ => { 84 | warn!( 85 | "Invalid unsubscribe params: {:?}. Perhaps it's not really an unsubscribe call?", 86 | call 87 | ); 88 | None 89 | } 90 | }, 91 | _ => { 92 | warn!( 93 | "Invalid unsubscribe payload: {:?}. Perhaps it's not really an unsubscribe call?", 94 | call 95 | ); 96 | None 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /plugins/upstream/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-2020 jsonrpc-proxy contributors. 2 | // 3 | // This file is part of jsonrpc-proxy 4 | // (see https://github.com/tomusdrw/jsonrpc-proxy). 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | //! Upstream base crate. 19 | //! 20 | //! Used by specific implementations and contains abstract logic that can be re-used between them. 21 | 22 | #![warn(missing_docs)] 23 | #![warn(unused_extern_crates)] 24 | 25 | extern crate cli_params; 26 | extern crate jsonrpc_core as rpc; 27 | extern crate jsonrpc_pubsub as pubsub; 28 | extern crate parking_lot; 29 | extern crate serde_json; 30 | 31 | #[macro_use] 32 | extern crate serde_derive; 33 | 34 | #[macro_use] 35 | extern crate log; 36 | 37 | use std::{collections::HashMap, sync::Arc}; 38 | 39 | use rpc::futures::{future::Either, Future}; 40 | 41 | pub mod config; 42 | pub mod helpers; 43 | pub mod shared; 44 | 45 | /// Represents a Pub-Sub method description. 46 | #[derive(Debug, Clone, Deserialize)] 47 | pub struct Subscription { 48 | /// Subscribe method name. 49 | pub subscribe: String, 50 | /// Unsubscribe method name. 51 | pub unsubscribe: String, 52 | /// A method for notifications for that subscription. 53 | pub name: String, 54 | } 55 | 56 | /// Passthrough transport. 57 | /// 58 | /// This is an upstream transport (can do load balancing, failover or parallel requests) 59 | pub trait Transport: Send + Sync + 'static { 60 | /// Error type of the transport. 61 | type Error: ::std::fmt::Debug; 62 | /// Future returned by the transport. 63 | type Future: Future, Self::Error>> + Send + Unpin + 'static; 64 | 65 | /// Send subscribe call upstream. 66 | fn subscribe( 67 | &self, 68 | call: rpc::Call, 69 | sink: Option>, 70 | subscription: Subscription, 71 | ) -> Self::Future; 72 | 73 | /// Send unsubscribe call upstream. 74 | fn unsubscribe(&self, call: rpc::Call, subscription: Subscription) -> Self::Future; 75 | 76 | /// Send a regular call upstream. 77 | fn send(&self, call: rpc::Call) -> Self::Future; 78 | } 79 | 80 | /// Pass-through middleware 81 | /// 82 | /// Delegates the calls to the upstream `Transport` - should be used as the last middleware, 83 | /// since it never calls `next`. 84 | #[derive(Debug)] 85 | pub struct Middleware { 86 | transport: T, 87 | subscribe_methods: HashMap, 88 | unsubscribe_methods: HashMap, 89 | } 90 | 91 | impl Middleware { 92 | /// Create new passthrough middleware with given upstream and the list of pubsub methods. 93 | pub fn new(transport: T, params: &[config::Param]) -> Self { 94 | let mut pubsub_methods = vec![]; 95 | for p in params { 96 | match p { 97 | config::Param::PubSubMethods(ref m) => pubsub_methods.extend(m.clone()), 98 | } 99 | } 100 | 101 | Self { 102 | transport, 103 | subscribe_methods: pubsub_methods 104 | .iter() 105 | .map(|s| (s.subscribe.clone(), s.clone())) 106 | .collect(), 107 | unsubscribe_methods: pubsub_methods.into_iter().map(|s| (s.unsubscribe.clone(), s)).collect(), 108 | } 109 | } 110 | } 111 | 112 | impl rpc::Middleware for Middleware 113 | where 114 | T: Transport + 'static, 115 | M: rpc::Metadata + Into>>, 116 | { 117 | type Future = rpc::middleware::NoopFuture; 118 | type CallFuture = rpc::middleware::NoopCallFuture; 119 | 120 | fn on_call(&self, request: rpc::Call, meta: M, _next: F) -> Either 121 | where 122 | F: FnOnce(rpc::Call, M) -> X + Send, 123 | X: Future> + Send + 'static, 124 | { 125 | use rpc::futures::{FutureExt, TryFutureExt}; 126 | 127 | let (subscribe, unsubscribe) = { 128 | let method = helpers::get_method_name(&request); 129 | if let Some(method) = method { 130 | match self.subscribe_methods.get(method).cloned() { 131 | Some(subscription) => (Some(subscription), None), 132 | None => (None, self.unsubscribe_methods.get(method).cloned()), 133 | } 134 | } else { 135 | (None, None) 136 | } 137 | }; 138 | 139 | if let Some(subscription) = subscribe { 140 | return Either::Left(Box::pin( 141 | self.transport 142 | .subscribe(request, meta.into(), subscription) 143 | .map_err(|e| warn!("Failed to subscribe: {:?}", e)) 144 | .map(|v| v.unwrap_or(None)), 145 | )); 146 | } 147 | 148 | if let Some(subscription) = unsubscribe { 149 | return Either::Left(Box::pin( 150 | self.transport 151 | .unsubscribe(request, subscription) 152 | .map_err(|e| warn!("Failed to unsubscribe: {:?}", e)) 153 | .map(|v| v.unwrap_or(None)), 154 | )); 155 | } 156 | 157 | Either::Left(Box::pin( 158 | self.transport 159 | .send(request) 160 | .map_err(|e| warn!("Failed to send: {:?}", e)) 161 | .map(|v| v.unwrap_or(None)), 162 | )) 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /plugins/upstream/src/shared.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-2020 jsonrpc-proxy contributors. 2 | // 3 | // This file is part of jsonrpc-proxy 4 | // (see https://github.com/tomusdrw/jsonrpc-proxy). 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | //! Shared pieces for building upstream transport. 19 | 20 | use parking_lot::{Mutex, RwLock}; 21 | use pubsub; 22 | use rpc::{self, futures::channel::oneshot}; 23 | use std::{ 24 | collections::HashMap, 25 | fmt, 26 | sync::{Arc, Weak}, 27 | }; 28 | 29 | /// Pending request details 30 | pub type Pending = (oneshot::Sender, PendingKind); 31 | /// A type of unsubscribe function 32 | pub type Unsubscribe = Box; 33 | 34 | /// Pending request type 35 | pub enum PendingKind { 36 | /// Regular request (RPC -> MethodCall) 37 | Regular, 38 | /// Subscribe request (after it's successful we should create a subscription) 39 | Subscribe(Arc, Unsubscribe), 40 | } 41 | 42 | impl fmt::Debug for PendingKind { 43 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { 44 | match *self { 45 | PendingKind::Regular => write!(fmt, "Regular"), 46 | PendingKind::Subscribe(ref session, _) => write!(fmt, "Subscribe({:?})", session), 47 | } 48 | } 49 | } 50 | 51 | /// Shared subscription and pending requests manager. 52 | #[derive(Debug, Default)] 53 | pub struct Shared { 54 | // TODO [ToDr] Get rid of Mutex, rather use `Select` and have another channel that sets up pending requests. 55 | pending: Mutex>, 56 | // TODO [ToDr] Use (SubscriptionName, SubscriptionId) as key. 57 | subscriptions: RwLock>>, 58 | } 59 | 60 | impl Shared { 61 | /// Adds a new request to the list of pending requests 62 | /// 63 | /// We are awaiting the response for those requests. 64 | pub fn add_pending(&self, id: Option<&rpc::Id>, kind: PendingKind) -> Option> { 65 | if let Some(id) = id { 66 | let (tx, rx) = oneshot::channel(); 67 | self.pending.lock().insert(id.clone(), (tx, kind)); 68 | Some(rx) 69 | } else { 70 | None 71 | } 72 | } 73 | 74 | /// Removes a requests from the list of pending requests. 75 | /// 76 | /// Most likely the response has been received so we can respond or add a subscription instead. 77 | pub fn remove_pending(&self, id: &rpc::Id) -> Option { 78 | self.pending.lock().remove(id) 79 | } 80 | 81 | /// Add a new subscription id and it's correlation with the session. 82 | pub fn add_subscription( 83 | &self, 84 | id: pubsub::SubscriptionId, 85 | session: Arc, 86 | unsubscribe: Unsubscribe, 87 | ) { 88 | // make sure to send unsubscribe request and remove the subscription. 89 | let id2 = id.clone(); 90 | session.on_drop(move || unsubscribe(id2)); 91 | 92 | trace!("Registered subscription id {:?}", id); 93 | self.subscriptions.write().insert(id, Arc::downgrade(&session)); 94 | } 95 | 96 | /// Removes a subscription. 97 | pub fn remove_subscription(&self, id: &pubsub::SubscriptionId) { 98 | trace!("Removing subscription id {:?}", id); 99 | self.subscriptions.write().remove(id); 100 | } 101 | 102 | /// Forwards a notification to given subscription. 103 | pub fn notify_subscription(&self, id: &pubsub::SubscriptionId, msg: String) -> Option> { 104 | if let Some(session) = self.subscriptions.read().get(&id) { 105 | if let Some(session) = session.upgrade() { 106 | return Some( 107 | session 108 | .sender() 109 | .unbounded_send(msg) 110 | .map_err(|e| format!("Error sending notification: {:?}", e)) 111 | .map(|_| ()), 112 | ); 113 | } else { 114 | error!("Session is not available and subscription was not removed."); 115 | } 116 | } 117 | 118 | None 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /plugins/ws-upstream/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ws-upstream" 3 | version = "0.1.0" 4 | authors = ["Tomasz Drwięga "] 5 | license = "GPL-3.0-or-later" 6 | edition = "2018" 7 | 8 | [dependencies] 9 | cli-params = { path = "../../proxy/cli-params" } 10 | futures01 = { package = "futures", version = "0.1" } 11 | jsonrpc-core = "16.0" 12 | jsonrpc-pubsub = "18.0" 13 | log = "0.4" 14 | serde_json = "1.0" 15 | upstream = { path = "../upstream" } 16 | url = "1.0" 17 | websocket = { version = "0.26", default-features = false, features = ["async"] } 18 | -------------------------------------------------------------------------------- /plugins/ws-upstream/src/config.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-2020 jsonrpc-proxy contributors. 2 | // 3 | // This file is part of jsonrpc-proxy 4 | // (see https://github.com/tomusdrw/jsonrpc-proxy). 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | //! WebSocket upstream configuration parameters. 19 | 20 | use cli_params; 21 | 22 | /// Configuration options of the WS upstream 23 | pub enum Param { 24 | /// Upstream URL 25 | Url(url::Url), 26 | } 27 | 28 | /// Returns all configuration parameters for WS upstream. 29 | pub fn params() -> Vec> { 30 | vec![cli_params::Param::new( 31 | "WebSockets upstream", 32 | "upstream-ws", 33 | "Address of the parent WebSockets RPC server that we should connect to.", 34 | "ws://127.0.0.1:9944", 35 | move |val: String| { 36 | let url = val.parse().map_err(|e| format!("Invalid upstream address: {:?}", e))?; 37 | Ok(Param::Url(url)) 38 | }, 39 | )] 40 | } 41 | -------------------------------------------------------------------------------- /plugins/ws-upstream/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-2020 jsonrpc-proxy contributors. 2 | // 3 | // This file is part of jsonrpc-proxy 4 | // (see https://github.com/tomusdrw/jsonrpc-proxy). 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | 19 | //! WebSocket Upstream Transport 20 | 21 | #![warn(missing_docs)] 22 | 23 | pub mod config; 24 | 25 | use jsonrpc_core::futures::{ 26 | self, 27 | channel::{mpsc, oneshot}, 28 | future::{self, Either}, 29 | Future, FutureExt, StreamExt, TryFutureExt, 30 | }; 31 | use std::sync::{atomic, Arc}; 32 | use upstream::{ 33 | helpers, 34 | shared::{PendingKind, Shared}, 35 | Subscription, 36 | }; 37 | use websocket::OwnedMessage; 38 | 39 | struct WebSocketHandler { 40 | shared: Arc, 41 | write_sender: mpsc::UnboundedSender, 42 | } 43 | 44 | impl WebSocketHandler { 45 | pub fn process_message(&self, message: OwnedMessage) -> impl Future> { 46 | future::ready(match message { 47 | OwnedMessage::Close(e) => self 48 | .write_sender 49 | .unbounded_send(OwnedMessage::Close(e)) 50 | .map_err(|e| format!("Error sending close message: {:?}", e)), 51 | OwnedMessage::Ping(d) => self 52 | .write_sender 53 | .unbounded_send(OwnedMessage::Pong(d)) 54 | .map_err(|e| format!("Error sending pong message: {:?}", e)), 55 | OwnedMessage::Text(t) => { 56 | // First check if it's a notification for a subscription 57 | if let Some(id) = helpers::peek_subscription_id(t.as_bytes()) { 58 | return future::ready(self.shared.notify_subscription(&id, t).unwrap_or_else(|| { 59 | log::warn!("Got notification for unknown subscription (id: {:?})", id); 60 | Ok(()) 61 | })); 62 | } 63 | 64 | // then check if it's one of the pending calls 65 | if let Some(id) = helpers::peek_id(t.as_bytes()) { 66 | if let Some((sink, kind)) = self.shared.remove_pending(&id) { 67 | match kind { 68 | // Just a regular call, don't do anything else. 69 | PendingKind::Regular => {} 70 | // We have a subscription ID, register subscription. 71 | PendingKind::Subscribe(session, unsubscribe) => { 72 | let subscription_id = helpers::peek_result(t.as_bytes()) 73 | .as_ref() 74 | .and_then(jsonrpc_pubsub::SubscriptionId::parse_value); 75 | if let Some(subscription_id) = subscription_id { 76 | self.shared.add_subscription(subscription_id, session, unsubscribe); 77 | } 78 | } 79 | } 80 | 81 | log::trace!("Responding to (id: {:?}) with {:?}", id, t); 82 | if let Err(err) = sink.send(t) { 83 | log::warn!("Sending a response to deallocated channel: {:?}", err); 84 | } 85 | } else { 86 | log::warn!("Got response for unknown request (id: {:?})", id); 87 | } 88 | } else { 89 | log::warn!("Got unexpected notification: {:?}", t); 90 | } 91 | 92 | Ok(()) 93 | } 94 | _ => Ok(()), 95 | }) 96 | } 97 | } 98 | 99 | type Spawnable = Box + Send + Unpin>; 100 | 101 | /// A tokio abstraction. 102 | pub trait Spawn: Send + Sync { 103 | /// Spawn a task in the background. 104 | fn spawn(&self, ft: Spawnable); 105 | } 106 | 107 | impl Spawn for F { 108 | fn spawn(&self, ft: Spawnable) { 109 | (*self)(ft) 110 | } 111 | } 112 | 113 | /// WebSocket transport 114 | #[derive(Clone)] 115 | pub struct WebSocket { 116 | id: Arc, 117 | url: url::Url, 118 | shared: Arc, 119 | spawn: Arc, 120 | write_sender: mpsc::UnboundedSender, 121 | } 122 | 123 | impl std::fmt::Debug for WebSocket { 124 | fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { 125 | fmt.debug_struct("WebSocket") 126 | .field("id", &self.id) 127 | .field("url", &self.url) 128 | .field("shared", &self.shared) 129 | .finish() 130 | } 131 | } 132 | 133 | impl WebSocket { 134 | /// Create new WebSocket transport within existing Event Loop. 135 | pub fn new(params: Vec, spawn_tasks: impl Spawn + 'static) -> Result { 136 | let mut url = "ws://127.0.0.1:9944".parse().expect("Valid address given."); 137 | 138 | for p in params { 139 | match p { 140 | config::Param::Url(new_url) => { 141 | url = new_url; 142 | } 143 | } 144 | } 145 | 146 | println!("[WS] Connecting to: {:?}", url); 147 | 148 | let (write_sender, write_receiver) = mpsc::unbounded(); 149 | let shared = Arc::new(Shared::default()); 150 | 151 | let ws_future = { 152 | use futures::{compat::Future01CompatExt, TryStreamExt}; 153 | use futures01::{Future, Sink, Stream}; 154 | 155 | let handler = WebSocketHandler { 156 | shared: shared.clone(), 157 | write_sender: write_sender.clone(), 158 | }; 159 | 160 | let write_receiver = write_receiver 161 | .map(|msg| { 162 | log::trace!("Sending request: {:?}", msg); 163 | msg 164 | }) 165 | .map(|x| Ok(x) as Result<_, websocket::WebSocketError>) 166 | .compat(); 167 | websocket::ClientBuilder::from_url(&url) 168 | .async_connect_insecure() 169 | .map(|(duplex, _)| duplex.split()) 170 | .map_err(|e| format!("{:?}", e)) 171 | .and_then(move |(sink, stream)| { 172 | let reader = stream.map_err(|e| format!("{:?}", e)).for_each(move |message| { 173 | log::trace!("Message received: {:?}", message); 174 | handler.process_message(message).compat() 175 | }); 176 | 177 | let writer = sink 178 | .send_all(write_receiver) 179 | .map_err(|e| format!("{:?}", e)) 180 | .map(|_| ()); 181 | 182 | reader.join(writer) 183 | }) 184 | .compat() 185 | }; 186 | 187 | spawn_tasks.spawn(Box::new( 188 | ws_future 189 | .map_err(|err| { 190 | log::error!("WebSocketError: {:?}", err); 191 | }) 192 | .map(|_| ()), 193 | )); 194 | 195 | Ok(Self { 196 | id: Arc::new(atomic::AtomicUsize::new(1)), 197 | url, 198 | shared, 199 | spawn: Arc::new(spawn_tasks), 200 | write_sender, 201 | }) 202 | } 203 | 204 | fn write_and_wait( 205 | &self, 206 | call: jsonrpc_core::Call, 207 | response: Option>, 208 | ) -> impl Future, String>> { 209 | let request = jsonrpc_core::types::to_string(&call).expect("jsonrpc-core are infallible"); 210 | let result = self 211 | .write_sender 212 | .unbounded_send(OwnedMessage::Text(request)) 213 | .map_err(|e| format!("Error sending request: {:?}", e)); 214 | 215 | future::ready(result).and_then(|_| match response { 216 | None => Either::Left(future::ready(Ok(None))), 217 | Some(res) => res 218 | .map_ok(|out| serde_json::from_str(&out).ok()) 219 | .map_err(|e| format!("{:?}", e)) 220 | .right_future(), 221 | }) 222 | } 223 | } 224 | 225 | // TODO [ToDr] Might be better to simply have one connection per subscription. 226 | // in case we detect that there is something wrong (i.e. the client disconnected) 227 | // we disconnect from the upstream as well and all the subscriptions are dropped automatically. 228 | impl upstream::Transport for WebSocket { 229 | type Error = String; 230 | type Future = Box, Self::Error>> + Send + Unpin>; 231 | 232 | fn send(&self, call: jsonrpc_core::Call) -> Self::Future { 233 | log::trace!("Calling: {:?}", call); 234 | 235 | // TODO [ToDr] Mangle ids per sender or just ensure atomicity 236 | let rx = { 237 | let id = helpers::get_id(&call); 238 | self.shared.add_pending(id, PendingKind::Regular) 239 | }; 240 | 241 | Box::new(self.write_and_wait(call, rx)) 242 | } 243 | 244 | fn subscribe( 245 | &self, 246 | call: jsonrpc_core::Call, 247 | session: Option>, 248 | subscription: Subscription, 249 | ) -> Self::Future { 250 | let session = match session { 251 | Some(session) => session, 252 | None => { 253 | return Box::new(futures::future::err("Called subscribe without session.".into())); 254 | } 255 | }; 256 | 257 | log::trace!("Subscribing to {:?}: {:?}", subscription, call); 258 | 259 | // TODO [ToDr] Mangle ids per sender or just ensure atomicity 260 | let rx = { 261 | let ws = self.clone(); 262 | let id = helpers::get_id(&call); 263 | self.shared.add_pending( 264 | id, 265 | PendingKind::Subscribe( 266 | session, 267 | Box::new(move |subs_id| { 268 | // Create unsubscribe request. 269 | let call = jsonrpc_core::Call::MethodCall(jsonrpc_core::MethodCall { 270 | jsonrpc: Some(jsonrpc_core::Version::V2), 271 | id: jsonrpc_core::Id::Num(1), 272 | method: subscription.unsubscribe.clone(), 273 | params: jsonrpc_core::Params::Array(vec![subs_id.into()]).into(), 274 | }); 275 | let name = subscription.name.clone(); 276 | let fut = ws 277 | .unsubscribe(call, subscription.clone()) 278 | .map_err(move |e| { 279 | log::warn!("Unable to auto-unsubscribe from '{}': {:?}", name, e); 280 | }) 281 | .map(|_| ()); 282 | 283 | ws.spawn.spawn(Box::new(fut)); 284 | }), 285 | ), 286 | ) 287 | }; 288 | 289 | Box::new(self.write_and_wait(call, rx)) 290 | } 291 | 292 | fn unsubscribe(&self, call: jsonrpc_core::Call, subscription: Subscription) -> Self::Future { 293 | log::trace!("Unsubscribing from {:?}: {:?}", subscription, call); 294 | 295 | // Remove the subscription id 296 | if let Some(subscription_id) = helpers::get_unsubscribe_id(&call) { 297 | self.shared.remove_subscription(&subscription_id); 298 | } 299 | 300 | // It's a regular RPC, so just send it 301 | self.send(call) 302 | } 303 | } 304 | -------------------------------------------------------------------------------- /proxy/cli-params/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cli-params" 3 | version = "0.1.0" 4 | authors = ["Tomasz Drwięga "] 5 | license = "GPL-3.0-or-later" 6 | 7 | [dependencies] 8 | -------------------------------------------------------------------------------- /proxy/cli-params/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-2020 jsonrpc-proxy contributors. 2 | // 3 | // This file is part of jsonrpc-proxy 4 | // (see https://github.com/tomusdrw/jsonrpc-proxy). 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | //! A base type for parameter definition. 19 | //! 20 | //! Intendend to be used by plugins to expose configurable parameters. 21 | 22 | #![warn(missing_docs)] 23 | #![warn(unused_extern_crates)] 24 | 25 | /// Parses parameter value 26 | pub trait Parser { 27 | /// A type that can apply parsed parameter. 28 | type Executor; 29 | 30 | /// Parse parameter and return the Executor. 31 | fn parse(&self, value: String) -> Result; 32 | } 33 | 34 | impl Parser for F 35 | where 36 | F: Fn(String) -> Result, 37 | { 38 | type Executor = X; 39 | 40 | fn parse(&self, value: String) -> Result { 41 | (*self)(value) 42 | } 43 | } 44 | 45 | /// Describes a CLI parameter that should be present in the help. 46 | pub struct Param { 47 | /// Parameters category 48 | pub category: String, 49 | /// Parameter name 50 | pub name: String, 51 | /// Parameter description 52 | pub description: String, 53 | /// Parameter default value 54 | pub default_value: String, 55 | /// Parameter parser 56 | pub parser: Box>, 57 | } 58 | 59 | impl Param { 60 | /// Create new parameter definition. 61 | pub fn new(category: A, name: B, description: C, default_value: D, parser: E) -> Self 62 | where 63 | A: Into, 64 | B: Into, 65 | C: Into, 66 | D: Into, 67 | E: Parser + 'static, 68 | { 69 | Param { 70 | category: category.into(), 71 | name: name.into(), 72 | description: description.into(), 73 | default_value: default_value.into(), 74 | parser: Box::new(parser), 75 | } 76 | } 77 | 78 | /// Parse given value and return `Executor` for given param. 79 | pub fn parse(&self, value: Option) -> Result { 80 | let default_value = self.default_value.clone(); 81 | let value = value.unwrap_or_else(|| default_value); 82 | 83 | self.parser.parse(value) 84 | } 85 | } 86 | 87 | // TODO [ToDr] ParamsBuilder to have nicer API 88 | -------------------------------------------------------------------------------- /proxy/cli/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "cli" 3 | version = "0.1.0" 4 | authors = ["Tomasz Drwięga "] 5 | license = "GPL-3.0-or-later" 6 | 7 | [dependencies] 8 | clap = "2.33" 9 | cli-params = { path = "../cli-params" } 10 | -------------------------------------------------------------------------------- /proxy/cli/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-2020 jsonrpc-proxy contributors. 2 | // 3 | // This file is part of jsonrpc-proxy 4 | // (see https://github.com/tomusdrw/jsonrpc-proxy). 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | //! Builds clap CLI from multiple plugins. 19 | 20 | #![warn(missing_docs)] 21 | #![warn(unused_extern_crates)] 22 | 23 | extern crate clap; 24 | extern crate cli_params as params; 25 | 26 | /// Adds plugin parameters to the CLI application. 27 | pub fn configure_app<'a, 'b, Exec>(mut app: clap::App<'a, 'b>, params: &'a [params::Param]) -> clap::App<'a, 'b> { 28 | for p in params { 29 | app = app.arg( 30 | clap::Arg::with_name(&p.name) 31 | .long(&p.name) 32 | .takes_value(true) 33 | .help(&p.description) 34 | .default_value(&p.default_value), 35 | ) 36 | } 37 | app 38 | } 39 | 40 | /// Extract parameters from CLI matches and turn them into parameters executors, which can be used 41 | /// to configure particular transport or plugin. 42 | pub fn parse_matches(matches: &clap::ArgMatches, params: &[params::Param]) -> Result, String> { 43 | params 44 | .iter() 45 | .map(|p| { 46 | let val = matches.value_of(&p.name); 47 | p.parse(val.map(str::to_owned)) 48 | }) 49 | .collect() 50 | } 51 | -------------------------------------------------------------------------------- /proxy/transports/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "transports" 3 | version = "0.1.0" 4 | authors = ["Tomasz Drwięga "] 5 | license = "GPL-3.0-or-later" 6 | 7 | [dependencies] 8 | cli-params = { path = "../cli-params" } 9 | # TODO [ToDr] feature-gate transports. 10 | jsonrpc-core = "16.0" 11 | jsonrpc-http-server = "16.0" 12 | jsonrpc-ipc-server = "16.0" 13 | jsonrpc-pubsub = "18.0" 14 | jsonrpc-tcp-server = "16.0" 15 | jsonrpc-ws-server = "16.0" 16 | log = "0.4" 17 | -------------------------------------------------------------------------------- /proxy/transports/src/http.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-2020 jsonrpc-proxy contributors. 2 | // 3 | // This file is part of jsonrpc-proxy 4 | // (see https://github.com/tomusdrw/jsonrpc-proxy). 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | //! HTTP server for the proxy. 19 | 20 | use std::{ 21 | io, 22 | net::{Ipv4Addr, SocketAddr}, 23 | sync::Arc, 24 | }; 25 | 26 | use jsonrpc_http_server as http; 27 | use params::Param; 28 | use pubsub; 29 | use rpc; 30 | 31 | const CATEGORY: &str = "HTTP Server"; 32 | const PREFIX: &str = "http"; 33 | 34 | /// Returns CLI configuration options for the HTTP server. 35 | pub fn params() -> Vec>>> 36 | where 37 | M: rpc::Metadata, 38 | S: rpc::Middleware, 39 | S::Future: Unpin, 40 | S::CallFuture: Unpin, 41 | { 42 | vec![ 43 | param("port", "9934", "Configures HTTP server listening port.", |value| { 44 | let port: u16 = value 45 | .parse() 46 | .map_err(|e| format!("Invalid port number {}: {}", value, e))?; 47 | Ok(move |address: &mut SocketAddr, builder| { 48 | address.set_port(port); 49 | Ok(builder) 50 | }) 51 | }), 52 | param("ip", "127.0.0.1", "Configures HTTP server interface.", |value| { 53 | let ip: Ipv4Addr = value 54 | .parse() 55 | .map_err(|e| format!("Invalid port number {}: {}", value, e))?; 56 | Ok(move |address: &mut SocketAddr, builder| { 57 | address.set_ip(ip.into()); 58 | Ok(builder) 59 | }) 60 | }), 61 | param("threads", "4", "Configures HTTP server threads.", |value| { 62 | let threads: usize = value 63 | .parse() 64 | .map_err(|e| format!("Invalid threads number {}: {}", value, e))?; 65 | Ok(move |_address: &mut SocketAddr, builder: http::ServerBuilder| Ok(builder.threads(threads))) 66 | }), 67 | param( 68 | "rest-api", 69 | "disabled", 70 | r#" 71 | Enables REST -> RPC converter for HTTP server. Allows you to 72 | call RPC methods with `POST ///`. 73 | The "secure" option requires the `Content-Type: application/json` 74 | header to be sent with the request (even though the payload is ignored) 75 | to prevent accepting POST requests from any website (via form submission). 76 | The "unsecure" option does not require any `Content-Type`. 77 | Possible options: "unsecure", "secure", "disabled"."#, 78 | |value| { 79 | let api = match value.as_str() { 80 | "disabled" | "off" | "no" => http::RestApi::Disabled, 81 | "secure" | "on" | "yes" => http::RestApi::Secure, 82 | "unsecure" => http::RestApi::Unsecure, 83 | _ => return Err(format!("Invalid value for rest-api: {}", value)), 84 | }; 85 | Ok(move |_address: &mut SocketAddr, builder: http::ServerBuilder| Ok(builder.rest_api(api))) 86 | }, 87 | ), 88 | param( 89 | "hosts", 90 | "none", 91 | r#" 92 | List of allowed Host header values. This option will 93 | validate the Host header sent by the browser, it is 94 | additional security against some attack vectors. Special 95 | options: "all", "none"."#, 96 | |value| { 97 | let hosts = match value.as_str() { 98 | "none" => Some(vec![]), 99 | "*" | "all" | "any" => None, 100 | _ => Some(value.split(',').map(Into::into).collect()), 101 | }; 102 | Ok(move |_address: &mut SocketAddr, builder: http::ServerBuilder| { 103 | Ok(builder.allowed_hosts(hosts.clone().into())) 104 | }) 105 | }, 106 | ), 107 | param( 108 | "cors", 109 | "none", 110 | r#" 111 | Specify CORS header for HTTP JSON-RPC API responses. 112 | Special options: "all", "null", "none"."#, 113 | |value| { 114 | let cors = match value.as_str() { 115 | "none" => Some(vec![]), 116 | "*" | "all" | "any" => None, 117 | _ => Some(value.split(',').map(Into::into).collect()), 118 | }; 119 | 120 | Ok(move |_address: &mut SocketAddr, builder: http::ServerBuilder| { 121 | Ok(builder.cors(cors.clone().into())) 122 | }) 123 | }, 124 | ), 125 | param( 126 | "cors-max-age", 127 | "3600000", 128 | r#"Configures AccessControlMaxAge header value in milliseconds. 129 | Informs the client that the preflight request is not required for the specified time. Use 0 to disable."#, 130 | |value| { 131 | let cors_max_age: u32 = value 132 | .parse() 133 | .map_err(|e| format!("Invalid cors max age {}: {}", value, e))?; 134 | 135 | Ok(move |_address: &mut SocketAddr, builder: http::ServerBuilder| { 136 | Ok(builder.cors_max_age(if cors_max_age == 0 { None } else { Some(cors_max_age) })) 137 | }) 138 | }, 139 | ), 140 | param( 141 | "max-payload", 142 | "5", 143 | "Maximal HTTP server payload in Megabytes.", 144 | |value| { 145 | let max_payload: usize = value 146 | .parse() 147 | .map_err(|e| format!("Invalid maximal payload size ({}): {}", value, e))?; 148 | Ok(move |_address: &mut SocketAddr, builder: http::ServerBuilder| { 149 | Ok(builder.max_request_body_size(max_payload * 1024 * 1024)) 150 | }) 151 | }, 152 | ), 153 | ] 154 | } 155 | 156 | /// Starts HTTP server on given handler. 157 | pub fn start(params: Vec>>, io: T) -> io::Result 158 | where 159 | T: Into>, 160 | M: rpc::Metadata + Default + From>>, 161 | S: rpc::Middleware, 162 | S::Future: Unpin, 163 | S::CallFuture: Unpin, 164 | { 165 | let mut builder = http::ServerBuilder::new(io); 166 | let mut address = "127.0.0.1:9934".parse().unwrap(); 167 | 168 | // configure the server 169 | for p in params { 170 | builder = p.configure(&mut address, builder)?; 171 | } 172 | println!("HTTP listening on {}", address); 173 | 174 | builder.start_http(&address) 175 | } 176 | 177 | fn param( 178 | name: &str, 179 | default_value: &str, 180 | description: &str, 181 | parser: F, 182 | ) -> Param>> 183 | where 184 | F: Fn(String) -> Result + 'static, 185 | X: Configurator + 'static, 186 | M: rpc::Metadata, 187 | S: rpc::Middleware, 188 | S::Future: Unpin, 189 | S::CallFuture: Unpin, 190 | { 191 | Param { 192 | category: CATEGORY.into(), 193 | name: format!("{}-{}", PREFIX, name), 194 | description: description.replace('\n', ""), 195 | default_value: default_value.into(), 196 | parser: Box::new(move |val: String| Ok(Box::new(parser(val)?) as _)), 197 | } 198 | } 199 | 200 | /// Configures the HTTP server. 201 | pub trait Configurator 202 | where 203 | M: rpc::Metadata, 204 | S: rpc::Middleware, 205 | { 206 | /// Configure the server. 207 | fn configure( 208 | &self, 209 | address: &mut SocketAddr, 210 | builder: http::ServerBuilder, 211 | ) -> io::Result>; 212 | } 213 | 214 | impl Configurator for F 215 | where 216 | F: Fn(&mut SocketAddr, http::ServerBuilder) -> io::Result>, 217 | M: rpc::Metadata, 218 | S: rpc::Middleware, 219 | { 220 | fn configure( 221 | &self, 222 | address: &mut SocketAddr, 223 | builder: http::ServerBuilder, 224 | ) -> io::Result> { 225 | (*self)(address, builder) 226 | } 227 | } 228 | -------------------------------------------------------------------------------- /proxy/transports/src/ipc.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-2020 jsonrpc-proxy contributors. 2 | // 3 | // This file is part of jsonrpc-proxy 4 | // (see https://github.com/tomusdrw/jsonrpc-proxy). 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | //! IPC server for the proxy. 19 | 20 | use std::{io, sync::Arc}; 21 | 22 | use jsonrpc_ipc_server as ipc; 23 | use params::Param; 24 | use pubsub; 25 | use rpc; 26 | 27 | const CATEGORY: &str = "IPC Server"; 28 | const PREFIX: &str = "ipc"; 29 | 30 | /// Returns CLI configuration options for the IPC server. 31 | pub fn params() -> Vec>>> 32 | where 33 | M: rpc::Metadata, 34 | S: rpc::Middleware, 35 | S::Future: Unpin, 36 | S::CallFuture: Unpin, 37 | { 38 | vec![ 39 | param("path", "./jsonrpc.ipc", "Configures IPC server socket path.", |value| { 40 | Ok(move |path: &mut String, builder| { 41 | *path = value.clone(); 42 | Ok(builder) 43 | }) 44 | }), 45 | param("request-separator", "none", 46 | "Configures TCP server request separator (single byte). If \"none\" the parser will try to figure out requests boundaries.", 47 | |value| { 48 | let separator = match value.as_str() { 49 | "none" => ipc::Separator::Empty, 50 | _ => ipc::Separator::Byte(value.parse().map_err(|e| format!("Invalid separator code {}: {}", value, e))?), 51 | }; 52 | Ok(move |_path: &mut String, builder: ipc::ServerBuilder| { 53 | Ok(builder.request_separators(separator.clone(), separator.clone())) 54 | }) 55 | } 56 | ), 57 | ] 58 | } 59 | 60 | /// Starts IPC server on given handler. 61 | pub fn start(params: Vec>>, io: T) -> io::Result 62 | where 63 | T: Into>, 64 | M: rpc::Metadata + Default + From>>, 65 | S: rpc::Middleware, 66 | S::Future: Unpin, 67 | S::CallFuture: Unpin, 68 | { 69 | let mut builder = ipc::ServerBuilder::with_meta_extractor(io, |context: &ipc::RequestContext| { 70 | Some(Arc::new(pubsub::Session::new(context.sender.clone()))).into() 71 | }); 72 | // should be overwritten by parameters anyway 73 | let mut path = "./jsonrpc.ipc".to_owned(); 74 | // configure the server 75 | for p in params { 76 | builder = p.configure(&mut path, builder)?; 77 | } 78 | 79 | println!("IPC listening at {}", path); 80 | 81 | builder.start(&path) 82 | } 83 | 84 | /// Configures the IPC server. 85 | pub trait Configurator 86 | where 87 | M: rpc::Metadata, 88 | S: rpc::Middleware, 89 | { 90 | /// Configure the server. 91 | fn configure(&self, path: &mut String, builder: ipc::ServerBuilder) -> io::Result>; 92 | } 93 | 94 | impl Configurator for F 95 | where 96 | F: Fn(&mut String, ipc::ServerBuilder) -> io::Result>, 97 | M: rpc::Metadata, 98 | S: rpc::Middleware, 99 | { 100 | fn configure(&self, path: &mut String, builder: ipc::ServerBuilder) -> io::Result> { 101 | (*self)(path, builder) 102 | } 103 | } 104 | 105 | fn param( 106 | name: &str, 107 | default_value: &str, 108 | description: &str, 109 | parser: F, 110 | ) -> Param>> 111 | where 112 | F: Fn(String) -> Result + 'static, 113 | X: Configurator + 'static, 114 | M: rpc::Metadata, 115 | S: rpc::Middleware, 116 | S::Future: Unpin, 117 | S::CallFuture: Unpin, 118 | { 119 | Param { 120 | category: CATEGORY.into(), 121 | name: format!("{}-{}", PREFIX, name), 122 | description: description.replace('\n', " "), 123 | default_value: default_value.into(), 124 | parser: Box::new(move |val: String| Ok(Box::new(parser(val)?) as _)), 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /proxy/transports/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-2020 jsonrpc-proxy contributors. 2 | // 3 | // This file is part of jsonrpc-proxy 4 | // (see https://github.com/tomusdrw/jsonrpc-proxy). 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | //! RPC Proxy servers 19 | 20 | #![warn(missing_docs)] 21 | #![warn(unused_extern_crates)] 22 | 23 | extern crate cli_params as params; 24 | extern crate jsonrpc_core as rpc; 25 | extern crate jsonrpc_pubsub as pubsub; 26 | 27 | extern crate jsonrpc_http_server; 28 | extern crate jsonrpc_ipc_server; 29 | extern crate jsonrpc_tcp_server; 30 | extern crate jsonrpc_ws_server; 31 | 32 | pub mod http; 33 | pub mod ipc; 34 | pub mod tcp; 35 | pub mod ws; 36 | -------------------------------------------------------------------------------- /proxy/transports/src/tcp.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-2020 jsonrpc-proxy contributors. 2 | // 3 | // This file is part of jsonrpc-proxy 4 | // (see https://github.com/tomusdrw/jsonrpc-proxy). 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | //! TCP server for the proxy. 19 | 20 | use std::{ 21 | io, 22 | net::{Ipv4Addr, SocketAddr}, 23 | sync::Arc, 24 | }; 25 | 26 | use jsonrpc_tcp_server as tcp; 27 | use params::Param; 28 | use pubsub; 29 | use rpc; 30 | 31 | const CATEGORY: &str = "TCP Server"; 32 | const PREFIX: &str = "tcp"; 33 | 34 | /// Returns CLI configuration options for the TCP server. 35 | pub fn params() -> Vec>>> 36 | where 37 | M: rpc::Metadata, 38 | S: rpc::Middleware, 39 | S::Future: Unpin, 40 | S::CallFuture: Unpin, 41 | { 42 | vec![ 43 | param("port", "9955", "Configures TCP server listening port.", |value| { 44 | let port: u16 = value.parse().map_err(|e| format!("Invalid port number {}: {}", value, e))?; 45 | Ok(move |address: &mut SocketAddr, builder| { 46 | address.set_port(port); 47 | Ok(builder) 48 | }) 49 | }), 50 | param("ip", "127.0.0.1", "Configures TCP server interface.", |value| { 51 | let ip: Ipv4Addr = value.parse().map_err(|e| format!("Invalid port number {}: {}", value, e))?; 52 | Ok(move |address: &mut SocketAddr, builder| { 53 | address.set_ip(ip.into()); 54 | Ok(builder) 55 | }) 56 | }), 57 | param("request-separator", "10", 58 | "Configures TCP server request separator (single byte). If \"none\" the parser will try to figure out requests boundaries. Default is new line character.", 59 | |value| { 60 | let separator = match value.as_str() { 61 | "none" => tcp::Separator::Empty, 62 | _ => tcp::Separator::Byte(value.parse().map_err(|e| format!("Invalid separator code {}: {}", value, e))?), 63 | }; 64 | Ok(move |_address: &mut SocketAddr, builder: tcp::ServerBuilder| { 65 | Ok(builder.request_separators(separator.clone(), separator.clone())) 66 | }) 67 | } 68 | ), 69 | ] 70 | } 71 | 72 | /// Starts TCP server on given handler. 73 | pub fn start(params: Vec>>, io: T) -> io::Result 74 | where 75 | T: Into>, 76 | M: rpc::Metadata + Default + From>>, 77 | S: rpc::Middleware, 78 | S::Future: Unpin, 79 | S::CallFuture: Unpin, 80 | { 81 | let mut builder = tcp::ServerBuilder::with_meta_extractor(io, |context: &tcp::RequestContext| { 82 | Some(Arc::new(pubsub::Session::new(context.sender.clone()))).into() 83 | }); 84 | // should be overwritten by parameters anyway 85 | let mut address = "127.0.0.1:9955".parse().unwrap(); 86 | // configure the server 87 | for p in params { 88 | builder = p.configure(&mut address, builder)?; 89 | } 90 | 91 | println!("TCP listening on {}", address); 92 | 93 | builder.start(&address) 94 | } 95 | 96 | /// Configures the TCP server. 97 | pub trait Configurator 98 | where 99 | M: rpc::Metadata, 100 | S: rpc::Middleware, 101 | { 102 | /// Configure the server. 103 | fn configure( 104 | &self, 105 | address: &mut SocketAddr, 106 | builder: tcp::ServerBuilder, 107 | ) -> io::Result>; 108 | } 109 | 110 | impl Configurator for F 111 | where 112 | F: Fn(&mut SocketAddr, tcp::ServerBuilder) -> io::Result>, 113 | M: rpc::Metadata, 114 | S: rpc::Middleware, 115 | { 116 | fn configure( 117 | &self, 118 | address: &mut SocketAddr, 119 | builder: tcp::ServerBuilder, 120 | ) -> io::Result> { 121 | (*self)(address, builder) 122 | } 123 | } 124 | 125 | fn param( 126 | name: &str, 127 | default_value: &str, 128 | description: &str, 129 | parser: F, 130 | ) -> Param>> 131 | where 132 | F: Fn(String) -> Result + 'static, 133 | X: Configurator + 'static, 134 | M: rpc::Metadata, 135 | S: rpc::Middleware, 136 | S::Future: Unpin, 137 | S::CallFuture: Unpin, 138 | { 139 | Param { 140 | category: CATEGORY.into(), 141 | name: format!("{}-{}", PREFIX, name), 142 | description: description.replace('\n', " "), 143 | default_value: default_value.into(), 144 | parser: Box::new(move |val: String| Ok(Box::new(parser(val)?) as _)), 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /proxy/transports/src/ws.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-2020 jsonrpc-proxy contributors. 2 | // 3 | // This file is part of jsonrpc-proxy 4 | // (see https://github.com/tomusdrw/jsonrpc-proxy). 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | //! WebSockets server for the proxy. 19 | 20 | use std::{ 21 | net::{Ipv4Addr, SocketAddr}, 22 | sync::Arc, 23 | }; 24 | 25 | use jsonrpc_ws_server as ws; 26 | use params::Param; 27 | use pubsub; 28 | use rpc; 29 | 30 | const CATEGORY: &str = "WebSockets Server"; 31 | const PREFIX: &str = "websockets"; 32 | 33 | /// Returns CLI configuration options for the WS server. 34 | pub fn params() -> Vec>>> 35 | where 36 | M: rpc::Metadata, 37 | S: rpc::Middleware, 38 | S::Future: Unpin, 39 | S::CallFuture: Unpin, 40 | { 41 | vec![ 42 | param( 43 | "port", 44 | "9945", 45 | "Configures WebSockets server listening port.", 46 | |value| { 47 | let port: u16 = value 48 | .parse() 49 | .map_err(|e| format!("Invalid port number {}: {}", value, e))?; 50 | Ok(move |address: &mut SocketAddr, builder| { 51 | address.set_port(port); 52 | Ok(builder) 53 | }) 54 | }, 55 | ), 56 | param("ip", "127.0.0.1", "Configures WebSockets server interface.", |value| { 57 | let ip: Ipv4Addr = value 58 | .parse() 59 | .map_err(|e| format!("Invalid port number {}: {}", value, e))?; 60 | Ok(move |address: &mut SocketAddr, builder| { 61 | address.set_ip(ip.into()); 62 | Ok(builder) 63 | }) 64 | }), 65 | param( 66 | "hosts", 67 | "none", 68 | r#" 69 | List of allowed Host header values. This option will 70 | validate the Host header sent by the browser, it is 71 | additional security against some attack vectors. Special 72 | options: "all", "none"."#, 73 | |value| { 74 | let hosts = match value.as_str() { 75 | "none" => Some(vec![]), 76 | "*" | "all" | "any" => None, 77 | _ => Some(value.split(',').map(Into::into).collect()), 78 | }; 79 | Ok(move |_address: &mut SocketAddr, builder: ws::ServerBuilder| { 80 | Ok(builder.allowed_hosts(hosts.clone().into())) 81 | }) 82 | }, 83 | ), 84 | param( 85 | "origins", 86 | "none", 87 | r#" 88 | Specify Origin header values allowed to connect. Special 89 | options: "all", "none". "#, 90 | |value| { 91 | let origins = match value.as_str() { 92 | "none" => Some(vec![]), 93 | "*" | "all" | "any" => None, 94 | _ => Some(value.split(',').map(Into::into).collect()), 95 | }; 96 | 97 | Ok(move |_address: &mut SocketAddr, builder: ws::ServerBuilder| { 98 | Ok(builder.allowed_origins(origins.clone().into())) 99 | }) 100 | }, 101 | ), 102 | param( 103 | "max-connections", 104 | "100", 105 | "Maximum number of allowed concurrent WebSockets JSON-RPC connections.", 106 | |value| { 107 | let max_connections: usize = value 108 | .parse() 109 | .map_err(|e| format!("Invalid number of connections {}: {}", value, e))?; 110 | Ok(move |_address: &mut SocketAddr, builder: ws::ServerBuilder| { 111 | Ok(builder.max_connections(max_connections)) 112 | }) 113 | }, 114 | ), 115 | ] 116 | } 117 | 118 | /// Starts WebSockets server on given handler. 119 | pub fn start(params: Vec>>, io: T) -> ws::Result 120 | where 121 | T: Into>, 122 | M: rpc::Metadata + Default + From>>, 123 | S: rpc::Middleware, 124 | S::Future: Unpin, 125 | S::CallFuture: Unpin, 126 | { 127 | let mut builder = ws::ServerBuilder::with_meta_extractor(io, |context: &ws::RequestContext| { 128 | Some(Arc::new(pubsub::Session::new(context.sender()))).into() 129 | }); 130 | // should be overwritten by parameters anyway 131 | let mut address = "127.0.0.1:9945".parse().unwrap(); 132 | // configure the server 133 | for p in params { 134 | builder = p.configure(&mut address, builder)?; 135 | } 136 | 137 | println!("WS listening on {}", address); 138 | 139 | builder.start(&address) 140 | } 141 | 142 | /// Configures the WS server. 143 | pub trait Configurator 144 | where 145 | M: rpc::Metadata, 146 | S: rpc::Middleware, 147 | { 148 | /// Configure the server. 149 | fn configure( 150 | &self, 151 | address: &mut SocketAddr, 152 | builder: ws::ServerBuilder, 153 | ) -> ws::Result>; 154 | } 155 | 156 | impl Configurator for F 157 | where 158 | F: Fn(&mut SocketAddr, ws::ServerBuilder) -> ws::Result>, 159 | M: rpc::Metadata, 160 | S: rpc::Middleware, 161 | { 162 | fn configure( 163 | &self, 164 | address: &mut SocketAddr, 165 | builder: ws::ServerBuilder, 166 | ) -> ws::Result> { 167 | (*self)(address, builder) 168 | } 169 | } 170 | 171 | fn param( 172 | name: &str, 173 | default_value: &str, 174 | description: &str, 175 | parser: F, 176 | ) -> Param>> 177 | where 178 | F: Fn(String) -> Result + 'static, 179 | X: Configurator + 'static, 180 | M: rpc::Metadata, 181 | S: rpc::Middleware, 182 | S::Future: Unpin, 183 | S::CallFuture: Unpin, 184 | { 185 | Param { 186 | category: CATEGORY.into(), 187 | name: format!("{}-{}", PREFIX, name), 188 | description: description.replace('\n', " "), 189 | default_value: default_value.into(), 190 | parser: Box::new(move |val: String| Ok(Box::new(parser(val)?) as _)), 191 | } 192 | } 193 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | max_width = 120 2 | #merge_imports = true 3 | -------------------------------------------------------------------------------- /substrate-proxy/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "substrate-proxy" 3 | version = "0.1.0" 4 | authors = ["Tomasz Drwięga "] 5 | license = "GPL-3.0-or-later" 6 | edition = "2018" 7 | 8 | [dependencies] 9 | clap = { version = "2.33", features = ["yaml"] } 10 | rpc-proxy = { path = "../generic-proxy" } 11 | simple-cache = { path = "../plugins/simple-cache" } 12 | tokio = { version = "1.13", features = ["macros"] } 13 | upstream = { path = "../plugins/upstream" } 14 | -------------------------------------------------------------------------------- /substrate-proxy/src/cli.yml: -------------------------------------------------------------------------------- 1 | ## 2 | ## Copyright (c) 2018-2020 jsonrpc-proxy contributors. 3 | ## 4 | ## This file is part of jsonrpc-proxy 5 | ## (see https://github.com/tomusdrw/jsonrpc-proxy). 6 | ## 7 | ## This program is free software: you can redistribute it and/or modify 8 | ## it under the terms of the GNU General Public License as published by 9 | ## the Free Software Foundation, either version 3 of the License, or 10 | ## (at your option) any later version. 11 | ## 12 | ## This program is distributed in the hope that it will be useful, 13 | ## but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | ## GNU General Public License for more details. 16 | ## 17 | ## You should have received a copy of the GNU General Public License 18 | ## along with this program. If not, see . 19 | ## 20 | name: substrate-proxy 21 | version: "0.1" 22 | about: Substrate JSON-RPC proxy. 23 | author: Parity Technologies Ltd 24 | 25 | -------------------------------------------------------------------------------- /substrate-proxy/src/main.rs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2018-2020 jsonrpc-proxy contributors. 2 | // 3 | // This file is part of jsonrpc-proxy 4 | // (see https://github.com/tomusdrw/jsonrpc-proxy). 5 | // 6 | // This program is free software: you can redistribute it and/or modify 7 | // it under the terms of the GNU General Public License as published by 8 | // the Free Software Foundation, either version 3 of the License, or 9 | // (at your option) any later version. 10 | // 11 | // This program is distributed in the hope that it will be useful, 12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | // GNU General Public License for more details. 15 | // 16 | // You should have received a copy of the GNU General Public License 17 | // along with this program. If not, see . 18 | //! JSON-RPC proxy suitable for Substrate nodes. 19 | //! 20 | //! The proxy contains a pre-configured list of cacheable methods and upstream subscriptions. 21 | 22 | #![warn(missing_docs)] 23 | 24 | #[tokio::main] 25 | async fn main() { 26 | let yml = clap::load_yaml!("./cli.yml"); 27 | let app = clap::App::from_yaml(yml).set_term_width(80); 28 | 29 | generic_proxy::run_app( 30 | app, 31 | vec![ 32 | // author 33 | cache("author_pendingExtrinsics"), 34 | // chain 35 | cache("chain_getHeader"), 36 | cache("chain_getBlock"), 37 | cache("chain_getBlockHash"), 38 | cache("chain_getHead"), 39 | cache("chain_getRuntimeVersion"), 40 | // state 41 | cache("state_call"), 42 | cache("state_callAt"), 43 | cache("state_getStorage"), 44 | cache("state_getStorageAt"), 45 | cache("state_getStorageHash"), 46 | cache("state_getStorageHashAt"), 47 | cache("state_getStorageSize"), 48 | cache("state_getStorageSizeAt"), 49 | cache("state_queryStorage"), 50 | // system 51 | cache("system_name"), 52 | cache("system_version"), 53 | cache("system_chain"), 54 | ], 55 | vec![ 56 | upstream::Subscription { 57 | subscribe: "author_submitAndWatchExtrinsic".into(), 58 | unsubscribe: "author_unwatchExtrinsic".into(), 59 | name: "author_extrinsicUpdate".into(), 60 | }, 61 | upstream::Subscription { 62 | subscribe: "chain_subscribeNewHead".into(), 63 | unsubscribe: "chain_unsubscribeNewHead".into(), 64 | name: "chain_newHead".into(), 65 | }, 66 | upstream::Subscription { 67 | subscribe: "state_subscribeStorage".into(), 68 | unsubscribe: "state_unsubscribeStorage".into(), 69 | name: "state_storage".into(), 70 | }, 71 | ], 72 | (), 73 | ) 74 | } 75 | 76 | fn cache(name: &str) -> simple_cache::Method { 77 | simple_cache::Method::new( 78 | name, 79 | simple_cache::CacheEviction::Time(::std::time::Duration::from_secs(3)), 80 | ) 81 | } 82 | --------------------------------------------------------------------------------