Skip to content

Commit

Permalink
fix the websocket test pass
Browse files Browse the repository at this point in the history
  • Loading branch information
yanyanho committed Feb 11, 2020
1 parent 75c46fe commit e053440
Show file tree
Hide file tree
Showing 11 changed files with 652 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package com.webank.webase.front.base.properties;

import java.math.BigInteger;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

import lombok.Data;
Expand Down Expand Up @@ -56,8 +57,9 @@ public class Constants {
public static final String FILE_ADDRESS = ".address";
public static final String MGR_PRIVATE_KEY_URI = "http://%s/WeBASE-Node-Manager/user/privateKey/%s";
public static final String WEBASE_SIGN_URI = "http://%s/WeBASE-Sign/sign";
public static final String WEBASE_SIGN_URI_WEBSOCKET = "ws://%s/WeBASE-Sign/websocket/";
public static final String account1Path = "node.key";

public static String frontId = UUID.randomUUID().toString();
public static final String CONSTANT_PREFIX = "constant";
private String nodeDir = "";
private String keyServer = "127.0.0.1:8080";
Expand All @@ -69,6 +71,7 @@ public class Constants {
private Integer http_read_timeOut = 10000;
private Integer http_connect_timeOut = 10000;
private Integer sleep = 500;
private Integer websocket = 1;
public static int error = 0;


Expand Down
59 changes: 38 additions & 21 deletions src/main/java/com/webank/webase/front/keystore/KeyStoreService.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,7 @@
package com.webank.webase.front.keystore;

import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.*;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
Expand All @@ -26,6 +23,8 @@
import com.webank.webase.front.keystore.entity.EncodeInfo;
import com.webank.webase.front.keystore.entity.KeyStoreInfo;
import com.webank.webase.front.keystore.entity.SignInfo;
import com.webank.webase.front.transaction.websocket.SignMessage;
import com.webank.webase.front.transaction.websocket.WebSocketService;
import com.webank.webase.front.util.CredentialUtils;
import com.webank.webase.front.util.PemUtils;
import org.apache.commons.lang3.StringUtils;
Expand All @@ -35,6 +34,8 @@
import org.fisco.bcos.web3j.crypto.ECKeyPair;
import org.fisco.bcos.web3j.crypto.Keys;
import org.fisco.bcos.web3j.crypto.gm.GenCredential;
import org.fisco.bcos.web3j.protocol.core.Request;
import org.fisco.bcos.web3j.protocol.core.methods.response.NodeVersion;
import org.fisco.bcos.web3j.utils.Numeric;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
Expand Down Expand Up @@ -73,6 +74,8 @@ public class KeyStoreService {
static final int PUBLIC_KEY_LENGTH_IN_HEX = 128;
private static Map<String, String> PRIVATE_KEY_MAP = new HashMap<>();

@Autowired
WebSocketService webSocketService;

/**
* createKeyStore
Expand Down Expand Up @@ -264,23 +267,37 @@ public String getPrivateKey(String user, boolean useAes) {
* @return
*/
public String getSignDate(EncodeInfo params) {
try {
SignInfo signInfo = new SignInfo();
String url = String.format(Constants.WEBASE_SIGN_URI, constants.getKeyServer());
log.info("getSignDate url:{}", url);
HttpHeaders headers = CommonUtils.buildHeaders();
HttpEntity<String> formEntity =
new HttpEntity<String>(JSON.toJSONString(params), headers);
BaseResponse response =
restTemplate.postForObject(url, formEntity, BaseResponse.class);
log.info("getSignDate response:{}", JSON.toJSONString(response));
if (response.getCode() == 0) {
signInfo = CommonUtils.object2JavaBean(response.getData(), SignInfo.class);
}
return signInfo.getSignDataStr();
} catch (Exception e) {
log.error("***getSignDate exception", e);
}

try {
if (constants.getWebsocket().intValue() == 0) {
SignInfo signInfo = new SignInfo();
String url = String.format(Constants.WEBASE_SIGN_URI, constants.getKeyServer());
log.info("getSignDate url:{}", url);
HttpHeaders headers = CommonUtils.buildHeaders();
HttpEntity<String> formEntity =
new HttpEntity<String>(JSON.toJSONString(params), headers);
BaseResponse response =
restTemplate.postForObject(url, formEntity, BaseResponse.class);
log.info("getSignDate response:{}", JSON.toJSONString(response));
if (response.getCode() == 0) {
signInfo = CommonUtils.object2JavaBean(response.getData(), SignInfo.class);
}
return signInfo.getSignDataStr();
} else {
String frontId = Constants.frontId;
Request<?, SignMessage> request = new Request<>(
"sign&" + frontId,
Arrays.asList(params.getUserId().toString(), params.getEncodedDataStr()),
webSocketService,
SignMessage.class);

SignMessage signMessage = webSocketService.send(request, SignMessage.class);
return signMessage.getSignature();
}
}catch (Exception e) {
log.error("***getSignDate exception", e);
}

return null;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,8 @@ public String signMessage(int groupId, Web3j web3j, int userId, String contractA
SignatureData signData = CommonUtils.stringToSignatureData(signDataStr);
byte[] signedMessage = TransactionEncoder.encode(rawTransaction, signData);
signMsg = Numeric.toHexString(signedMessage);
} else {
}
else {
String chainId = (String) JSONObject.parseObject(versionContent).get("Chain Id");
ExtendedRawTransaction extendedRawTransaction =
ExtendedRawTransaction.createTransaction(randomid, constants.GAS_PRICE,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.webank.webase.front.transaction.websocket;


import org.fisco.bcos.web3j.protocol.core.Response;

/**
* eth_sign.
*/
public class SignMessage extends Response<String> {
public String getSignature() {
return getRawResponse();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package com.webank.webase.front.transaction.websocket;


import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.fisco.bcos.web3j.protocol.websocket.WebSocketListener;
import org.java_websocket.handshake.ServerHandshake;

import javax.websocket.*;
import java.io.IOException;
import java.net.URI;
import java.util.Map;
import java.util.Optional;

@Slf4j
public class WebSocketClient extends org.java_websocket.client.WebSocketClient{
private Optional<WebSocketListener> listenerOpt = Optional.empty();

public WebSocketClient(URI serverUri) {
super(serverUri);
}

@Override
public void onOpen(ServerHandshake serverHandshake) {
log.info("Opened WebSocket connection to {}", uri);
}

@OnMessage
public void onMessage(String s) {
log.debug("Received message {} from server {}", s, uri);
listenerOpt.ifPresent(listener -> {
try {
listener.onMessage(s);
} catch (Exception e) {
log.error("Failed to process message '{}' from server {}", s, uri, e);
}
});
}

@Override
public void onClose(int code, String reason, boolean remote) {
log.info("Closed WebSocket connection to {}, because of reason: '{}'."
+ "Connection closed remotely: {}", uri, reason, remote);
listenerOpt.ifPresent(WebSocketListener::onClose);
}

@Override
public void onError(Exception ex) {
log.error("WebSocket connection to {} failed with error", uri, ex);
listenerOpt.ifPresent(listener -> listener.onError(ex));

}

public void setListener(WebSocketListener listener) {
this.listenerOpt = Optional.ofNullable(listener);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.webank.webase.front.transaction.websocket;

import java.util.concurrent.CompletableFuture;

/**
* Objects necessary to process a reply for a request sent via WebSocket protocol.
*
* @param <T> type of a data item that should be returned by the sent request
*/
public class WebSocketRequest<T> {
private CompletableFuture<T> onReply;
private Class<T> responseType;

public WebSocketRequest(CompletableFuture<T> onReply, Class<T> responseType) {
this.onReply = onReply;
this.responseType = responseType;
}

public CompletableFuture<T> getOnReply() {
return onReply;
}

public Class<T> getResponseType() {
return responseType;
}
}
Loading

0 comments on commit e053440

Please sign in to comment.