Skip to content

Commit d107ca6

Browse files
authored
Add tars sdk impl (#818)
Add tars sdk impl (#818)
1 parent cf1cfff commit d107ca6

File tree

4 files changed

+204
-2
lines changed

4 files changed

+204
-2
lines changed

build.gradle

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ ext {
2828
slf4jApiVerison = '1.7.36'
2929
mockitoVersion = '4.8.0'
3030
gsonVersion = '2.10.1'
31+
tarsSDKVersion = '3.5.0-SNAPSHOT'
3132
}
3233

3334
// check.dependsOn integrationTest
@@ -59,8 +60,8 @@ allprojects {
5960
repositories {
6061
mavenCentral()
6162
maven { url "https://maven.aliyun.com/nexus/content/groups/public/" }
62-
maven { url "https://oss.sonatype.org/service/local/staging/deploy/maven2" }
6363
maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
64+
maven { url "https://oss.sonatype.org/service/local/staging/deploy/maven2" }
6465
}
6566

6667
dependencies {
@@ -124,6 +125,7 @@ googleJavaFormat {
124125
}
125126

126127
dependencies {
128+
api("org.fisco-bcos:fisco-bcos-tars-sdk:${tarsSDKVersion}")
127129
api("org.fisco-bcos:bcos-sdk-jni:${bcosSdkJniVersion}") {
128130
exclude group : "org.slf4j"
129131
exclude group : "com.fasterxml.jackson.core"
@@ -181,6 +183,7 @@ javadoc {
181183
task sourcesJar(type: Jar) {
182184
from sourceSets.main.allJava
183185
archiveClassifier = 'sources'
186+
duplicatesStrategy = 'warn'
184187
}
185188

186189
task javadocJar(type: Jar) {
@@ -207,7 +210,6 @@ tasks.withType(Test) {
207210
publishing {
208211
publications {
209212
mavenJava(MavenPublication) {
210-
211213
artifactId "fisco-bcos-" + project.name
212214
groupId project.group
213215
version project.version

src/main/java/org/fisco/bcos/sdk/v3/BcosSDK.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import org.fisco.bcos.sdk.jni.BlockNotifier;
1818
import org.fisco.bcos.sdk.v3.amop.Amop;
1919
import org.fisco.bcos.sdk.v3.client.Client;
20+
import org.fisco.bcos.sdk.v3.client.TarsClient;
2021
import org.fisco.bcos.sdk.v3.config.Config;
2122
import org.fisco.bcos.sdk.v3.config.ConfigOption;
2223
import org.fisco.bcos.sdk.v3.config.exceptions.ConfigException;
@@ -89,6 +90,15 @@ public Client getClient(String groupId) throws BcosSDKException {
8990
}
9091
}
9192

93+
public TarsClient getTarsClient(String groupID) {
94+
try {
95+
return TarsClient.build(groupID, config, bcosSDKJniObj.getNativePointer());
96+
} catch (Exception e) {
97+
logger.warn("create client for failed, error: ", e);
98+
throw new BcosSDKException("get Client failed, e: " + e.getMessage(), e);
99+
}
100+
}
101+
92102
/**
93103
* Get a Client instance of default group in config
94104
*
Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
package org.fisco.bcos.sdk.v3.client;
2+
3+
import java.math.BigInteger;
4+
import java.net.URL;
5+
import java.util.Objects;
6+
import java.util.concurrent.ArrayBlockingQueue;
7+
import java.util.concurrent.ThreadPoolExecutor;
8+
import java.util.concurrent.TimeUnit;
9+
import java.util.stream.Collectors;
10+
import org.fisco.bcos.sdk.tars.Callback;
11+
import org.fisco.bcos.sdk.tars.Config;
12+
import org.fisco.bcos.sdk.tars.CryptoSuite;
13+
import org.fisco.bcos.sdk.tars.LogEntry;
14+
import org.fisco.bcos.sdk.tars.RPCClient;
15+
import org.fisco.bcos.sdk.tars.SWIGTYPE_p_bcos__bytesConstRef;
16+
import org.fisco.bcos.sdk.tars.SWIGTYPE_p_bcos__h256;
17+
import org.fisco.bcos.sdk.tars.SWIGTYPE_p_std__vectorT_unsigned_char_t;
18+
import org.fisco.bcos.sdk.tars.SendTransaction;
19+
import org.fisco.bcos.sdk.tars.StringVector;
20+
import org.fisco.bcos.sdk.tars.Transaction;
21+
import org.fisco.bcos.sdk.tars.TransactionFactoryImpl;
22+
import org.fisco.bcos.sdk.tars.TransactionReceipt;
23+
import org.fisco.bcos.sdk.tars.bcos;
24+
import org.fisco.bcos.sdk.v3.client.protocol.response.BcosTransactionReceipt;
25+
import org.fisco.bcos.sdk.v3.config.ConfigOption;
26+
import org.fisco.bcos.sdk.v3.model.callback.TransactionCallback;
27+
import org.fisco.bcos.sdk.v3.utils.Hex;
28+
import org.slf4j.Logger;
29+
import org.slf4j.LoggerFactory;
30+
31+
public class TarsClient extends ClientImpl implements Client {
32+
private static Logger logger = LoggerFactory.getLogger(TarsClient.class);
33+
private RPCClient tarsRPCClient;
34+
private TransactionFactoryImpl transactionFactory;
35+
private ThreadPoolExecutor asyncThreadPool;
36+
static final int queueSize = 10 * 10000;
37+
static final String libFileName = System.mapLibraryName("bcos_swig_java");
38+
39+
protected TarsClient(String groupID, ConfigOption configOption, long nativePointer) {
40+
super(groupID, configOption, nativePointer);
41+
String connectionString =
42+
RPCClient.toConnectionString(
43+
new StringVector(configOption.getNetworkConfig().getTarsPeers()));
44+
45+
logger.info("Tars connection: {}", connectionString);
46+
Config config = new Config();
47+
config.setConnectionString(connectionString);
48+
config.setSendQueueSize(queueSize);
49+
config.setTimeoutMs(configOption.getNetworkConfig().getTimeout() * 1000);
50+
tarsRPCClient = new RPCClient(config);
51+
52+
CryptoSuite cryptoSuite =
53+
bcos.newCryptoSuite(configOption.getCryptoMaterialConfig().getUseSmCrypto());
54+
transactionFactory = new TransactionFactoryImpl(cryptoSuite);
55+
asyncThreadPool =
56+
new ThreadPoolExecutor(
57+
1,
58+
configOption.getThreadPoolConfig().getThreadPoolSize(),
59+
0,
60+
TimeUnit.SECONDS,
61+
new ArrayBlockingQueue<Runnable>(queueSize));
62+
}
63+
64+
public static void loadLibrary() {
65+
URL configUrl = TarsClient.class.getClassLoader().getResource(libFileName);
66+
System.load(configUrl.getPath());
67+
}
68+
69+
public static void loadLibrary(String libPath) {
70+
System.load(libPath);
71+
}
72+
73+
public static TarsClient build(String groupId, ConfigOption configOption, long nativePointer) {
74+
logger.info(
75+
"build, groupID: {}, configOption: {}, nativePointer: {}",
76+
groupId,
77+
configOption,
78+
nativePointer);
79+
return new TarsClient(groupId, configOption, nativePointer);
80+
}
81+
82+
@Override
83+
public BcosTransactionReceipt sendTransaction(
84+
String node, String signedTransactionData, boolean withProof) {
85+
if (withProof) {
86+
return super.sendTransaction(node, signedTransactionData, withProof);
87+
}
88+
node = Objects.isNull(node) ? "" : node;
89+
90+
Transaction transaction = toTransaction(signedTransactionData);
91+
TransactionReceipt receipt = new SendTransaction(tarsRPCClient).send(transaction).get();
92+
BcosTransactionReceipt bcosReceipt = new BcosTransactionReceipt();
93+
bcosReceipt.setResult(toJSONTransactionReceipt(receipt, transaction));
94+
95+
return bcosReceipt;
96+
}
97+
98+
@Override
99+
public void sendTransactionAsync(
100+
String node,
101+
String signedTransactionData,
102+
boolean withProof,
103+
TransactionCallback callback) {
104+
if (withProof) {
105+
super.sendTransactionAsync(node, signedTransactionData, withProof, callback);
106+
return;
107+
}
108+
node = Objects.isNull(node) ? "" : node;
109+
Transaction transaction = toTransaction(signedTransactionData);
110+
SendTransaction sendTransaction = new SendTransaction(tarsRPCClient);
111+
112+
sendTransaction.setCallback(
113+
new Callback() {
114+
public void onMessage() {
115+
asyncThreadPool.submit(
116+
() -> {
117+
TransactionReceipt receipt = sendTransaction.get();
118+
callback.onResponse(
119+
toJSONTransactionReceipt(receipt, transaction));
120+
});
121+
}
122+
});
123+
sendTransaction.send(transaction);
124+
}
125+
126+
private Transaction toTransaction(String signedTransactionData) {
127+
byte[] transactionBytes = Hex.decode(signedTransactionData);
128+
129+
SWIGTYPE_p_std__vectorT_unsigned_char_t vectorTransactionBytes =
130+
bcos.toBytes(transactionBytes);
131+
SWIGTYPE_p_bcos__bytesConstRef ref = bcos.toBytesConstRef(vectorTransactionBytes);
132+
Transaction transaction = transactionFactory.createTransaction(ref, false, false);
133+
return transaction;
134+
}
135+
136+
private org.fisco.bcos.sdk.v3.model.TransactionReceipt toJSONTransactionReceipt(
137+
TransactionReceipt receipt, Transaction transaction) {
138+
org.fisco.bcos.sdk.v3.model.TransactionReceipt jsonReceipt =
139+
new org.fisco.bcos.sdk.v3.model.TransactionReceipt();
140+
jsonReceipt.setTransactionHash("0x" + bcos.toHex(transaction.hash()));
141+
jsonReceipt.setVersion(receipt.version());
142+
jsonReceipt.setReceiptHash("0x" + bcos.toHex(receipt.hash()));
143+
jsonReceipt.setBlockNumber(BigInteger.valueOf(receipt.blockNumber()));
144+
jsonReceipt.setFrom(bcos.toString(transaction.sender()));
145+
jsonReceipt.setTo(bcos.toString(transaction.to()));
146+
jsonReceipt.setGasUsed(bcos.toString(receipt.gasUsed()));
147+
jsonReceipt.setContractAddress(bcos.toString(receipt.contractAddress()));
148+
jsonReceipt.setChecksumContractAddress(jsonReceipt.getContractAddress()); // FIXME: how to?
149+
jsonReceipt.setLogEntries(
150+
bcos.logEntrySpanToVector(receipt.logEntries()).stream()
151+
.map(
152+
(LogEntry logEntry) -> {
153+
org.fisco.bcos.sdk.v3.model.TransactionReceipt.Logs
154+
rawLogEntry =
155+
new org.fisco.bcos.sdk.v3.model
156+
.TransactionReceipt.Logs();
157+
rawLogEntry.setAddress(bcos.toString(logEntry.address()));
158+
rawLogEntry.setBlockNumber(
159+
String.valueOf(receipt.blockNumber()));
160+
rawLogEntry.setData("0x" + bcos.toHex(logEntry.data()));
161+
rawLogEntry.setTopics(
162+
bcos.h256SpanToVector(logEntry.topics()).stream()
163+
.map(
164+
(SWIGTYPE_p_bcos__h256 hash) -> {
165+
return "0x" + bcos.toHex(hash);
166+
})
167+
.collect(Collectors.toList()));
168+
return rawLogEntry;
169+
})
170+
.collect(Collectors.toList()));
171+
jsonReceipt.setStatus(receipt.status());
172+
jsonReceipt.setInput("0x" + bcos.toHex(transaction.input()));
173+
jsonReceipt.setOutput("0x" + bcos.toHex(receipt.output()));
174+
jsonReceipt.setExtraData(bcos.toString(transaction.extraData()));
175+
176+
return jsonReceipt;
177+
}
178+
}

src/main/java/org/fisco/bcos/sdk/v3/config/model/NetworkConfig.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ public class NetworkConfig {
2727
private static final Logger logger = LoggerFactory.getLogger(NetworkConfig.class);
2828

2929
private List<String> peers;
30+
private List<String> tarsPeers;
3031
private int timeout = -1;
3132
private String defaultGroup;
3233
private boolean sendRpcRequestToHighestBlockNode = true;
@@ -37,6 +38,7 @@ public NetworkConfig(ConfigProperty configProperty) {
3738
Map<String, Object> networkProperty = configProperty.getNetwork();
3839
if (networkProperty != null) {
3940
peers = (List<String>) networkProperty.get("peers");
41+
tarsPeers = (List<String>) networkProperty.get("tarsPeers");
4042
defaultGroup = (String) networkProperty.get("defaultGroup");
4143
Object value = networkProperty.get("messageTimeout");
4244
if (Objects.nonNull(value)) {
@@ -63,6 +65,14 @@ public void setPeers(List<String> peers) {
6365
this.peers = peers;
6466
}
6567

68+
public List<String> getTarsPeers() {
69+
return tarsPeers;
70+
}
71+
72+
public void setTarsPeers(List<String> tarsPeers) {
73+
this.tarsPeers = tarsPeers;
74+
}
75+
6676
public String getDefaultGroup() {
6777
return defaultGroup;
6878
}
@@ -92,6 +102,8 @@ public String toString() {
92102
return "NetworkConfig{"
93103
+ "peers="
94104
+ peers
105+
+ ", tarsPeers="
106+
+ tarsPeers
95107
+ ", timeout="
96108
+ timeout
97109
+ ", defaultGroup='"

0 commit comments

Comments
 (0)