ethereum web3js 如何导入“crypto-js”?

Posted

技术标签:

【中文标题】ethereum web3js 如何导入“crypto-js”?【英文标题】:how does ethereum web3js imports "crypto-js"? 【发布时间】:2021-07-02 00:22:37 【问题描述】:

我对以太坊存储库的 web3.js 文件中使用的语法有点困惑,虽然没有名为 crypto-js 的文件,也没有任何 npm 或 yarn,但这个导入是如何完成的? https://github.com/ethereum/go-ethereum/blob/master/internal/jsre/deps/web3.js#L1828

【问题讨论】:

您正在寻找缩小的源。我建议你查看原始源文件。 这是在以太坊控制台中使用的内置版本,我想修改它@MikkoOhtamaa 有没有办法改变未缩小的 web3 然后将其注入以太坊? @MikkoOhtamaa 你不需要 geth 以太坊控制台。如果你想运行 javascript,你可以只执行 web3.js 并让它连接你通过 HTTP 或 IPC JSON-RPC 运行的任何 Go Ethereum 节点。 不确定,我确实看到了一个 npm 模块 crypto-js,它正在以太坊中使用,还有 sha3。我在这里错过了什么吗? 【参考方案1】:

您正在查看的 javascript 文件 (web3.js) 是 web3 构建的结果,即整个 web3 项目及其依赖项的 browserify 包。来自 npm 的整个 crypto-js 库都捆绑在该文件中——这就是为什么在 go-ethereum 项目中没有其他对 crypto-js 的引用。让我们看一下包含您链接的代码的对象,它看起来像这样:


    //...
    19: [
        function(require, module, exports) 
            //...
            var CryptoJS = require('crypto-js');
            var sha3 = require('crypto-js/sha3');
            //...
        ,
        
            "crypto-js": 59,
            "crypto-js/sha3": 80
        
    ]
    //...

这个键/值对代表一个模块。键 19 是包中模块的 ID。该值是一个包含两个元素的数组:(1) 模块代码和 (2) 模块的依赖项。依赖项作为具有模块名称键和模块 ID 值的对象给出。因此,crypto-js 模块可以在键 59 下的同一对象中找到,同样,crypto-js/sha3 在键 80 下。

修改web3.js可以通过获取源并重建它来完成。 go-ethereum repo 中的版本似乎是 0.20.1,对应于 web3 repository 中的提交 996148d3。构建这个版本有点痛苦,因为当时 web3 没有提交 package-lock.json。我能够通过强制使用 gulp 3.9 和节点 10 来构建它。至于替换 crypto-js,您可以编辑 lib/utils/sha3.js 并将其替换为不同的 sha3 实现。

重建 web3 后,将 dist/web3-light.js 复制到 go-ethereum 仓库中的 internals/jsre/deps/web3.js 并运行 go generate 以重新生成 internals/jsre/deps/bindata.go。最后,构建geth

把这一切放在一起:

# Clone web3
git clone https://github.com/ChainSafe/web3.js
cd web3.js
git switch -c replace-crypto-js 996148d356570745ef20630b499bce37f8484920

# Edit the sha3 implementation
vim lib/utils/sha3.js

# Build using gulp 3.9 and node 10
sed -i 's/"gulp": ">=3.9.0"/"gulp": "^3.9.0"/' package.json
npm install
npm --no-save install node@10
PATH=./node_modules/.bin gulp

# Clone go-ethereum
cd ..
git clone https://github.com/ethereum/go-ethereum.git
cd go-ethereum

# Copy new web3 and regenerate bindata.go
cp ../web3.js/dist/web3-light.js internal/jsre/deps/web3.js
make devtools
PATH=$PATH:$(go env GOPATH)/bin go generate internal/jsre/deps/deps.go

# Build geth and test out changes in console
make geth
./build/bin/geth console

【讨论】:

以上是关于ethereum web3js 如何导入“crypto-js”?的主要内容,如果未能解决你的问题,请参考以下文章

使用Java+Web3j和Ethereum网络交互:获取Ethereum信息

区块链以太坊(Ethereum )高级进阶实战视频教程

web3js方法获取账户信息和余额

我无法更改 Web3js 的版本

web3js learning

以太坊/BSC 区块链交易数据