在通过web3j依赖包提供的api调用personalNewAccount方法返回null,也就是说并没有真正生成地址。这是什么原因导致的呢?

如下代码调用:

String password = EthereumConfiguration.getWalletPwd();
NewAccountIdentifier newAccountIdentifier;
try {
	newAccountIdentifier = web3.personalNewAccount(password).send();
	if (newAccountIdentifier.getAccountId() == null) {
		throw new BaseException(ResultCodeConstants.RECHARGE_ADDR_GET_FAILED);
	}
} catch (IOException e) {
	logger.info(String.format("[eth wallet service]: 获取以太坊充值地址失败, message:%s", e.getMessage()));
	throw new BaseException(ResultCodeConstants.RECHARGE_ADDR_GET_FAILED);
}

上面的业务逻辑中,先是获得密码、然后调用生成地址方法,检查返回值是否为null,来确定地址是否生成成功。调用web3j的相关personalNewAccount的代码如下:

public Request<?, NewAccountIdentifier> personalNewAccount(String password) {
        return new Request("personal_newAccount", Arrays.asList(password), this.web3jService, NewAccountIdentifier.class);
    }

也就是说通过json-rpc来调用personal_newAccount方法生成地址。

那么,为什么返回为null呢,常见的原因是以太坊geth节点启动之后,并没有开放personal操作的rpcapi。

对照以下启动geth的命令:

nohup ./geth --datadir ./data/ --cache 4096 --rpc --rpcport 8545 --rpcaddr 0.0.0.0 --rpcapi eth,net,web3,personal --ws --wsaddr 0.0.0.0 --wsport 8546 --wsapi eth,net,web3 --wsorigins "*" --allow-insecure-unlock --syncmode fast  & > nohup.out

添加了–rpcapi eth,net,web3,personal参数,便可以正常访问了。

其中–allow-insecure-unlock参数允许调用personal.unlockAccount(“address”)命令。

以太坊geth web3j personalNewAccount返回null插图
公众号:程序新视界


以太坊geth web3j personalNewAccount返回null插图1

关注公众号:程序新视界,一个让你软实力、硬技术同步提升的平台

除非注明,否则均为程序新视界原创文章,转载必须以链接形式标明本文链接

本文链接:http://www.choupangxia.com/2019/11/15/geth-web3j-personalnewaccount-null/