Skip to content

Commit

Permalink
Merge pull request #157 from WeBankFinTech/feature/batch-evidence
Browse files Browse the repository at this point in the history
* Add Batch Evidence creation interface
  • Loading branch information
chaoxinhu committed Apr 9, 2020
2 parents f742e57 + b85d7a4 commit 4afd79e
Show file tree
Hide file tree
Showing 7 changed files with 131 additions and 50 deletions.
6 changes: 4 additions & 2 deletions src/main/java/com/webank/weid/constant/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,8 @@ public enum ErrorCode {
/**
* The credential issuer mismatch.
*/
CREDENTIAL_ISSUER_MISMATCH(100403, "issuer weId does not match the weId of credential"),
CREDENTIAL_ISSUER_MISMATCH(100403,
"issuer weId does not match the weId of credential"),

/**
* The credential signature broken.
Expand Down Expand Up @@ -323,7 +324,8 @@ public enum ErrorCode {
/**
* The credential evidence interface does not support fisco bcos 1.3.
*/
FISCO_BCOS_VERSION_NOT_SUPPORTED(170000, "this function does not support current fisco bcos version"),
FISCO_BCOS_VERSION_NOT_SUPPORTED(170000,
"this function does not support current fisco bcos version"),

/**
* On-chain string length exceeded acceptable max.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,28 +110,28 @@ private static Persistence getDataDriver() {
}
return dataDriver;
}

private static WeIdService getWeIdService() {
if (weIdService == null) {
weIdService = new WeIdServiceImpl();
}
return weIdService;
}

private static CptService getCptService() {
if (cptService == null) {
cptService = new CptServiceImpl();
}
return cptService;
}

private static PdfTransportation getPdfTransportation() {
if (pdfTransportation == null) {
pdfTransportation = new PdfTransportationImpl();
}
return pdfTransportation;
}

/**
* Salt generator. Automatically fillin the map structure in a recursive manner.
*
Expand Down Expand Up @@ -738,7 +738,8 @@ private static UserResult makeCredential(

Map<String, String> credentialInfoMap = buildCredentialInfo(preCredential, claimJson);

ResponseData<CredentialTemplateEntity> resp = getCptService().queryCredentialTemplate(cptId);
ResponseData<CredentialTemplateEntity> resp = getCptService()
.queryCredentialTemplate(cptId);
CredentialTemplateEntity credentialTemplate = resp.getResult();

UserResult userResult = UserClient.makeCredential(credentialInfoMap, credentialTemplate);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,9 @@ public ResponseData<String> createEvidenceWithLogAndCustomKey(
if (!isChainStringLengthValid(log) || !isChainStringLengthValid(customKey)) {
return new ResponseData<>(StringUtils.EMPTY, ErrorCode.ON_CHAIN_STRING_TOO_LONG);
}
if (StringUtils.isEmpty(customKey)) {
customKey = StringUtils.EMPTY;
}
ResponseData<String> hashResp = getHashValue(object);
String hashValue = hashResp.getResult();
if (StringUtils.isEmpty(hashResp.getResult())) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,12 +95,6 @@ public ResponseData<String> createEvidence(
String privateKey
) {
try {
EvidenceContract evidenceContractWriter =
reloadContract(
fiscoConfig.getEvidenceAddress(),
privateKey,
EvidenceContract.class
);
List<byte[]> hashByteList = new ArrayList<>();
hashByteList.add(DataToolUtils.convertHashStrIntoHashByte32Array(hashValue));
String address = WeIdUtils
Expand All @@ -113,6 +107,12 @@ public ResponseData<String> createEvidence(
logList.add(extra);
List<BigInteger> timestampList = new ArrayList<>();
timestampList.add(new BigInteger(String.valueOf(timestamp), 10));
EvidenceContract evidenceContractWriter =
reloadContract(
fiscoConfig.getEvidenceAddress(),
privateKey,
EvidenceContract.class
);
TransactionReceipt receipt =
evidenceContractWriter.createEvidence(
hashByteList,
Expand Down Expand Up @@ -158,12 +158,6 @@ public ResponseData<List<Boolean>> batchCreateEvidence(
result.add(false);
}
try {
EvidenceContract evidenceContractWriter =
reloadContract(
fiscoConfig.getEvidenceAddress(),
privateKey,
EvidenceContract.class
);
List<byte[]> hashByteList = new ArrayList<>();
List<String> signerList = new ArrayList<>();
List<BigInteger> timestampList = new ArrayList<>();
Expand All @@ -173,6 +167,12 @@ public ResponseData<List<Boolean>> batchCreateEvidence(
signerList.add(WeIdUtils.convertWeIdToAddress(signers.get(i)));
timestampList.add(new BigInteger(String.valueOf(timestamp.get(i)), 10));
}
EvidenceContract evidenceContractWriter =
reloadContract(
fiscoConfig.getEvidenceAddress(),
privateKey,
EvidenceContract.class
);
TransactionReceipt receipt =
evidenceContractWriter.createEvidence(
hashByteList,
Expand All @@ -198,7 +198,8 @@ public ResponseData<List<Boolean>> batchCreateEvidence(
.getValue()));
}
}
return new ResponseData<>(DataToolUtils.strictCheckExistence(hashValues, returnedHashs),
return new ResponseData<>(
DataToolUtils.strictCheckExistence(hashValues, returnedHashs),
ErrorCode.SUCCESS, info);
}
} catch (Exception e) {
Expand All @@ -222,12 +223,6 @@ public ResponseData<List<Boolean>> batchCreateEvidenceWithCustomKey(
result.add(false);
}
try {
EvidenceContract evidenceContractWriter =
reloadContract(
fiscoConfig.getEvidenceAddress(),
privateKey,
EvidenceContract.class
);
List<byte[]> hashByteList = new ArrayList<>();
List<String> signerList = new ArrayList<>();
List<BigInteger> timestampList = new ArrayList<>();
Expand All @@ -237,6 +232,12 @@ public ResponseData<List<Boolean>> batchCreateEvidenceWithCustomKey(
signerList.add(WeIdUtils.convertWeIdToAddress(signers.get(i)));
timestampList.add(new BigInteger(String.valueOf(timestamp.get(i)), 10));
}
EvidenceContract evidenceContractWriter =
reloadContract(
fiscoConfig.getEvidenceAddress(),
privateKey,
EvidenceContract.class
);
TransactionReceipt receipt =
evidenceContractWriter.createEvidenceWithExtraKey(
hashByteList,
Expand All @@ -263,7 +264,8 @@ public ResponseData<List<Boolean>> batchCreateEvidenceWithCustomKey(
.getValue()));
}
}
return new ResponseData<>(DataToolUtils.strictCheckExistence(hashValues, returnedHashs),
return new ResponseData<>(
DataToolUtils.strictCheckExistence(hashValues, returnedHashs),
ErrorCode.SUCCESS, info);
}
} catch (Exception e) {
Expand All @@ -280,12 +282,6 @@ public ResponseData<Boolean> addLog(
String privateKey
) {
try {
EvidenceContract evidenceContractWriter =
reloadContract(
fiscoConfig.getEvidenceAddress(),
privateKey,
EvidenceContract.class
);
List<byte[]> hashByteList = new ArrayList<>();
hashByteList.add(DataToolUtils.convertHashStrIntoHashByte32Array(hashValue));
List<String> sigList = new ArrayList<>();
Expand All @@ -298,6 +294,13 @@ public ResponseData<Boolean> addLog(
.convertWeIdToAddress(DataToolUtils.convertPrivateKeyToDefaultWeId(privateKey));
List<String> signerList = new ArrayList<>();
signerList.add(address);
EvidenceContract evidenceContractWriter =
reloadContract(
fiscoConfig.getEvidenceAddress(),
privateKey,
EvidenceContract.class
);
signerList.add(address);
TransactionReceipt receipt =
evidenceContractWriter.createEvidence(
hashByteList,
Expand Down Expand Up @@ -562,12 +565,6 @@ public ResponseData<String> createEvidenceWithCustomKey(
String extraKey,
String privateKey) {
try {
EvidenceContract evidenceContractWriter =
reloadContract(
fiscoConfig.getEvidenceAddress(),
privateKey,
EvidenceContract.class
);
List<byte[]> hashByteList = new ArrayList<>();
hashByteList.add(DataToolUtils.convertHashStrIntoHashByte32Array(hashValue));
String address = WeIdUtils
Expand All @@ -582,6 +579,12 @@ public ResponseData<String> createEvidenceWithCustomKey(
timestampList.add(new BigInteger(String.valueOf(timestamp), 10));
List<String> extraKeyList = new ArrayList<>();
extraKeyList.add(extraKey);
EvidenceContract evidenceContractWriter =
reloadContract(
fiscoConfig.getEvidenceAddress(),
privateKey,
EvidenceContract.class
);
TransactionReceipt receipt =
evidenceContractWriter.createEvidenceWithExtraKey(
hashByteList,
Expand Down
44 changes: 36 additions & 8 deletions src/main/java/com/webank/weid/util/DataToolUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -1783,6 +1783,13 @@ public static boolean isLocalAddress(String host) {
}
}

/**
* Convert a hash string (0x[64Bytes]) into a byte array with 32 bytes length by compressing
* each two nearby characters into one.
*
* @param hash hash String
* @return byte array
*/
public static byte[] convertHashStrIntoHashByte32Array(String hash) {
if (!isValidHash(hash)) {
return null;
Expand All @@ -1798,8 +1805,15 @@ public static byte[] convertHashStrIntoHashByte32Array(String hash) {
return result;
}

/**
* Convert a byte array with 32 bytes into a hash String by stretching the two halfs of a hex
* byte into two separate hex string. Padding with zeros must be kept in mind.
*
* @param hash hash byte array
* @return hash String
*/
public static String convertHashByte32ArrayIntoHashStr(byte[] hash) {
StringBuffer convertedBackStr = new StringBuffer().append(WeIdConstant.HEX_PREFIX);
StringBuilder convertedBackStr = new StringBuilder().append(WeIdConstant.HEX_PREFIX);
for (int i = 0; i < WeIdConstant.BYTES32_FIXED_LENGTH; i++) {
String hex = Integer
.toHexString(((int) hash[i]) >= 0 ? ((int) hash[i]) : ((int) hash[i]) + 256);
Expand All @@ -1811,23 +1825,37 @@ public static String convertHashByte32ArrayIntoHashStr(byte[] hash) {
return convertedBackStr.toString();
}

/**
* An intermediate fix to convert Bytes32 Object List from web3sdk 2.x into a real String list.
*
* @param byteList Bytes32 Object list
* @return hash String list
*/
public static List<String> convertBytes32ObjectListToStringHashList(
List<org.fisco.bcos.web3j.abi.datatypes.generated.Bytes32> bList) {
List<String> sList = new ArrayList<>();
for (int i = 0; i < bList.size(); i++) {
sList.add(DataToolUtils.convertHashByte32ArrayIntoHashStr(
((org.fisco.bcos.web3j.abi.datatypes.generated.Bytes32) (bList.toArray()[i])).getValue()));
List<org.fisco.bcos.web3j.abi.datatypes.generated.Bytes32> byteList) {
List<String> strList = new ArrayList<>();
for (int i = 0; i < byteList.size(); i++) {
strList.add(DataToolUtils.convertHashByte32ArrayIntoHashStr(
((org.fisco.bcos.web3j.abi.datatypes.generated.Bytes32) (byteList.toArray()[i]))
.getValue()));
}
return sList;
return strList;
}

/**
* Strictly check two lists' elements existence whether items in src exists in dst list or not.
*
* @param src source list
* @param dst dest list
* @return boolean list, each true / false indicating existing or not.
*/
public static List<Boolean> strictCheckExistence(List<String> src, List<String> dst) {
List<Boolean> result = new ArrayList<>();
int index = 0;
for (int i = 0; i < src.size(); i++) {
if (src.get(i).equalsIgnoreCase(dst.get(index))) {
result.add(true);
index ++;
index++;
} else {
result.add(false);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
import com.webank.weid.service.impl.engine.EvidenceServiceEngine;
import com.webank.weid.util.CredentialPojoUtils;
import com.webank.weid.util.DataToolUtils;
import com.webank.weid.util.DateUtils;

/**
* Test CreateEvidence.
Expand Down Expand Up @@ -278,7 +279,9 @@ public void testBatchCreate() throws Exception {
List<Long> timestamps = new ArrayList<>();
List<String> signers = new ArrayList<>();
List<String> logs = new ArrayList<>();
for (int i = 0; i < 100; i++) {
List<String> customKeys = new ArrayList<>();
int batchSize = 100;
for (int i = 0; i < batchSize; i++) {
CredentialPojo credential = createCredentialPojo(createCredentialPojoArgs);
credential.setId(UUID.randomUUID().toString());
String hash = credential.getHash();
Expand All @@ -289,20 +292,61 @@ public void testBatchCreate() throws Exception {
timestamps.add(System.currentTimeMillis());
signers.add(DataToolUtils.convertPrivateKeyToDefaultWeId(privateKey));
logs.add("test log" + i);
if (i % 2 == 1) {
customKeys.add(String.valueOf(System.currentTimeMillis()));
} else {
customKeys.add(StringUtils.EMPTY);
}
}
EvidenceServiceEngine engine = EngineFactory.createEvidenceServiceEngine();

// raw creation
Long start = System.currentTimeMillis();
ResponseData<List<Boolean>> resp = engine
.batchCreateEvidence(hashValues, signatures, logs, timestamps, signers, privateKey);
Long end = System.currentTimeMillis();
System.out.println(end - start);
System.out.println("Batch creation w/ size: " + batchSize + " takes time (ms): " + (String
.valueOf(end - start)));
List<Boolean> booleans = resp.getResult();
Assert.assertEquals(booleans.size(), hashValues.size());
Boolean result = true;
for (int i = 0; i < booleans.size(); i++) {
result &= booleans.get(i);
}
Assert.assertTrue(result);

// custom keys (semi filled)
start = System.currentTimeMillis();
resp = engine
.batchCreateEvidenceWithCustomKey(hashValues, signatures, logs, timestamps, signers,
customKeys, privateKey);
end = System.currentTimeMillis();
System.out.println(
"Batch creation w/ custom keys and size: " + batchSize + " takes time (ms): " + (String
.valueOf(end - start)));
booleans = resp.getResult();
Assert.assertEquals(booleans.size(), hashValues.size());
result = true;
for (int i = 0; i < booleans.size(); i++) {
result &= booleans.get(i);
}
Assert.assertTrue(result);

// Check get
String hash0 = hashValues.get(0);
String hash1 = hashValues.get(1);
String key1 = customKeys.get(1);
EvidenceInfo evidenceInfo0 = evidenceService.getEvidence(hash0).getResult();
EvidenceInfo evidenceInfo1 = evidenceService.getEvidence(hash1).getResult();
EvidenceInfo evidenceInfo1k = evidenceService.getEvidenceByCustomKey(key1).getResult();
Assert.assertNotNull(evidenceInfo0);
Assert.assertNotNull(evidenceInfo1);
Assert.assertNotNull(evidenceInfo1k);
Assert.assertEquals(evidenceInfo0.getSignInfo()
.get(DataToolUtils.convertPrivateKeyToDefaultWeId(privateKey)).getLogs().size(), 2);
Assert.assertEquals(evidenceInfo1.getSignInfo()
.get(DataToolUtils.convertPrivateKeyToDefaultWeId(privateKey)).getLogs().size(), 2);
Assert.assertEquals(evidenceInfo1.getCredentialHash(), evidenceInfo1k.getCredentialHash());
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/test/java/com/webank/weid/util/TestDataTypetUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ public void testHashConversion() {
Assert.assertEquals(hash, convertedBackStr);
Assert.assertEquals(hash.length(), WeIdConstant.BYTES32_FIXED_LENGTH * 2 + 2);
List<String> listX = new ArrayList(
Arrays.asList("a","b", "c", "d", "f", "f", "g"));
Arrays.asList("a", "b", "c", "d", "f", "f", "g"));
List<String> listY = new ArrayList(Arrays.asList("a", "c", "f", "f", "g"));
List<Boolean> result = DataToolUtils.strictCheckExistence(listX, listY);
Assert.assertTrue(result.get(0) && result.get(2));
Expand Down

0 comments on commit 4afd79e

Please sign in to comment.