From 7d62e8fc0d1c79e2ff5268d77584153256d4f769 Mon Sep 17 00:00:00 2001 From: Simon Warta Date: Wed, 6 Apr 2022 23:25:50 +0200 Subject: [PATCH 1/5] Create HttpEndpoint interface --- packages/cli/examples/figment.ts | 21 ++++++++ packages/cli/run_examples.sh | 3 ++ .../cosmwasm-stargate/src/cosmwasmclient.ts | 4 +- packages/cosmwasm-stargate/src/index.ts | 3 ++ .../src/signingcosmwasmclient.ts | 4 +- packages/stargate/src/index.ts | 3 ++ .../stargate/src/signingstargateclient.ts | 4 +- packages/stargate/src/stargateclient.ts | 4 +- packages/tendermint-rpc/src/index.ts | 4 ++ .../src/rpcclients/httpclient.spec.ts | 4 +- .../src/rpcclients/httpclient.ts | 48 ++++++++++++++++--- .../tendermint-rpc/src/rpcclients/index.ts | 2 +- .../src/tendermint34/tendermint34client.ts | 13 +++-- 13 files changed, 95 insertions(+), 22 deletions(-) create mode 100644 packages/cli/examples/figment.ts diff --git a/packages/cli/examples/figment.ts b/packages/cli/examples/figment.ts new file mode 100644 index 00000000..8a7592ef --- /dev/null +++ b/packages/cli/examples/figment.ts @@ -0,0 +1,21 @@ +import { StargateClient } from "@cosmjs/stargate"; + +// Network config +const rpcEndpoint = { + // Note: we removed the /status patch from the examples because we use the HTTP POST API + url: "https://cosmoshub-4--rpc--full.datahub.figment.io/", + headers: { + "Authorization": "5195ebb0bfb7f0fe5c43409240c8b2c4", + } +}; + +// Setup client +const client = await StargateClient.connect(rpcEndpoint); + +// Get some data +const chainId = await client.getChainId(); +console.log("Chain ID:", chainId); +const balance = await client.getAllBalances("cosmos1ey69r37gfxvxg62sh4r0ktpuc46pzjrmz29g45"); +console.log("Balances:", balance); + +client.disconnect(); diff --git a/packages/cli/run_examples.sh b/packages/cli/run_examples.sh index 73dbafb2..5e301bca 100755 --- a/packages/cli/run_examples.sh +++ b/packages/cli/run_examples.sh @@ -17,3 +17,6 @@ if [ -n "${SIMAPP42_ENABLED:-}" ]; then yarn node ./bin/cosmjs-cli --init examples/stargate.ts --code "process.exit(0)" yarn node ./bin/cosmjs-cli --init examples/simulate.ts --code "process.exit(0)" fi + +# Disabled as this requires internet access +# yarn node ./bin/cosmjs-cli --init examples/figment.ts --code "process.exit(0)" diff --git a/packages/cosmwasm-stargate/src/cosmwasmclient.ts b/packages/cosmwasm-stargate/src/cosmwasmclient.ts index e09c76e7..c308c598 100644 --- a/packages/cosmwasm-stargate/src/cosmwasmclient.ts +++ b/packages/cosmwasm-stargate/src/cosmwasmclient.ts @@ -23,7 +23,7 @@ import { TimeoutError, TxExtension, } from "@cosmjs/stargate"; -import { Tendermint34Client, toRfc3339WithNanoseconds } from "@cosmjs/tendermint-rpc"; +import { HttpEndpoint, Tendermint34Client, toRfc3339WithNanoseconds } from "@cosmjs/tendermint-rpc"; import { assert, sleep } from "@cosmjs/utils"; import { CodeInfoResponse, @@ -89,7 +89,7 @@ export class CosmWasmClient { private readonly codesCache = new Map(); private chainId: string | undefined; - public static async connect(endpoint: string): Promise { + public static async connect(endpoint: string | HttpEndpoint): Promise { const tmClient = await Tendermint34Client.connect(endpoint); return new CosmWasmClient(tmClient); } diff --git a/packages/cosmwasm-stargate/src/index.ts b/packages/cosmwasm-stargate/src/index.ts index 91ab2f30..49908b5d 100644 --- a/packages/cosmwasm-stargate/src/index.ts +++ b/packages/cosmwasm-stargate/src/index.ts @@ -29,3 +29,6 @@ export { SigningCosmWasmClientOptions, UploadResult, } from "./signingcosmwasmclient"; + +// Re-exported because this is part of the CosmWasmClient/SigningCosmWasmClient APIs +export { HttpEndpoint } from "@cosmjs/tendermint-rpc"; diff --git a/packages/cosmwasm-stargate/src/signingcosmwasmclient.ts b/packages/cosmwasm-stargate/src/signingcosmwasmclient.ts index 1e940d88..69e2d71d 100644 --- a/packages/cosmwasm-stargate/src/signingcosmwasmclient.ts +++ b/packages/cosmwasm-stargate/src/signingcosmwasmclient.ts @@ -30,7 +30,7 @@ import { SignerData, StdFee, } from "@cosmjs/stargate"; -import { Tendermint34Client } from "@cosmjs/tendermint-rpc"; +import { HttpEndpoint, Tendermint34Client } from "@cosmjs/tendermint-rpc"; import { assert, assertDefined } from "@cosmjs/utils"; import { MsgWithdrawDelegatorReward } from "cosmjs-types/cosmos/distribution/v1beta1/tx"; import { MsgDelegate, MsgUndelegate } from "cosmjs-types/cosmos/staking/v1beta1/tx"; @@ -172,7 +172,7 @@ export class SigningCosmWasmClient extends CosmWasmClient { private readonly gasPrice: GasPrice | undefined; public static async connectWithSigner( - endpoint: string, + endpoint: string | HttpEndpoint, signer: OfflineSigner, options: SigningCosmWasmClientOptions = {}, ): Promise { diff --git a/packages/stargate/src/index.ts b/packages/stargate/src/index.ts index 6af58edc..f3cd17f1 100644 --- a/packages/stargate/src/index.ts +++ b/packages/stargate/src/index.ts @@ -122,3 +122,6 @@ export { } from "./stargateclient"; export { StdFee } from "@cosmjs/amino"; export { Coin, coin, coins, makeCosmoshubPath, parseCoins } from "@cosmjs/proto-signing"; + +// Re-exported because this is part of the StargateClient/SigningStargateClient APIs +export { HttpEndpoint } from "@cosmjs/tendermint-rpc"; diff --git a/packages/stargate/src/signingstargateclient.ts b/packages/stargate/src/signingstargateclient.ts index e0e13c5a..9dec3293 100644 --- a/packages/stargate/src/signingstargateclient.ts +++ b/packages/stargate/src/signingstargateclient.ts @@ -12,7 +12,7 @@ import { Registry, TxBodyEncodeObject, } from "@cosmjs/proto-signing"; -import { Tendermint34Client } from "@cosmjs/tendermint-rpc"; +import { HttpEndpoint, Tendermint34Client } from "@cosmjs/tendermint-rpc"; import { assert, assertDefined } from "@cosmjs/utils"; import { Coin } from "cosmjs-types/cosmos/base/v1beta1/coin"; import { MsgWithdrawDelegatorReward } from "cosmjs-types/cosmos/distribution/v1beta1/tx"; @@ -116,7 +116,7 @@ export class SigningStargateClient extends StargateClient { private readonly gasPrice: GasPrice | undefined; public static async connectWithSigner( - endpoint: string, + endpoint: string | HttpEndpoint, signer: OfflineSigner, options: SigningStargateClientOptions = {}, ): Promise { diff --git a/packages/stargate/src/stargateclient.ts b/packages/stargate/src/stargateclient.ts index bbbfa251..859408b0 100644 --- a/packages/stargate/src/stargateclient.ts +++ b/packages/stargate/src/stargateclient.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/naming-convention */ import { toHex } from "@cosmjs/encoding"; import { Uint53 } from "@cosmjs/math"; -import { Tendermint34Client, toRfc3339WithNanoseconds } from "@cosmjs/tendermint-rpc"; +import { HttpEndpoint, Tendermint34Client, toRfc3339WithNanoseconds } from "@cosmjs/tendermint-rpc"; import { sleep } from "@cosmjs/utils"; import { MsgData } from "cosmjs-types/cosmos/base/abci/v1beta1/abci"; import { Coin } from "cosmjs-types/cosmos/base/v1beta1/coin"; @@ -149,7 +149,7 @@ export class StargateClient { private readonly accountParser: AccountParser; public static async connect( - endpoint: string, + endpoint: string | HttpEndpoint, options: StargateClientOptions = {}, ): Promise { const tmClient = await Tendermint34Client.connect(endpoint); diff --git a/packages/tendermint-rpc/src/index.ts b/packages/tendermint-rpc/src/index.ts index e56a3e5c..98515b4d 100644 --- a/packages/tendermint-rpc/src/index.ts +++ b/packages/tendermint-rpc/src/index.ts @@ -12,6 +12,10 @@ export { toRfc3339WithNanoseconds, toSeconds, } from "./dates"; +export { + // This type is part of the Tendermint34Client.connect API + HttpEndpoint, +} from "./rpcclients"; export { HttpClient, WebsocketClient } from "./rpcclients"; // TODO: Why do we export those outside of this package? export { AbciInfoRequest, diff --git a/packages/tendermint-rpc/src/rpcclients/httpclient.spec.ts b/packages/tendermint-rpc/src/rpcclients/httpclient.spec.ts index add473e9..a73972c8 100644 --- a/packages/tendermint-rpc/src/rpcclients/httpclient.spec.ts +++ b/packages/tendermint-rpc/src/rpcclients/httpclient.spec.ts @@ -13,13 +13,13 @@ const tendermintUrl = defaultInstance.url; describe("http", () => { it("can send a health request", async () => { pendingWithoutTendermint(); - const response = await http("POST", `http://${tendermintUrl}`, createJsonRpcRequest("health")); + const response = await http("POST", `http://${tendermintUrl}`, undefined, createJsonRpcRequest("health")); expect(response).toEqual(jasmine.objectContaining({ jsonrpc: "2.0" })); }); it("errors for non-open port", async () => { await expectAsync( - http("POST", `http://localhost:56745`, createJsonRpcRequest("health")), + http("POST", `http://localhost:56745`, undefined, createJsonRpcRequest("health")), ).toBeRejectedWithError(/(ECONNREFUSED|Failed to fetch)/i); }); }); diff --git a/packages/tendermint-rpc/src/rpcclients/httpclient.ts b/packages/tendermint-rpc/src/rpcclients/httpclient.ts index 293842df..83dd81bb 100644 --- a/packages/tendermint-rpc/src/rpcclients/httpclient.ts +++ b/packages/tendermint-rpc/src/rpcclients/httpclient.ts @@ -11,6 +11,8 @@ import { hasProtocol, RpcClient } from "./rpcclient"; // Global symbols in some environments // https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch declare const fetch: any | undefined; +// eslint-disable-next-line @typescript-eslint/naming-convention +declare const Headers: any | undefined; function filterBadStatus(res: any): any { if (res.status >= 400) { @@ -25,23 +27,55 @@ function filterBadStatus(res: any): any { * For some reason, fetch does not complain about missing server-side CORS support. */ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types -export async function http(method: "POST", url: string, request?: any): Promise { +export async function http( + method: "POST", + url: string, + headers: Record | undefined, + request?: any, +): Promise { if (typeof fetch !== "undefined") { const body = request ? JSON.stringify(request) : undefined; - return fetch(url, { method: method, body: body }) + const settings = { + method: method, + body: body, + headers: headers ? new Headers(headers) : undefined, + }; + return fetch(url, settings) .then(filterBadStatus) .then((res: any) => res.json()); } else { - return axios.request({ url: url, method: method, data: request }).then((res) => res.data); + return axios + .request({ url: url, method: method, data: request, headers: headers }) + .then((res) => res.data); } } +export interface HttpEndpoint { + /** + * The URL of the HTTP endpoint. + * + * For POST APIs like Tendermint RPC in CosmJS, + * this is without the method specific paths (e.g. https://cosmoshub-4--rpc--full.datahub.figment.io/) + */ + readonly url: string; + /** + * HTTP headers that are sent with every request, such as authorization information. + */ + readonly headers: Record; +} + export class HttpClient implements RpcClient { protected readonly url: string; + protected readonly headers: Record | undefined; - public constructor(url: string) { - // accept host.name:port and assume http protocol - this.url = hasProtocol(url) ? url : "http://" + url; + public constructor(endpoint: string | HttpEndpoint) { + if (typeof endpoint === "string") { + // accept host.name:port and assume http protocol + this.url = hasProtocol(endpoint) ? endpoint : "http://" + endpoint; + } else { + this.url = endpoint.url; + this.headers = endpoint.headers; + } } public disconnect(): void { @@ -49,7 +83,7 @@ export class HttpClient implements RpcClient { } public async execute(request: JsonRpcRequest): Promise { - const response = parseJsonRpcResponse(await http("POST", this.url, request)); + const response = parseJsonRpcResponse(await http("POST", this.url, this.headers, request)); if (isJsonRpcErrorResponse(response)) { throw new Error(JSON.stringify(response.error)); } diff --git a/packages/tendermint-rpc/src/rpcclients/index.ts b/packages/tendermint-rpc/src/rpcclients/index.ts index 31cff4b0..bff29531 100644 --- a/packages/tendermint-rpc/src/rpcclients/index.ts +++ b/packages/tendermint-rpc/src/rpcclients/index.ts @@ -1,5 +1,5 @@ // This folder contains Tendermint-specific RPC clients -export { HttpClient } from "./httpclient"; +export { HttpClient, HttpEndpoint } from "./httpclient"; export { instanceOfRpcStreamingClient, RpcClient, RpcStreamingClient, SubscriptionEvent } from "./rpcclient"; export { WebsocketClient } from "./websocketclient"; diff --git a/packages/tendermint-rpc/src/tendermint34/tendermint34client.ts b/packages/tendermint-rpc/src/tendermint34/tendermint34client.ts index 05176d60..a0220eb4 100644 --- a/packages/tendermint-rpc/src/tendermint34/tendermint34client.ts +++ b/packages/tendermint-rpc/src/tendermint34/tendermint34client.ts @@ -4,6 +4,7 @@ import { Stream } from "xstream"; import { createJsonRpcRequest } from "../jsonrpc"; import { HttpClient, + HttpEndpoint, instanceOfRpcStreamingClient, RpcClient, SubscriptionEvent, @@ -19,10 +20,14 @@ export class Tendermint34Client { * * Uses HTTP when the URL schema is http or https. Uses WebSockets otherwise. */ - public static async connect(url: string): Promise { - const useHttp = url.startsWith("http://") || url.startsWith("https://"); - const rpcClient = useHttp ? new HttpClient(url) : new WebsocketClient(url); - return Tendermint34Client.create(rpcClient); + public static async connect(endpoint: string | HttpEndpoint): Promise { + if (typeof endpoint === "object") { + return Tendermint34Client.create(new HttpClient(endpoint)); + } else { + const useHttp = endpoint.startsWith("http://") || endpoint.startsWith("https://"); + const rpcClient = useHttp ? new HttpClient(endpoint) : new WebsocketClient(endpoint); + return Tendermint34Client.create(rpcClient); + } } /** From 2a8433a06dc2137ab86d5bb1e4ffbe0e7337246f Mon Sep 17 00:00:00 2001 From: Simon Warta Date: Tue, 12 Apr 2022 16:07:07 +0200 Subject: [PATCH 2/5] Add CHANGELOG entry for custom HTTP headers --- CHANGELOG.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c278ae6b..2bc18d85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,7 +14,16 @@ and this project adheres to - @cosmjs/faucet: Docker build image is 90 % smaller now (from 500 MB to 50 MB) due to build system optimizations ([#1120], [#1121]). +- @cosmjs/cosmwasm-stargate: `CosmWasmClient.connect` and + `SigningCosmWasmClient.connectWithSigner` now accept custom HTTP headers + ([#1007]) +- @cosmjs/stargate: `StargateClient.connect` and + `SigningStargateClient.connectWithSigner` now accept custom HTTP headers + ([#1007]) +- @cosmjs/tendermint-rpc: `Tendermint34Client.connect` now accepts custom HTTP + headers ([#1007]). +[#1007]: https://github.com/cosmos/cosmjs/issues/1007 [#1110]: https://github.com/cosmos/cosmjs/issues/1110 [#1120]: https://github.com/cosmos/cosmjs/pull/1120 [#1121]: https://github.com/cosmos/cosmjs/pull/1121 From e5947cf650eb8578c713b5abd3785b9e5d0edec9 Mon Sep 17 00:00:00 2001 From: Simon Warta Date: Tue, 12 Apr 2022 17:55:10 +0200 Subject: [PATCH 3/5] Fix spelling of Tendermint RPC --- packages/tendermint-rpc/src/rpcclients/httpclient.spec.ts | 2 +- packages/tendermint-rpc/src/rpcclients/rpcclient.spec.ts | 2 +- packages/tendermint-rpc/src/rpcclients/websocketclient.spec.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/tendermint-rpc/src/rpcclients/httpclient.spec.ts b/packages/tendermint-rpc/src/rpcclients/httpclient.spec.ts index a73972c8..66295e33 100644 --- a/packages/tendermint-rpc/src/rpcclients/httpclient.spec.ts +++ b/packages/tendermint-rpc/src/rpcclients/httpclient.spec.ts @@ -4,7 +4,7 @@ import { http, HttpClient } from "./httpclient"; function pendingWithoutTendermint(): void { if (!process.env.TENDERMINT_ENABLED) { - pending("Set TENDERMINT_ENABLED to enable tendermint rpc tests"); + pending("Set TENDERMINT_ENABLED to enable Tendermint RPC tests"); } } diff --git a/packages/tendermint-rpc/src/rpcclients/rpcclient.spec.ts b/packages/tendermint-rpc/src/rpcclients/rpcclient.spec.ts index c55cd751..a5fb0310 100644 --- a/packages/tendermint-rpc/src/rpcclients/rpcclient.spec.ts +++ b/packages/tendermint-rpc/src/rpcclients/rpcclient.spec.ts @@ -6,7 +6,7 @@ import { WebsocketClient } from "./websocketclient"; function pendingWithoutTendermint(): void { if (!process.env.TENDERMINT_ENABLED) { - pending("Set TENDERMINT_ENABLED to enable tendermint rpc tests"); + pending("Set TENDERMINT_ENABLED to enable Tendermint RPC tests"); } } diff --git a/packages/tendermint-rpc/src/rpcclients/websocketclient.spec.ts b/packages/tendermint-rpc/src/rpcclients/websocketclient.spec.ts index d8496af4..8c88a450 100644 --- a/packages/tendermint-rpc/src/rpcclients/websocketclient.spec.ts +++ b/packages/tendermint-rpc/src/rpcclients/websocketclient.spec.ts @@ -9,7 +9,7 @@ import { WebsocketClient } from "./websocketclient"; function pendingWithoutTendermint(): void { if (!process.env.TENDERMINT_ENABLED) { - pending("Set TENDERMINT_ENABLED to enable tendermint rpc tests"); + pending("Set TENDERMINT_ENABLED to enable Tendermint RPC tests"); } } From b8d7db931170806c805cfcee935db3192d9529a6 Mon Sep 17 00:00:00 2001 From: Simon Warta Date: Tue, 12 Apr 2022 17:57:45 +0200 Subject: [PATCH 4/5] Create httpserver --- .circleci/config.yml | 22 +++++++++++++++ HACKING.md | 7 +++++ scripts/httpserver/Dockerfile | 7 +++++ scripts/httpserver/echo.py | 53 +++++++++++++++++++++++++++++++++++ scripts/httpserver/start.sh | 31 ++++++++++++++++++++ scripts/httpserver/stop.sh | 8 ++++++ 6 files changed, 128 insertions(+) create mode 100644 scripts/httpserver/Dockerfile create mode 100755 scripts/httpserver/echo.py create mode 100755 scripts/httpserver/start.sh create mode 100755 scripts/httpserver/stop.sh diff --git a/.circleci/config.yml b/.circleci/config.yml index fb4cfedb..f0d1ba0c 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -145,9 +145,13 @@ jobs: - run: name: Start socket server command: ./scripts/socketserver/start.sh + - run: + name: Start http server + command: ./scripts/httpserver/start.sh - run: name: Run tests environment: + HTTPSERVER_ENABLED: 1 TENDERMINT_ENABLED: 1 SOCKETSERVER_ENABLED: 1 SKIP_BUILD: 1 @@ -166,6 +170,7 @@ jobs: name: Run CLI examples working_directory: packages/cli environment: + HTTPSERVER_ENABLED: 1 TENDERMINT_ENABLED: 1 SOCKETSERVER_ENABLED: 1 SKIP_BUILD: 1 @@ -177,6 +182,7 @@ jobs: - run: name: Stop chains command: | + ./scripts/httpserver/stop.sh ./scripts/socketserver/stop.sh ./scripts/tendermint/all_stop.sh ./scripts/<< parameters.simapp >>/stop.sh @@ -265,8 +271,12 @@ jobs: - run: name: Start socket server command: ./scripts/socketserver/start.sh + - run: + name: Start http server + command: ./scripts/httpserver/start.sh - run: environment: + HTTPSERVER_ENABLED: 1 SIMAPP42_ENABLED: 1 SLOW_SIMAPP42_ENABLED: 1 TENDERMINT_ENABLED: 1 @@ -285,6 +295,7 @@ jobs: name: Run CLI examples working_directory: packages/cli environment: + HTTPSERVER_ENABLED: 1 SIMAPP42_ENABLED: 1 SLOW_SIMAPP42_ENABLED: 1 TENDERMINT_ENABLED: 1 @@ -295,6 +306,7 @@ jobs: - run: name: Stop chains command: | + ./scripts/httpserver/stop.sh ./scripts/socketserver/stop.sh ./scripts/tendermint/all_stop.sh ./scripts/simapp42/stop.sh @@ -376,8 +388,12 @@ jobs: - run: name: Start socket server command: ./scripts/socketserver/start.sh + - run: + name: Start http server + command: ./scripts/httpserver/start.sh - run: environment: + HTTPSERVER_ENABLED: 1 SIMAPP42_ENABLED: 1 SLOW_SIMAPP42_ENABLED: 1 TENDERMINT_ENABLED: 1 @@ -388,6 +404,7 @@ jobs: - run: name: Stop chains command: | + ./scripts/httpserver/stop.sh ./scripts/socketserver/stop.sh ./scripts/tendermint/all_stop.sh ./scripts/simapp42/stop.sh @@ -468,8 +485,12 @@ jobs: - run: name: Start socket server command: ./scripts/socketserver/start.sh + - run: + name: Start http server + command: ./scripts/httpserver/start.sh - run: environment: + HTTPSERVER_ENABLED: 1 SIMAPP42_ENABLED: 1 SLOW_SIMAPP42_ENABLED: 1 TENDERMINT_ENABLED: 1 @@ -483,6 +504,7 @@ jobs: - run: name: Stop chains command: | + ./scripts/httpserver/stop.sh ./scripts/socketserver/stop.sh ./scripts/tendermint/all_stop.sh ./scripts/simapp42/stop.sh diff --git a/HACKING.md b/HACKING.md index 9813ffca..8080f2d8 100644 --- a/HACKING.md +++ b/HACKING.md @@ -64,13 +64,19 @@ export TENDERMINT_ENABLED=1 ./scripts/socketserver/start.sh export SOCKETSERVER_ENABLED=1 +# Start Http server +./scripts/httpserver/start.sh +export HTTPSERVER_ENABLED=1 + # now more tests are running that were marked as "pending" before yarn test # And at the end of the day +unset HTTPSERVER_ENABLED unset SOCKETSERVER_ENABLED unset TENDERMINT_ENABLED unset LAUNCHPAD_ENABLED +./scripts/httpserver/stop.sh ./scripts/socketserver/stop.sh ./scripts/tendermint/all_stop.sh ./scripts/launchpad/stop.sh @@ -100,6 +106,7 @@ order to avoid conflicts. Here is an overview of the ports used: | 1319 | wasmd LCD API | Manual Stargate debugging | | 4444 | socketserver | @cosmjs/sockets tests | | 4445 | socketserver slow | @cosmjs/sockets tests | +| 5555 | httpserver | @cosmjs/tendermint-rpc tests | | 9090 | simapp gRPC | Manual Stargate debugging | | 11134 | Tendermint 0.34 RPC | @cosmjs/tendermint-rpc tests | | 26658 | simapp Tendermint RPC | Stargate client tests | diff --git a/scripts/httpserver/Dockerfile b/scripts/httpserver/Dockerfile new file mode 100644 index 00000000..15971432 --- /dev/null +++ b/scripts/httpserver/Dockerfile @@ -0,0 +1,7 @@ +FROM python:3.9-alpine + +WORKDIR /usr/src/app + +COPY echo.py ./ + +ENTRYPOINT ["python", "./echo.py"] diff --git a/scripts/httpserver/echo.py b/scripts/httpserver/echo.py new file mode 100755 index 00000000..4582d552 --- /dev/null +++ b/scripts/httpserver/echo.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +#pylint:disable=missing-docstring,invalid-name + +import argparse +from http.server import HTTPServer, BaseHTTPRequestHandler +import json +import sys + +HOST = "0.0.0.0" + +def log(data): + print(data, flush=True) + +class CORSRequestHandler(BaseHTTPRequestHandler): + def end_headers(self): + self.send_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS") + self.send_header("Access-Control-Allow-Origin", "*") + self.send_header("Access-Control-Allow-Headers", "*") + BaseHTTPRequestHandler.end_headers(self) + + def do_OPTIONS(self): + self.send_response(200) + self.end_headers() + + def do_GET(self): + """Respond to a GET request.""" + if self.path == "/echo_headers": + self.send_response(200) + self.send_header("Content-type", "text/plain") + self.send_header('Content-type', 'application/json') + self.end_headers() + body = { + "request_headers": dict(self.headers) + } + self.wfile.write(json.dumps(body, sort_keys=True).encode()) + else: + self.send_response(404) + self.wfile.write("404. Try /echo_headers".encode()) + + def do_POST(self): + self.do_GET() + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument("--port", + help="Port to listen on", + type=int, + default=5555) + args = parser.parse_args() + httpd = HTTPServer((HOST, args.port), CORSRequestHandler) + log("Starting server at {}:{}".format(HOST, args.port)) + httpd.serve_forever() + log("Running now.") diff --git a/scripts/httpserver/start.sh b/scripts/httpserver/start.sh new file mode 100755 index 00000000..95546d9b --- /dev/null +++ b/scripts/httpserver/start.sh @@ -0,0 +1,31 @@ +#!/bin/bash +set -o errexit -o nounset -o pipefail +command -v shellcheck >/dev/null && shellcheck "$0" + +# Please keep this in sync with the Ports overview in HACKING.md +DEFAULT_PORT_GUEST="5555" +DEFAULT_PORT_HOST="5555" + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +HTTPSERVER_DIR=$(mktemp -d "${TMPDIR:-/tmp}/httpserver.XXXXXXXXX") +export HTTPSERVER_DIR +echo "HTTPSERVER_DIR = $HTTPSERVER_DIR" + +IMAGE_NAME="httpserver:local" +CONTAINER_NAME="httpserver" + +LOGFILE_DEFAULT="${HTTPSERVER_DIR}/httpserver_$DEFAULT_PORT_HOST.log" + +docker build -t "$IMAGE_NAME" "$SCRIPT_DIR" + +docker run --rm \ + --user="$UID" \ + --name "$CONTAINER_NAME" \ + -p "$DEFAULT_PORT_HOST:$DEFAULT_PORT_GUEST" \ + "$IMAGE_NAME" \ + >"$LOGFILE_DEFAULT" & + +# Debug start +sleep 3 +cat "$LOGFILE_DEFAULT" diff --git a/scripts/httpserver/stop.sh b/scripts/httpserver/stop.sh new file mode 100755 index 00000000..74d04dcb --- /dev/null +++ b/scripts/httpserver/stop.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -o errexit -o nounset -o pipefail +command -v shellcheck >/dev/null && shellcheck "$0" + +CONTAINER_NAME="httpserver" + +echo "Killing socketserver containers ..." +docker container kill "$CONTAINER_NAME" From 384d8f20f36072be9c7a14699bbb2e22289fe784 Mon Sep 17 00:00:00 2001 From: Simon Warta Date: Tue, 12 Apr 2022 17:58:01 +0200 Subject: [PATCH 5/5] Test custom headers --- .../src/rpcclients/httpclient.spec.ts | 44 +++++++++++++++++++ .../src/rpcclients/httpclient.ts | 11 ++--- packages/tendermint-rpc/webpack.web.config.js | 5 ++- 3 files changed, 54 insertions(+), 6 deletions(-) diff --git a/packages/tendermint-rpc/src/rpcclients/httpclient.spec.ts b/packages/tendermint-rpc/src/rpcclients/httpclient.spec.ts index 66295e33..1c326508 100644 --- a/packages/tendermint-rpc/src/rpcclients/httpclient.spec.ts +++ b/packages/tendermint-rpc/src/rpcclients/httpclient.spec.ts @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/naming-convention */ import { createJsonRpcRequest } from "../jsonrpc"; import { defaultInstance } from "../testutil.spec"; import { http, HttpClient } from "./httpclient"; @@ -8,7 +9,14 @@ function pendingWithoutTendermint(): void { } } +function pendingWithoutHttpServer(): void { + if (!process.env.HTTPSERVER_ENABLED) { + pending("Set HTTPSERVER_ENABLED to enable HTTP tests"); + } +} + const tendermintUrl = defaultInstance.url; +const echoUrl = "http://localhost:5555/echo_headers"; describe("http", () => { it("can send a health request", async () => { @@ -22,6 +30,42 @@ describe("http", () => { http("POST", `http://localhost:56745`, undefined, createJsonRpcRequest("health")), ).toBeRejectedWithError(/(ECONNREFUSED|Failed to fetch)/i); }); + + it("can send custom headers", async () => { + pendingWithoutHttpServer(); + // Without custom headers + const response1 = await http("POST", echoUrl, undefined, createJsonRpcRequest("health")); + expect(response1).toEqual({ + request_headers: jasmine.objectContaining({ + // Basic headers from http client + Accept: jasmine.any(String), + "Content-Length": jasmine.any(String), + "Content-Type": "application/json", + Host: jasmine.any(String), + "User-Agent": jasmine.any(String), + }), + }); + + // With custom headers + const response2 = await http( + "POST", + echoUrl, + { foo: "bar123", Authorization: "Basic Z3Vlc3Q6bm9QYXNzMTIz" }, + createJsonRpcRequest("health"), + ); + expect(response2).toEqual({ + request_headers: jasmine.objectContaining({ + // Basic headers from http client + "Content-Length": jasmine.any(String), + "Content-Type": "application/json", + Host: jasmine.any(String), + "User-Agent": jasmine.any(String), + // Custom headers + foo: "bar123", + Authorization: "Basic Z3Vlc3Q6bm9QYXNzMTIz", + }), + }); + }); }); describe("HttpClient", () => { diff --git a/packages/tendermint-rpc/src/rpcclients/httpclient.ts b/packages/tendermint-rpc/src/rpcclients/httpclient.ts index 83dd81bb..0b7dedac 100644 --- a/packages/tendermint-rpc/src/rpcclients/httpclient.ts +++ b/packages/tendermint-rpc/src/rpcclients/httpclient.ts @@ -11,8 +11,6 @@ import { hasProtocol, RpcClient } from "./rpcclient"; // Global symbols in some environments // https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch declare const fetch: any | undefined; -// eslint-disable-next-line @typescript-eslint/naming-convention -declare const Headers: any | undefined; function filterBadStatus(res: any): any { if (res.status >= 400) { @@ -34,11 +32,14 @@ export async function http( request?: any, ): Promise { if (typeof fetch !== "undefined") { - const body = request ? JSON.stringify(request) : undefined; const settings = { method: method, - body: body, - headers: headers ? new Headers(headers) : undefined, + body: request ? JSON.stringify(request) : undefined, + headers: { + // eslint-disable-next-line @typescript-eslint/naming-convention + "Content-Type": "application/json", + ...headers, + }, }; return fetch(url, settings) .then(filterBadStatus) diff --git a/packages/tendermint-rpc/webpack.web.config.js b/packages/tendermint-rpc/webpack.web.config.js index 260f3154..d72c8f89 100644 --- a/packages/tendermint-rpc/webpack.web.config.js +++ b/packages/tendermint-rpc/webpack.web.config.js @@ -16,7 +16,10 @@ module.exports = [ filename: "tests.js", }, plugins: [ - new webpack.EnvironmentPlugin({ TENDERMINT_ENABLED: "" }), + new webpack.EnvironmentPlugin({ + HTTPSERVER_ENABLED: "", + TENDERMINT_ENABLED: "", + }), new webpack.ProvidePlugin({ Buffer: ["buffer", "Buffer"], }),