Skip to content

Commit

Permalink
<feat>(test): client,connection,account unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
yangfang2 committed Aug 16, 2024
1 parent 058dd57 commit 15791cc
Show file tree
Hide file tree
Showing 24 changed files with 1,227 additions and 14 deletions.
8 changes: 5 additions & 3 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -90,13 +90,15 @@ dependencies {
exclude group: "io.netty"
exclude group: 'org.fisco-bcos', module: 'tcnative'
}
implementation('org.fisco-bcos.java-sdk:fisco-bcos-sdk-abi:2.10.0-SNAPSHOT')
implementation 'org.fisco-bcos.java-sdk:fisco-bcos-sdk-abi:2.10.0-SNAPSHOT'
implementation 'org.web3j:core:4.9.8'

// implementation('org.fisco-bcos.java-sdk:fisco-bcos-sdk-abi:2.10.0-SNAPSHOT')

// Use JUnit test framework
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.slf4j:slf4j-log4j12:2.0.5'

integTestImplementation 'junit:junit:4.13.2'
integTestImplementation 'org.slf4j:slf4j-log4j12:2.0.5'
}

sourceSets {
Expand Down
27 changes: 27 additions & 0 deletions src/main/java/com/webank/wecross/stub/web3/Web3Connection.java
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,13 @@ private void handleAsyncGetBlockNumberRequest(Callback callback) {
response.setErrorMessage(Web3StatusCode.getStatusMessage(Web3StatusCode.Success));
try {
BigInteger blockNumber = clientWrapper.ethBlockNumber();
if (Objects.isNull(blockNumber)) {
response.setErrorCode(Web3StatusCode.BlockNumberNotExist);
response.setErrorMessage(
Web3StatusCode.getStatusMessage(Web3StatusCode.BlockNumberNotExist));
return;
}

if (logger.isDebugEnabled()) {
logger.debug("handleAsyncGetBlockNumberRequest,blockNumber: {}", blockNumber);
}
Expand Down Expand Up @@ -211,6 +218,12 @@ private void handleAsyncCallRequest(Request request, Callback callback) {
from, to, data);
EthCall ethCall = clientWrapper.ethCall(transaction);

if (Objects.isNull(ethCall)) {
response.setErrorCode(Web3StatusCode.CallNotSuccessStatus);
response.setErrorMessage("ethCall is null");
return;
}

// ethCall has error
if (ethCall.hasError()) {
response.setErrorCode(Web3StatusCode.CallNotSuccessStatus);
Expand Down Expand Up @@ -244,6 +257,13 @@ private void handleAsyncTransactionRequest(Request request, Callback callback) {
EthSendTransaction ethSendTransaction =
clientWrapper.ethSendRawTransaction(signedTransactionData);

if (Objects.isNull(ethSendTransaction)) {
response.setErrorCode(Web3StatusCode.TransactionReceiptNotExist);
response.setErrorMessage(
Web3StatusCode.getStatusMessage(Web3StatusCode.TransactionReceiptNotExist));
return;
}

// ethSendTransaction has error
if (ethSendTransaction.hasError()) {
response.setErrorCode(Web3StatusCode.SendTransactionNotSuccessStatus);
Expand All @@ -253,6 +273,13 @@ private void handleAsyncTransactionRequest(Request request, Callback callback) {

// get transactionReceipt
String transactionHash = ethSendTransaction.getTransactionHash();
if (StringUtils.isBlank(transactionHash)) {
response.setErrorCode(Web3StatusCode.TransactionReceiptNotExist);
response.setErrorMessage(
Web3StatusCode.getStatusMessage(Web3StatusCode.TransactionReceiptNotExist));
return;
}

TransactionReceipt transactionReceipt =
clientWrapper.ethGetTransactionReceipt(transactionHash);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.webank.wecross.stub.web3.common.Web3Constant;
import com.webank.wecross.stub.web3.config.Web3AccountConfig;
import com.webank.wecross.stub.web3.config.Web3AccountConfigParser;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
Expand Down Expand Up @@ -67,6 +68,8 @@ public static Web3Account build(Map<String, Object> properties) {
// build credentials from privateKey
Credentials credentials = Credentials.create(secKey);
Web3Account web3Account = new Web3Account(username, type, credentials);
web3Account.setDefault(isDefault);
web3Account.setKeyID(keyID);

// check publicKey
if (!Objects.equals(web3Account.getPublicKey(), pubKey)) {
Expand All @@ -84,7 +87,8 @@ public static Web3Account build(Map<String, Object> properties) {
}
}

public Web3Account build(String name, String accountPath) throws IOException, CipherException {
public static Web3Account build(String name, String accountPath)
throws IOException, CipherException {
Web3AccountConfigParser parser =
new Web3AccountConfigParser(accountPath, Web3Constant.ACCOUNT_TOML_NAME);
Web3AccountConfig web3AccountConfig = parser.loadConfig();
Expand All @@ -94,7 +98,7 @@ public Web3Account build(String name, String accountPath) throws IOException, Ci
String password = account.getPassword();

ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource accountFileResource = resolver.getResource(accountFile);
Resource accountFileResource = resolver.getResource(accountPath + File.separator + accountFile);

Credentials credentials;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@

import java.io.IOException;
import java.math.BigInteger;
import org.reactivestreams.Subscriber;
import org.web3j.protocol.core.methods.request.EthFilter;
import org.web3j.protocol.core.methods.response.EthBlock;
import org.web3j.protocol.core.methods.response.EthCall;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.protocol.core.methods.response.Log;
import org.web3j.protocol.core.methods.response.Transaction;
import org.web3j.protocol.core.methods.response.TransactionReceipt;

Expand All @@ -31,4 +34,6 @@ EthCall ethCall(org.web3j.protocol.core.methods.request.Transaction transaction)
BigInteger ethGasPrice() throws IOException;

BigInteger ethGasLimit() throws IOException;

void subscribe(EthFilter ethFilter, Subscriber<Log> subscriber);
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,19 @@
import java.math.BigInteger;
import java.util.Objects;
import java.util.Optional;
import org.reactivestreams.Subscriber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameter;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.request.EthFilter;
import org.web3j.protocol.core.methods.response.EthBlock;
import org.web3j.protocol.core.methods.response.EthCall;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.protocol.core.methods.response.EthGetTransactionReceipt;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.protocol.core.methods.response.Log;
import org.web3j.protocol.core.methods.response.Transaction;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.utils.RevertReasonExtractor;
Expand Down Expand Up @@ -119,6 +122,11 @@ public BigInteger ethGasLimit() throws IOException {
return web3j.ethMaxPriorityFeePerGas().send().getMaxPriorityFeePerGas();
}

@Override
public void subscribe(EthFilter ethFilter, Subscriber<Log> subscriber) {
web3j.ethLogFlowable(ethFilter).safeSubscribe(subscriber);
}

public String extractRevertReason(TransactionReceipt transactionReceipt, String data)
throws IOException {
String revertReason =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,14 @@ public class Web3StatusCode {
public static final int TransactionReceiptNotExist = 2010;
public static final int TransactionNotExist = 2011;
public static final int BlockNotExist = 2012;
public static final int TransactionProofNotExist = 2013;
public static final int TransactionReceiptProofNotExist = 2014;
public static final int BlockNumberNotExist = 2013;

public static final int HandleSendTransactionFailed = 2021;
public static final int HandleCallRequestFailed = 2022;
public static final int HandleGetBlockNumberFailed = 2023;
public static final int HandleGetBlockFailed = 2024;
public static final int HandleGetTransactionFailed = 2025;
public static final int ListResourcesFailed = 2026;
public static final int RegisterContractFailed = 2027;
public static final int RegisterContractFailed = 2026;

public static final int CallNotSuccessStatus = 2030;
public static final int SendTransactionNotSuccessStatus = 2031;
Expand Down Expand Up @@ -64,11 +62,8 @@ public static String getStatusMessage(int status) {
case TransactionNotExist:
message = "transaction not exist";
break;
case TransactionProofNotExist:
message = "transaction proof not exist";
break;
case TransactionReceiptProofNotExist:
message = "transaction receipt proof not exist";
case BlockNumberNotExist:
message = "block number not exist";
break;
case BlockNotExist:
message = "block not exist";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public List<ResourceInfo> convertToResourceInfos() {
resourceInfo.setStubType(this.getCommon().getType());

Map<Object, Object> properties = resourceInfo.getProperties();
properties.put(Web3Constant.WEB3_PROPERTY_CHAIN_URL, this.getService().getUrl());
properties.put(resource.getName(), resource.getAddress());
properties.put(resource.getName() + Web3Constant.WEB3_PROPERTY_ABI_SUFFIX, resource.getAbi());
resourceInfos.add(resourceInfo);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package com.webank.wecross.stub.web3.event;

import com.webank.wecross.stub.web3.client.ClientWrapper;
import com.webank.wecross.stub.web3.config.Web3StubConfig;
import java.util.Arrays;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.web3j.abi.EventEncoder;
import org.web3j.abi.TypeReference;
import org.web3j.abi.datatypes.Address;
import org.web3j.abi.datatypes.DynamicArray;
import org.web3j.abi.datatypes.Event;
import org.web3j.abi.datatypes.Utf8String;
import org.web3j.abi.datatypes.generated.Uint256;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.request.EthFilter;
import org.web3j.protocol.core.methods.response.Log;

public class Web3ChainEventManager {
private static final Logger logger = LoggerFactory.getLogger(Web3ChainEventManager.class);

private final ClientWrapper clientWrapper;

public static final String LUYU_CALL = "LuyuCall";
public static final String LUYU_SEND_TRANSACTION = "LuyuSendTransaction";

public static final Event LUYUCALL_EVENT =
new Event(
LUYU_CALL,
Arrays.asList(
new TypeReference<Utf8String>() {},
new TypeReference<Utf8String>() {},
new TypeReference<DynamicArray<Utf8String>>() {},
new TypeReference<Uint256>() {},
new TypeReference<Utf8String>() {},
new TypeReference<Utf8String>() {},
new TypeReference<Address>() {}));

public static final Event LUYUSENDTRANSACTION_EVENT =
new Event(
LUYU_SEND_TRANSACTION,
Arrays.asList(
new TypeReference<Utf8String>() {},
new TypeReference<Utf8String>() {},
new TypeReference<DynamicArray<Utf8String>>() {},
new TypeReference<Uint256>() {},
new TypeReference<Utf8String>() {},
new TypeReference<Utf8String>() {},
new TypeReference<Address>() {}));

public Web3ChainEventManager(ClientWrapper clientWrapper) {
this.clientWrapper = clientWrapper;
}

public void registerEvent(Web3StubConfig.Resource resource) {
registerEvent(resource.getName(), resource.getAddress(), LUYUCALL_EVENT);
registerEvent(resource.getName(), resource.getAddress(), LUYUSENDTRANSACTION_EVENT);
}

private void registerEvent(String resourceName, String address, Event event) {
EthFilter ethFilter =
new EthFilter(
DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST, address);
String encodedEventSignature = EventEncoder.encode(event);
ethFilter.addSingleTopic(encodedEventSignature);

clientWrapper.subscribe(
ethFilter,
new Subscriber<Log>() {
@Override
public void onSubscribe(Subscription subscription) {
subscription.request(Long.MAX_VALUE);
}

@Override
public void onNext(Log log) {
// TODO handle events based on event name
String eventName = event.getName();
}

@Override
public void onError(Throwable throwable) {}

@Override
public void onComplete() {
registerEvent(resourceName, address, event);
}
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.webank.wecross.stub.web3;

import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertTrue;

import com.webank.wecross.stub.web3.account.Web3Account;
import com.webank.wecross.stub.web3.account.Web3AccountFactory;
import java.io.IOException;
import java.util.Objects;
import org.junit.Test;
import org.web3j.crypto.CipherException;

public class Web3AccountFactoryTest {

@Test
public void buildAccountTest() throws CipherException, IOException {
Web3Account web3Account = Web3AccountFactory.build("wallet", "./account");

assertTrue(Objects.nonNull(web3Account));
assertEquals(web3Account.getName(), "wallet");
assertEquals(web3Account.getType(), "WEB3");
assertEquals(web3Account.getIdentity(), "0x698d83382f9ffb72271cd0826479e8ab02077842");
assertEquals(
web3Account.getPublicKey(),
"ab1c9d486b269adbb604766daf7d209440663299dd78b229ffcf728568b6b8a93c8a096ca4328d93040a0c8b4bd448e0e2da2566bf252845426f806a053d2cc6");
}
}
Loading

0 comments on commit 15791cc

Please sign in to comment.