Giter Site home page Giter Site logo

fisco-bcos / web3sdk Goto Github PK

View Code? Open in Web Editor NEW
117.0 15.0 83.0 23.49 MB

java sdk for FISCO BCOS(deprecated, please use FISCO-BCOS/java-sdk)

License: Apache License 2.0

Java 98.26% Shell 0.12% Solidity 1.62%
sdk web3sdk bcos fisco-bcos consortium spring java

web3sdk's Introduction

English / 中文

Web3SDK

PRs Welcome Build Status CodeFactor Codacy Badge GitHub All Releases

Web3SDK provides the Java API for FISCO-BCOS. You can easily and quickly develop your blockchain applications based on the Web3SDK. The version only supports FISCO BCOS 2.0+.

Features

Compile

Environmental requirements:

Compile web3sdk using the following command:

$ cd web3sdk
$ ./gradlew build

The artifact is located at:

web3sdk/dist/apps/web3sdk.jar

Documentation

Quickstart

spring boot starter for Web3SDK is available that demonstrates a number of core features, including:

  • Connecting to a node on the FISCO BCOS network.
  • Deploying a smart contract to the network.
  • Reading a value from the deployed smart contract.
  • Updating a value in the deployed smart contract.
  • Providing integration tests demonstrating for the above features.

Code Contribution

  • If this project is useful to you, please star us on GitHub project page.
  • Pull requests. See CONTRIBUTING.
  • Report bugs, issues or feature requests. Using GitHub issues.

Join Our Community

The FISCO BCOS community is one of the most active open-source blockchain communities in China. It provides long-term technical support for both institutional and individual developers and users of FISCO BCOS. Thousands of technical enthusiasts from numerous industry sectors have joined this community, studying and using FISCO BCOS platform. If you are also interested, you are most welcome to join us for more support and fun.

License

license

All contributions are made under the Apache License 2.0. See LICENSE.

web3sdk's People

Contributors

bxq2011hust avatar chaychen2005 avatar cyjseagull avatar dalaocu avatar fisco-dev avatar fqliao avatar haoxuan40404 avatar idioticmadman avatar jimmyshi22 avatar mingzhenliu avatar morebtcg avatar netgodfather avatar qwdarrenyin avatar shareong avatar sulenn avatar vita-dounai avatar wheatli avatar yanyanho avatar ywy2090 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

web3sdk's Issues

使用webase私钥管理功能时发现web3sdk引的bcprov jar包找不到convertSpec方法

image

错误日志
八月 25, 2020 4:15:51 下午 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet [dispatcherServlet] in context with path [/WeBASE-Node-Manager] threw exception [Handler dispatch fail
ed; nested exception is java.lang.NoSuchMethodError: org.bouncycastle.jcajce.provider.asymmetric.util.EC5Util.convertSpec(Ljava/security/s
pec/ECParameterSpec;Z)Lorg/bouncycastle/jce/spec/ECParameterSpec;] with root cause
java.lang.NoSuchMethodError: org.bouncycastle.jcajce.provider.asymmetric.util.EC5Util.convertSpec(Ljava/security/spec/ECParameterSpec;Z)Lo
rg/bouncycastle/jce/spec/ECParameterSpec;
at org.fisco.bcos.channel.client.P12Manager.getPublicKey(P12Manager.java:81)
at org.fisco.bcos.channel.client.P12Manager.getECKeyPair(P12Manager.java:129)
at com.webank.webase.node.mgr.user.UserService.importKeyStoreFromP12(UserService.java:378)
at com.webank.webase.node.mgr.user.UserService$$FastClassBySpringCGLIB$$796fed91.invoke()
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:687)
at com.webank.webase.node.mgr.user.UserService$$EnhancerBySpringCGLIB$$d5a9e38e.importKeyStoreFromP12()
at com.webank.webase.node.mgr.user.UserController.importP12PrivateKey(UserController.java:224)
at com.webank.webase.node.mgr.user.UserController$$FastClassBySpringCGLIB$$54fc7f40.invoke()
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:752)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:69)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691)
at com.webank.webase.node.mgr.user.UserController$$EnhancerBySpringCGLIB$$98029e51.importP12PrivateKey()
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMeth

请问client.keystore如何生成

配置中的第三小点
需要包含一个由节点CA证书颁发的,别名为client的身份证书
请问如何根据ca.crt生成该文件。。

web3sdk不支持多群组

问题描述:

bcos在2.0版本支持多群组的功能,但是web3sdk中的org.fisco.bcos.channel.client.Service只支持单groupId的实现

Service service = new Service();
service.setGroupId(groupId);
service.setOrgID(orgId);
service.setAllChannelConnections(groupChannelConnectionsConfig);
service.run();
sdk.setService(service);      

ChannelEthereumService channelEthereumService = new ChannelEthereumService();
channelEthereumService.setChannelService(service);
sdk.setWeb3j(Web3j.build(channelEthereumService,groupId));

虽然可以实例化多个channelService, 但是Service中的groupID是static修饰的, 所以只有最后一个实例化的groupID才会生效

public class Service {
       private static int groupId;
}

运行一段时间后总发生处理Ethereum消息超时

目前使用web3sdk生成的java代码和链交互。在正常使用一段时间后,就会发生“处理Ethereum消息超时”,此时重启链和java项目就会回复正常。请问这是什么原因,如何解决。
错误信息如下:
`2018-05-16 16:11:41.374 ERROR 19642 --- [tLoopGroup-2-11] org.bcos.channel.handler.ChannelHandler : 网络错误

java.io.IOException: Connection reset by peer
at sun.nio.ch.FileDispatcherImpl.read0(Native Method) ~[na:1.8.0_144]
at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39) ~[na:1.8.0_144]
at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223) ~[na:1.8.0_144]
at sun.nio.ch.IOUtil.read(IOUtil.java:192) ~[na:1.8.0_144]
at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:380) ~[na:1.8.0_144]
at io.netty.buffer.PooledUnsafeDirectByteBuf.setBytes(PooledUnsafeDirectByteBuf.java:288) ~[netty-all-4.1.22.Final.jar:4.1.22.Final]
at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1108) ~[netty-all-4.1.22.Final.jar:4.1.22.Final]
at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:345) ~[netty-all-4.1.22.Final.jar:4.1.22.Final]
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:131) ~[netty-all-4.1.22.Final.jar:4.1.22.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:645) [netty-all-4.1.22.Final.jar:4.1.22.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:580) [netty-all-4.1.22.Final.jar:4.1.22.Final]
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:497) [netty-all-4.1.22.Final.jar:4.1.22.Final]
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:459) [netty-all-4.1.22.Final.jar:4.1.22.Final]
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:886) [netty-all-4.1.22.Final.jar:4.1.22.Final]
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) [netty-all-4.1.22.Final.jar:4.1.22.Final]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_144]

2018-05-16 16:11:43.390 ERROR 19642 --- [pool-2-thread-1] o.b.c.client.EthereumResponseCallback : 处理Ethereum消息超时:{}
`

合约调用完,获取TransactionReceipt 中的blockNumber获取报错

合约调用完毕,获取 回执中的blockNumber,报org.bcos.web3j.protocol.exceptions.MessageDecodingException: Value must be in format 0x[1-9]+[0-9]* or 0x0

查看源码中Numeric.decodeQuantity 有校验是否数据为0x的判断,但是我debug发现 blockNumber本身就是一个数值,没有0x前缀,是否为BUG?

I compile the same contract using the same version of web3sdk, but get different bin files.

I found the last 76 characters of bin file may be different.

The last 4 digits are always 0029.
The middle 64 characters are the hash of metadata. Refer to here: https://solidity.readthedocs.io/en/latest/metadata.html?highlight=metadata#contract-metadata
So the first 8 of 76 may be the prefix of rlp? I don't quite sure of that.

The changing bin of the same contract can confuse the parse of contract result, including account and construct parsing.

I suggest that you could set the fixed String to the bin, or even remove this metadata hash, coz it's no use in fisco-bcos.

gradle run,会有错误

按照文档提供的命令对SDK执行gradle run,会有错误。如果改为执行gradle build可以编译成功。

预编译合约Service返回值为String,需要手动反序列化才能做错误处理

预编译合约的Service的交易回值和返回值对于错误处理不方便,即PrecompiledCommon.java中handleTransactionReceit(TransactionReceipt, Web3j)方法,当预编译执行错误时,返回的不是一个(code,msg)的response实体类对象,而是一个String对象。二次开发时只能自己复制实现一次handleTransactionReceipt方法,自己抛错。

public static String handleTransactionReceipt(TransactionReceipt receipt, Web3j web3j)
            throws TransactionException, IOException {
        String status = receipt.getStatus();
        if (!"0x0".equals(status)) {
            throw new TransactionException(
                    StatusCode.getStatusMessage(receipt.getStatus(), receipt.getMessage()));
        } else {
            // status不为0x0即交易成功
            // output中包含了预编译合约的执行结果,此处返回为String,并没有包含执行结果的statusCode,如-50000为permission denied, 实际上返回的只有permission denied的字符串。
            if (receipt.getOutput() != null) {
                return PrecompiledCommon.getJsonStr(receipt.getOutput(), web3j);
            } else {
                throw new TransactionException("Transaction is handled failure.");
            }
        }
    }

判断预编译合约是否执行成功,只能如下反序列后操作:
image

控制台报错Input byte array must be in range 0 < M <= 32 and length must match type

我的智能合约函数声明是
function Store(bytes memory payload, bytes32 hash, bytes memory signature) public
在传入第二个参数的时候一直报错:
Input byte array must be in range 0 < M <= 32 and length must match type

我尝试不同的第二个参数长度,终于找到一个bug级别的错误,我传入的参数长度如下:
call TicketStorage 0x0b5b720823e3740f1d19fda77131343b050f3960 Store "0xdeadbeef" "0x000000000000000000000000000000" "0x00"
注意第二个参数实际上只有15个字节长度,但是这里却认为这是正确的bytes32,我暂时不知道这是控制台的bug还是web3sdk的bug,就在这里提了,因为找到报错的地方是在web3sdk。

web3sdk 什么时候适配 ipv6 呀?

ipv6 作为一种大趋势,在全世界各种互联网产品中已经应用十分广泛。fisco bcos 作为广受好评的联盟链架构是不是也可以适配 ipv6?哈哈哈哈哈哈哈哈哈哈

TransactionReceipt解析出错

2018-07-30 10:14:07.068|nioEventLoopGroup-2-4|DEBUG|Service.java:275| response: {"id":1,"jsonrpc":"2.0","result":{"blockHash":"0x8a5044e39385f97d876438611b5728d7700b497f8f74edb3eb79347b9bbf382f","blockNumber":159,"contractAddress":"0x0000000000000000000000000000000000000000","cumulativeGasUsed":"0x9a1d","gasUsed":"0x9a1d","logs":[{"address":"0xe9b04d2f2d8a3e01696ce0bd203ae4aba431a3c6","blockHash":"0x8a5044e39385f97d876438611b5728d7700b497f8f74edb3eb79347b9bbf382f","blockNumber":159,"data":"0x0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000623634f45b2112f90d2423616592f5c1f3030df5","logIndex":0,"polarity":false,"topics":["0x52b41a3d5941bc85d0e71d1857c7c52ac9f45cf25c6607ab1254bc4a25c8e4f9"],"transactionHash":"0xbe5e95eb9b0f1d02ca7753bf96909f60683835acef92c3fc5dc10cc4570b3682","transactionIndex":0,"type":"mined"}],"transactionHash":"0xbe5e95eb9b0f1d02ca7753bf96909f60683835acef92c3fc5dc10cc4570b3682","transactionIndex":0}}

返回值如上,解析数值报错
image
debug观察到为解析返回log中数值出错

用spring boot 构建项目,使用web3sdk操作区块链。打成jar 包运行时,提示找不到ca.crt和client.keystore等资源文件

1,我定义了一个初始化web3sdk的静态方法,在spring boot 启动后执行
`public class FiscoBcosSdk {
private static Logger logger = LoggerFactory.getLogger(FiscoBcosSdk.class);
private static ApplicationContext context=null;

public static Web3j web3;
public static Credentials credentials;

public static void initObj() throws Exception {
	logger.info("(◉ω◉)===>Starting...");
	//初始化Service
	context = new ClassPathXmlApplicationContext("classpath:fisco-bcos/applicationContext.xml");
	Service service = context.getBean(Service.class);
	service.run();

	logger.info("(◉ω◉)===>初始化AOMP的ChannelEthereumService");

	ChannelEthereumService channelEthereumService = new ChannelEthereumService();
	channelEthereumService.setChannelService(service);
	
	//使用AMOP消息信道初始化web3j
	web3 = Web3j.build(channelEthereumService);
	
	EthBlockNumber ethBlockNumber = web3.ethBlockNumber().sendAsync().get();
	logger.info("(◉ω◉)===>获取ethBlockNumber:{}",ethBlockNumber.getBlockNumber());
	
	//初始化交易签名私钥
	ECKeyPair keyPair = Keys.createEcKeyPair();
	credentials = Credentials.create(keyPair);
	logger.info("(◉ω◉)===>blockchain sdk init success!");
}}

`
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
try {
FiscoBcosSdk.initObj();
} catch (Exception e) {
logger.error("(T_T)===>FiscoBcosSdk.initObj() throws exception!");
e.printStackTrace();
}

}
`

代码在我本地的idea上执行没有任何问题。如下图:
image

2,我吧项目用maven 导出成jar 包在mac电脑上(linux)执行,提示找不到ca.crt等资源文件。如下图:
image

web3sdk启动报错

操作系统:Linux version 4.8.0-53-generic (buildd@lgw01-56) (gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.4) )

jdk
java version "1.8.0_161"
Java(TM) SE Runtime Environment (build 1.8.0_161-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.161-b12, mixed mod

gradle

Gradle 4.6
Build time: 2018-02-28 13:36:36 UTC
Revision: 8fa6ce7945b640e6168488e4417f9bb96e4ab46c

Groovy: 2.4.12
Ant: Apache Ant(TM) version 1.9.9 compiled on February 2 2017
JVM: 1.8.0_161 (Oracle Corporation 25.161-b12)
OS: Linux 4.8.0-53-generic amd

启动web3sdk中test下的Ethereum类,总是报如下错误
2018-04-30 13:25:59.018 [nioEventLoopGroup-2-1] DEBUG NativeLibraryLoader(:) - Unable to load the library 'netty_tcnative_linux_x86_64', trying other loading mechanism.
java.lang.UnsatisfiedLinkError: no netty_tcnative_linux_x86_64 in java.library.path
netty_tcnative_linux_x86_64 cannot be loaded from java.libary.path, now trying export to -Dio.netty.native.workdir: /tmp
java.lang.UnsatisfiedLinkError: no netty_tcnative_linux_x86_64 in java.library.path

ResultEntity传入数组(DynamicBytes或BytesX)时,序列化会出现空字符串

ResultEntity中,若传入数组,那么序列化ResultEntity会出现空字符串。

测试代码

    @Test
    public void any() throws Exception{
        DynamicBytes db = new DynamicBytes(new byte[]{1,2,3});
        ResultEntity resultEntity = new ResultEntity("aa","bytes",db );
        System.out.println(JsonUtils.toJson(resultEntity));

        Bytes3 bytes32 = new Bytes3(new byte[]{1,2,3});
        resultEntity = new ResultEntity("aa","bytes32",bytes32 );
        System.out.println(JsonUtils.toJson(resultEntity));
    }

当前结果:

{"name":"aa","type":"bytes","data":""}
{"name":"aa","type":"bytes32","data":""}

期望结果

{"name":"aa","type":"bytes","data":[Hex或Base64编码的二进制]}
{"name":"aa","type":"bytes32","data":"[Hex或Base64编码的二进制]"}

原因分析

ResultEntity在构造函数里传入DynamicBytes或定长Bytes时,会将字节数组通过UTF8转码为字符串,这一步将产生不可读的字符串。

image

如何提升web3sdk的性能

使用jmeter进行压测的时候,发现tps只有几十
#sdk-threadPool-config corePoolSize: 50 maxPoolSize: 100 queueCapacity: 100 keepAlive: 60 timeout: 30000
修改corePoolSize、maxPoolSize后也没有多少提升,这样才能提高性能?

启动netty抛错

[nioEventLoopGroup-2-1] DEBUG NativeLibraryLoader(Slf4JLogger.java:81) - Unable to load the library 'netty_tcnative', trying other loading mechanism.
java.lang.UnsatisfiedLinkError: no netty_tcnative in java.library.path,大神麻烦看看?

TransactionRecipt status

I want to check wether my tx success executed.
So I found follow comment in source code.

    // status is only present on Byzantium transactions onwards
    // see EIP 658 https://github.com/ethereum/EIPs/pull/658
    private String status;
    private String from;

In EIP658, “0x0” means failure.
But from my experiement,
fisco bcos return “0x16” represent failure
“0x0” represent success.

FISCO-BCOS中client.keystore 的生成方法

FISCO-BCOS中client.keystore 的生成方法
1、client.keystore是用做web3sdk的SSL证书。
2、在web3sdk V1.0.0中,client.keystore里面有两个证书,一个client证书,一个ca证书。client.keystore的密码必须为“123456”,keystore中有私钥的client证书的密码也必须为“123456”。

V1.0.0版本的client.keystore生成方式:

(1)keytool -import -trustcacerts -alias ca -file ca.crt -keystore client.keystore
(2)openssl pkcs12 -export -name client -in server.crt -inkey server.key -out keystore.p12
(3)keytool -importkeystore -destkeystore client.keystore -srckeystore keystore.p12 -srcstoretype pkcs12 -alias client
(4)、Attention! Password must be ”123456”

注意:其中用到的ca.crt,必须是节点的ca.crt。server.crt,server.key 必须是节点的或者节点的兄弟证书(同一CA颁发)。

3、在web3sdk V1.1.0中,我们修改了证书这块的缺陷,client.keystore只保存client证书,而且命名和密码都做成了可配置。
相关的配置是这样的:

<bean class="org.bcos.channel.handler.ChannelConnections">
	<property name="caCertPath" value="classpath:ca.crt" />
	<property name="clientKeystorePath" value="classpath:client.keystore" />
	<property name="keystorePassWord" value="123456" />
	<property name="clientCertPassWord" value="123456" />
	<property name="connectionsStr">
		<list>
			<value>[email protected]:8822</value>
		</list>
	</property>
</bean>

V1.1.0版本的client.keystore生成方式:

(1)openssl pkcs12 -export -name client -in server.crt -inkey server.key -out keystore.p12
(2)keytool -importkeystore -destkeystore client.keystore -srckeystore keystore.p12 -srcstoretype pkcs12 -alias client

注意:server.crt,server.key 必须是节点的或者节点的兄弟证书(同一CA颁发)。

附录
常用的keystore命令:https://www.sslshopper.com/article-most-common-java-keytool-keystore-commands.html
keystore 和 openssl整合的命令:
http://www.herongyang.com/crypto/Migrating_Keys_keytool_to_OpenSSL_4.html

关于源码中验证peer结点证书的问题

在源码里面,首先判断preverify_ok等于true后,进行之后的判断逻辑
但是后面就算出错,比如
if (!cert)
{
HOST_LOG(ERROR) << LOG_DESC("Get cert failed");
return preverified;
}
直接返回true,这样不会有问题吗

Solc生成的合约EventValues对象类型映射错误

在solc中,会自动生成Java代码,其中每个event会生成一个对应的内部类PO,以EventResponse结尾,例如存在合约:

        event LogSetSArray(uint256[2] o, uint256[2] n);

对应的java代码为:

 public static class LogSetSArrayEventResponse {
        public Log log;

        public List<BigInteger> o;

        public List<BigInteger> n;
    }

但是,在最新的版本中,如果event中存在动态或静态数字的数组,会统一映射为 List,但是实际上的类型并非 List。

以上述类型为例,当调用时,实际的类型为原版本的映射类型,

		List<LogSetSArrayEventResponse> LogSetSArrayEventResponseList = contract.getLogSetSArrayEvents(receipt);

实际的类型为List:

[{"value":1,"typeAsString":"uint256"},{"value":2,"typeAsString":"uint256"}]

这个问题会导致下游系统对数据的解析产生错误。

加载pem账号文件时报错

加载本地.pem文件时报错,报错信息如下:java.lang.ClassCastException: org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey cannot be cast to org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey at org.fisco.bcos.web3j.crypto.ECKeyPair.create(ECKeyPair.java:52) at org.fisco.bcos.web3j.crypto.Keys.createEcKeyPair(Keys.java:59)

使用的是最新版的web3sdk, maven的方式依赖的

将ECKeyPair中的PrivateKey保存为.pem文件的方法

是否没有提供将PrivateKey保存的.pem的方法?

目前通过如下方法将PrivateKey保存为.pem

public void savePrivateKey(OutputStream outputStream, BigInteger privateKey) throws Exception{
        ECNamedCurveParameterSpec ecNamedCurveParameterSpec = ECNamedCurveTable.getParameterSpec("secp256k1");
        ECPrivateKeySpec ecPrivateKeySpec = new ECPrivateKeySpec(privateKey,ecNamedCurveParameterSpec);
        KeyFactory keyFactory = KeyFactory.getInstance("ECDSA");
        keyFactory.generatePrivate(ecPrivateKeySpec).getEncoded();
        outputStream.write(
                ("-----BEGIN PRIVATE KEY-----\n" +
                        Base64.encodeBase64String(keyFactory.generatePrivate(ecPrivateKeySpec).getEncoded()) +
                 "\n-----END PRIVATE KEY-----\n").getBytes()
        );
        outputStream.close();
    }

是否有其他内置方法可供调用?

项目中引用web3sdk,出现no content to map

排查后,发现是netty的版本问题,在web3sdk中引用的netty版本是4.1.15.final
问题在于:

  1. 因为web3sdk没有在maven仓库中有相关的版本,项目不能直接添加maven引用,只能本地引用jar lib
  2. web3sdk的readme中没有强调第三方jar包的依赖关系,建议写上

历史查询问题

合约里一个状态变量,一个set方法,多次执行set方法,对状态变量赋值不同的值,每次都返回交易的hash值,请问怎么通过交易的hash值, 获取到当时的交易的交易明细?

TransactionReceipt 没有合约写操作返回值

一个写操作交易完整返回值包含如下:
status
gas
transaction cost
execution cost
hash
decoded input
decoded output
logs | []
value
但是在TransactionReceipt没找到decoded output的值和类型,可否修改下返回序列化的类?虽然用log也能曲线救国,就感觉怪怪的

使用工具包生成合约Java Wrap代码时报错

https://github.com/FISCO-BCOS/web3sdk 下载代码(Download ZIP),解压之后,目录名称将为:web3sdk-master,运行gradle命令后生成的工具包中,/dist/apps目录下生成的jar包名称为web3sdk-master.jar,导致和/dist/bin/web3sdk中配置的CLASSPATH中的配置项$APP_HOME/apps/web3sdk.jar名称不一致,从而导致使用工具包生成合约Java Wrap代码时会报错。

TransactionDecoder解析带有数值类型的定长数组的参数错误Bug

在使用TransactionDecoder解析event的时候,当解析带有数值类型的定长数组的参数错误Bug。

例如,定义如下函数:

 event LogSetSArray(uint8[2] o, uint8[2] n);

function getSArray() public returns (uint8[2]){
            uint8[2] memory arr = [uint8(1),2];
            emit LogSetSArray(arr, _uint8SArray);
            return arr;
}

执行以后,会发现events解析为空,从控制台运行的结果就能看出来:


=============================================================================================
[group:1]> deploy ComplexSol 1 "1"
contract address: 0xec839b4a14c00ff2d002450599efd36e4819313d

[group:1]> call ComplexSol 0xec839b4a14c00ff2d002450599efd36e4819313d getSArray
transaction hash: 0xd65aa1a00ff469c158b8559d2d7e67673c7bc7dda86778a0fc3dabcd3db3ba8f
---------------------------------------------------------------------------------------------
Output
function: getSArray()
return type: (uint8[2])
return value: ([1, 2])
---------------------------------------------------------------------------------------------
Event logs
---------------------------------------------------------------------------------------------

查看web3sdk代码,发现问题的原因出在StaticArrayReference的create2函数,里面只支持转换为256类的数值类型。这会导致event所build的method id与event logs里面的topic内容不一致,造成无法解析event的错误。

相反,在js版本的web3j里,不存在同样的bug。

运行 deployAndCallHelloWorld 报错

java.lang.RuntimeException: org.fisco.bcos.web3j.protocol.exceptions.MessageDecodingException: {"error":{"code":-32601,"message":"METHOD_NOT_FOUND: The method being requested is not available on this server"},"id":1,"jsonrpc":"2.0"}

at org.fisco.bcos.web3j.tx.Contract.deploy(Contract.java:363)
at org.fisco.bcos.web3j.tx.Contract.lambda$deployRemoteCall$6(Contract.java:429)
at org.fisco.bcos.web3j.protocol.core.RemoteCall.send(RemoteCall.java:31)
at org.fisco.bcos.ContractTest.deployAndCallHelloWorld(ContractTest.java:48)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Caused by: org.fisco.bcos.web3j.protocol.exceptions.MessageDecodingException: {"error":{"code":-32601,"message":"METHOD_NOT_FOUND: The method being requested is not available on this server"},"id":1,"jsonrpc":"2.0"}

at org.fisco.bcos.web3j.protocol.channel.ChannelEthereumService.send(ChannelEthereumService.java:67)
at org.fisco.bcos.web3j.protocol.core.Request.send(Request.java:96)
at org.fisco.bcos.web3j.tx.RawTransactionManager.signAndSend(RawTransactionManager.java:128)
at org.fisco.bcos.web3j.tx.RawTransactionManager.sendTransaction(RawTransactionManager.java:95)
at org.fisco.bcos.web3j.tx.TransactionManager.executeTransaction(TransactionManager.java:53)
at org.fisco.bcos.web3j.tx.ManagedTransaction.send(ManagedTransaction.java:45)
at org.fisco.bcos.web3j.tx.Contract.executeTransaction(Contract.java:290)
at org.fisco.bcos.web3j.tx.Contract.create(Contract.java:333)
at org.fisco.bcos.web3j.tx.Contract.deploy(Contract.java:359)
... 33 

General SSLEngine problem 错误

我使用web3sdk的源代码建立web工程,利用节点生成的client.keystore文件,并放在了classes路径下,启动的时候,提示下面的内容,请大神看看是什么原因。谢谢
01:12:07.674 DEBUG org.bcos.channel.client.Service$ConnectionCallback 74 onConnect - 已建立连接,将topic发送到该连接:60ead22418294a009eddd53e12be293d
01:12:07.675 DEBUG org.bcos.channel.client.Service$ConnectionCallback 78 onConnect - topics: []
01:12:07.679 ERROR org.bcos.channel.handler.ChannelHandler 147 exceptionCaught - 网络错误 io.netty.handler.codec.DecoderException: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:459) ~[netty-all-4.1.15.Final.jar:4.1.15.Final]
at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:265) ~[netty-all-4.1.15.Final.jar:4.1.15.Final]
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) [netty-all-4.1.15.Final.jar:4.1.15.Final]

合约地址不对时,load合约不会报错

比如调用load合约方法:load(String contractAddress, Web3j web3j, Credentials credentials,
BigInteger gasPrice, BigInteger gasLimit)
结果不会报错,实际应该报错。

WalletUtils.isValidAddress() 只检查String长度

String addr1 = "0x0cc37d28ff272d0f92a402d29af4efc334bf3c7*";
return WalletUtils.isValidAddress(addr1);

这里返回的是true,因为代码里只做了长度检查

建议:首先检查是否为Hex字符串
WeID里面使用的正则表达式:0x[a-fA-f0-9]{40}

错误: 找不到或无法加载主类 org.bcos.web3j.console.Runner ending .

环境

OS:Ububtu16.04
websdk:1.2.0
fisco-solc:master

执行

bash compile.sh org.home.contract

抛出如下异常:

generate java code according to Evidence.sol abi, bin file...
/fiscobcos/web3sdk-1.2.0/tools/bin/../bin/web3sdk solidity generate /fiscobcos/web3sdk-1.2.0/tools/bin/../output/Evidence.bin /fiscobcos/web3sdk-1.2.0/tools/bin/../output/Evidence.abi -o /fiscobcos/web3sdk-1.2.0/tools/bin/../output -p org.home.contract
SystemContract Command reference is as follows
Usage:./web3sdk InitSystemContract
Usage:./web3sdk SystemProxy
Usage:./web3sdk NodeAction all|registerNode|cancelNode
Usage:./web3sdk CAAction all|add|remove
Usage:./web3sdk ConfigAction get|set
Usage:./web3sdk ConsensusControl deploy|turnoff|list
Usage:./web3sdk CNSAction add|update|get|list|historylist|reset
===================================================================
WEB3RPC Command reference is as follows
Usage: ./web3sdk web3_clientVersion 
Usage: ./web3sdk eth_accounts
Usage: ./web3sdk eth_blockNumber
Usage: ./web3sdk eth_pbftView
Usage: ./web3sdk eth_getCode address blockNumber
Usage: ./web3sdk eth_getBlockTransactionCountByHash blockHash
Usage: ./web3sdk eth_getTransactionCount address blockNumber
Usage: ./web3sdk eth_getBlockTransactionCountByNumber blockNumber
Usage: ./web3sdk eth_sendRawTransaction signTransactionData
Usage: ./web3sdk eth_getBlockByHash blockHash true|false
Usage: ./web3sdk eth_getBlockByNumber blockNumber
Usage: ./web3sdk eth_getTransactionByBlockNumberAndIndex blockNumber transactionPosition
Usage: ./web3sdk eth_getTransactionByBlockHashAndIndex blockHash transactionPosition
Usage: ./web3sdk eth_getTransactionReceipt transactionHash
===================================================================
Permission Command reference is as follows
Usage: ./web3sdk ARPI_Model 
Usage: ./web3sdk PermissionInfo 
Usage: ./web3sdk FilterChain addFilter name1 version1 desc1 
Usage: ./web3sdk FilterChain delFilter num 
Usage: ./web3sdk FilterChain showFilter 
Usage: ./web3sdk FilterChain resetFilter 
Usage: ./web3sdk Filter getFilterStatus num 
Usage: ./web3sdk Filter enableFilter num 
Usage: ./web3sdk Filter disableFilter num 
Usage: ./web3sdk Filter setUsertoNewGroup num account 
Usage: ./web3sdk Filter setUsertoExistingGroup num account group 
Usage: ./web3sdk Filter listUserGroup num account 
Usage: ./web3sdk Group getBlackStatus num account 
Usage: ./web3sdk Group enableBlack num account 
Usage: ./web3sdk Group disableBlack num account 
Usage: ./web3sdk Group getDeployStatus num account 
Usage: ./web3sdk Group enableDeploy num account 
Usage: ./web3sdk Group disableDeploy num account 
Usage: ./web3sdk Group addPermission num account A.address fun(string) 
Usage: ./web3sdk Group delPermission num account A.address fun(string) 
Usage: ./web3sdk Group checkPermission num account A.address fun(string) 
Usage: ./web3sdk Group listPermission num account 
错误: 找不到或无法加载主类 org.bcos.web3j.console.Runner

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.