以太坊 web3js 如何导入“crypto-js”?

问题描述

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

解决方法

您正在查看的 javascript 文件 (web3.js) 是 web3 构建的结果,即整个 web3 项目及其依赖项的浏览器包。 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 存储库中的版本似乎是 0.20.1,对应于 996148d3 中的提交 web3 repository。构建这个版本有点痛苦,因为当时 web3 没有提交 package-lock.json。我能够通过强制使用 gulp 3.9 和节点 10 来构建它。至于替换 crypto-js,您可以编辑 lib/utils/sha3.js 并将其替换为不同的 sha3 实现。

重建 web3 后,将 dist/web3-light.js 复制到 internals/jsre/deps/web3.js 存储库中的 go-ethereum 并运行 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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...