以太坊常见问题和错误

在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器

使用web3j加载智以太坊能合约如何指定证书Credentials?

我正在使用web3j库来生成一个用于我的solidity以太坊智能合约的Java封装包,我已经将该智能合约部署到区块链中,并且它已经被挖掘,现在我想使用Java封装包在Java中加载该以太坊智能合约。

java封装包是SimpleStorage,web3j已经生成了用于加载以太坊智能合约的以下方法签名:

public static SimpleStorage load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
    return new SimpleStorage(contractAddress, web3j, credentials, gasPrice, gasLimit);
}

public static SimpleStorage load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {
    return new SimpleStorage(contractAddress, web3j, transactionManager, gasPrice, gasLimit);
}

如何提供Credentials对象?我有一个公钥、私钥和地址,它是我在区块链上部署的,但是Credentials对象需要一个ECKeyPair,它希望私钥和公钥是一个BigInteger,但是我的密钥只是字符串形式的。

加载参数可以传递给这个方法:

public static Credentials create(String privateKey, String publicKey) {
    return create(new ECKeyPair(Numeric.toBigInt(privateKey), Numeric.toBigInt(publicKey)));
}

如果我的公钥和私钥不能转换成BigInt,那么这将失败。

问题的解决

若要生成凭据,如果你有普通的公钥和私钥,则需要将它们转换为十六进制的表示形式,然后将它们传递给构造函数用于Credentials

String hexPrivateKey = String.format("%040x", new BigInteger(1, privateKey.getBytes()));
String hexPublicKey = String.format("%040x", new BigInteger(1, publicKey.getBytes()));  
Credentials creds = Credentials.create(hexPrivateKey, hexPublicKey);

其中privateKeyprivateKey是包含你的私钥和公钥的字符串。