This repository has been archived by the owner on Feb 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Create a web3 http provider that can handle massive JSON blobs without crashing due to string or buffer length issues #4381
Draft
davidmurdoch
wants to merge
7
commits into
develop
Choose a base branch
from
fix/streaming-web3-http-provider
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
b550ccb
init
davidmurdoch dd77115
add tests
davidmurdoch d7b3e2d
remove a thing
davidmurdoch 80339a1
parse correctly
davidmurdoch cbdf10d
Update packages/core/lib/command-utils.js
davidmurdoch eedb25e
fix?
davidmurdoch e841ab6
big brain time
davidmurdoch File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
node_modules | ||
dist |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
Copyright (c) 2021 ConsenSys, Inc. | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
# @truffle/stream-provider | ||
|
||
A Web3.providers.HttpProvider that can handle JSON blobs greater than 1 GB. | ||
|
||
Large blob handling is currently only used for `debug_traceTransaction` | ||
results. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,102 @@ | ||
import axios, { AxiosRequestConfig } from "axios"; | ||
import type { JsonRpcResponse } from "web3-core-helpers"; | ||
import { errors } from "web3-core-helpers"; | ||
import _Web3HttpProvider, { HttpProvider } from "web3-providers-http"; | ||
const JSONStream = require("JSONStream"); | ||
|
||
// they export types, but in the wrong place | ||
const Web3HttpProvider = _Web3HttpProvider as any as typeof HttpProvider; | ||
|
||
export class StreamingWeb3HttpProvider extends Web3HttpProvider { | ||
/** | ||
* Should be used to make async request | ||
* | ||
* @method send | ||
* @param {Object} payload | ||
* @param {Function} callback triggered on end with (err, result) | ||
*/ | ||
send( | ||
payload: any, | ||
callback: (error: Error | null, result: JsonRpcResponse | undefined) => void | ||
) { | ||
if ( | ||
typeof payload === "object" && | ||
payload.method === "debug_traceTransaction" | ||
) { | ||
const requestOptions: AxiosRequestConfig = { | ||
method: "post", | ||
url: this.host, | ||
responseType: "stream", | ||
data: payload, | ||
timeout: this.timeout, | ||
withCredentials: this.withCredentials, | ||
headers: this.headers | ||
? this.headers.reduce((acc, header) => { | ||
acc[header.name] = header.value; | ||
return acc; | ||
}, {} as Record<string, string>) | ||
: undefined | ||
}; | ||
// transitional.clarifyTimeoutError is required so we can detect and emit | ||
// a timeout error the way web3 already does | ||
(requestOptions as any).transitional = { | ||
clarifyTimeoutError: true | ||
}; | ||
const agents = { | ||
httpsAgent: (this as any).httpsAgent, | ||
httpAgent: (this as any).httpAgent, | ||
baseUrl: (this as any).baseUrl | ||
}; | ||
if (this.agent) { | ||
agents.httpsAgent = this.agent.https; | ||
agents.httpAgent = this.agent.http; | ||
agents.baseUrl = this.agent.baseUrl; | ||
} | ||
requestOptions.httpAgent = agents.httpAgent; | ||
requestOptions.httpsAgent = agents.httpsAgent; | ||
requestOptions.baseURL = agents.baseUrl; | ||
|
||
axios(requestOptions) | ||
.then(async response => { | ||
let error = null; | ||
let result: any = {}; | ||
const stream = response.data.pipe( | ||
JSONStream.parse([{ emitKey: true }]) | ||
); | ||
try { | ||
result = await new Promise((resolve, reject) => { | ||
let result: any = {}; | ||
stream.on("data", (data: any) => { | ||
const { key, value } = data; | ||
result[key] = value; | ||
}); | ||
stream.on("error", (error: Error) => { | ||
reject(error); | ||
}); | ||
stream.on("end", () => { | ||
resolve(result); | ||
}); | ||
}); | ||
} catch (e) { | ||
error = errors.InvalidResponse(e); | ||
} | ||
this.connected = true; | ||
// process.nextTick so an exception thrown in the callback doesn't | ||
// bubble back up to here | ||
process.nextTick(callback, error, result); | ||
}) | ||
.catch(error => { | ||
this.connected = false; | ||
if (error.code === "ETIMEDOUT") { | ||
// web3 passes timeout as a number to ConnectionTimeout, despite the | ||
// type requiring a string | ||
callback(errors.ConnectionTimeout(this.timeout as any), undefined); | ||
} else { | ||
callback(errors.InvalidConnection(this.host), undefined); | ||
} | ||
}); | ||
} else { | ||
return super.send(payload, callback); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
{ | ||
"name": "@truffle/stream-provider", | ||
"description": "Enables streaming results into memory from debug_traceTransaction", | ||
"license": "MIT", | ||
"author": "David Murdoch <[email protected]>", | ||
"homepage": "https://github.com/trufflesuite/truffle/tree/master/packages/stream-provider#readme", | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/trufflesuite/truffle.git", | ||
"directory": "packages/stream-provider" | ||
}, | ||
"bugs": { | ||
"url": "https://github.com/trufflesuite/truffle/issues" | ||
}, | ||
"version": "0.0.1", | ||
"main": "dist/index.js", | ||
"files": [ | ||
"dist" | ||
], | ||
"directories": { | ||
"lib": "lib" | ||
}, | ||
"scripts": { | ||
"build": "tsc", | ||
"prepare": "yarn build", | ||
"test:ts": "NODE_OPTIONS=--max-old-space-size=4096 mocha -r ts-node/register test/*.ts", | ||
"test": "yarn test:ts" | ||
}, | ||
"types": "dist/index.d.ts", | ||
"dependencies": { | ||
"web3-providers-http": "^1.6.0", | ||
"web3-core-helpers": "1.5.3", | ||
"JSONStream": "1.3.5", | ||
"axios": "^0.21.1" | ||
}, | ||
"devDependencies": { | ||
"mocha": "8.1.2" | ||
}, | ||
"keywords": [ | ||
"ethereum", | ||
"etherscan", | ||
"ipfs", | ||
"solidity", | ||
"web3" | ||
], | ||
"publishConfig": { | ||
"access": "public" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
import assert from "assert"; | ||
import http, { Server, ServerResponse } from "http"; | ||
import { StreamingWeb3HttpProvider } from "../lib/"; | ||
|
||
describe("test", () => { | ||
const PORT = 9451; | ||
let server: Server; | ||
const SIZE = (1000000000 / 2) | 0; | ||
beforeEach(() => { | ||
server = http.createServer(); | ||
server | ||
.on("request", (request, response: ServerResponse) => { | ||
let body: Buffer[] = []; | ||
request | ||
.on("data", (chunk: Buffer) => { | ||
body.push(chunk); | ||
}) | ||
.on("end", () => { | ||
response.writeHead(200, "OK", { | ||
"content-type": "application/json" | ||
}); | ||
const prefix = '{"id":1,"result":{"structLogs":["'; | ||
const postfix = '"]}}'; | ||
response.write(prefix); | ||
// .5 gigs of utf-8 0s | ||
const lots = Buffer.allocUnsafe(SIZE).fill(48); | ||
response.write(lots); | ||
response.write('","'); | ||
response.write(lots); | ||
response.write('","'); | ||
response.write(lots); | ||
response.write('","'); | ||
response.write(lots); | ||
response.write(postfix); | ||
response.end(); | ||
}); | ||
}) | ||
.listen(PORT); | ||
}); | ||
afterEach(async () => { | ||
server && server.close(); | ||
}); | ||
it("handles giant traces", async function () { | ||
this.timeout(0); | ||
const provider = new StreamingWeb3HttpProvider(`http://localhost:${PORT}`); | ||
const { result } = await new Promise<any>((resolve, reject) => { | ||
provider.send( | ||
{ | ||
id: 1, | ||
jsonrpc: "2.0", | ||
method: "debug_traceTransaction", | ||
params: ["0x1234"] | ||
}, | ||
(err, result) => { | ||
if (err) return void reject(err); | ||
resolve(result); | ||
} | ||
); | ||
}); | ||
assert.strictEqual(result.structLogs.length, 4); | ||
result.structLogs.forEach((log: Buffer) => { | ||
assert.strictEqual(log.length, SIZE); | ||
}); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
{ | ||
"compilerOptions": { | ||
"declaration": true, | ||
"module": "commonjs", | ||
"esModuleInterop": true, | ||
"target": "es2016", | ||
"downlevelIteration": true, | ||
"noImplicitAny": true, | ||
"moduleResolution": "node", | ||
"sourceMap": true, | ||
"outDir": "dist", | ||
"baseUrl": ".", | ||
"lib": [ | ||
"es2017" | ||
], | ||
"paths": {}, | ||
"rootDir": "lib", | ||
"types": [ | ||
"mocha", | ||
"node" | ||
] | ||
}, | ||
"include": [ | ||
"./lib/**/*.ts" | ||
] | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should we make this guy also implement
request
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No. This is a drop-in replacement for
Web3HttpProvider
, which doesn't implementrequest
.