我正在关注 Alchemy Learn 的以太坊开发者训练营。我在自己的 JavaScript 环境中运行以下代码时遇到错误,该代码旨在使用私钥对消息进行签名。我正在使用
ethereum-cryptography
版本的 2.0.0
库。
// signMessage.js file
const secp = require("ethereum-cryptography/secp256k1");
const hashMessage = require("./hashMessage");
const PRIVATE_KEY = "some-key";
async function signMessage(msg) {
const hash = hashMessage(msg);
const sign = await secp.sign(hash, PRIVATE_KEY, { recovered: true });
return sign;
}
module.exports = signMessage;
这是
test.js
文件:
const { assert } = require('chai');
const secp = require("ethereum-cryptography/secp256k1");
const { toHex } = require("ethereum-cryptography/utils");
const signMessage = require('./signMessage');
const hashMessage = require('./hashMessage');
const PRIVATE_KEY = "some-key";
describe('Sign Message', () => {
it('should return both a signature and a recovery bit', async () => {
const response = await signMessage('hello world');
const errMessage = "expected signMessage to return both a signature and recovery bit!";
assert(response.length, errMessage);
assert(response.length === 2, errMessage);
const [signature, recoveryBit] = response;
assert(signature.length, "expected signature to be a Uint8Array");
assert(typeof recoveryBit === "number", "expected the recovery bit to be a number");
});
it('should have been signed by the same private key', async () => {
const [sig, recoveryBit] = await signMessage('hello world');
const messageHash = hashMessage('hello world');
const recovered = secp.recoverPublicKey(messageHash, sig, recoveryBit);
const publicKey = secp.getPublicKey(PRIVATE_KEY);
assert.equal(toHex(recovered), toHex(publicKey));
});
});
然后,在终端上运行
yarn test
时,我得到:
yarn run v1.22.19
$ yarn mocha ./src/test.js
$ '/Users/user/alchemy/node_modules/.bin/mocha' ./src/test.js
Sign Message
1) should return both a signature and a recovery bit
2) should have been signed by the same private key
0 passing (6ms)
2 failing
1) Sign Message
should return both a signature and a recovery bit:
TypeError: secp.sign is not a function
at signMessage (src/signMessage.js:11:29)
at Context.<anonymous> (src/test.js:13:32)
at process.processImmediate (node:internal/timers:478:21)
2) Sign Message
should have been signed by the same private key:
TypeError: secp.sign is not a function
at signMessage (src/signMessage.js:11:29)
at Context.<anonymous> (src/test.js:25:42)
at process.processImmediate (node:internal/timers:478:21)
error Command failed with exit code 2.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error Command failed with exit code 2.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
在 Alchemy 在线环境中运行它时,它可以工作。我想知道问题是什么。希望有人能帮助我。