diff --git a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/PrimitiveType.java b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/PrimitiveType.java
index b43f743e..fdfa77ae 100644
--- a/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/PrimitiveType.java
+++ b/source/binary-proto/src/main/java/com/jd/blockchain/binaryproto/PrimitiveType.java
@@ -1,66 +1,66 @@
-package com.jd.blockchain.binaryproto;
-
-/**
- * 键值操作的数据类型;
- *
- * @author huanghaiquan
- *
- */
-public enum PrimitiveType {
-
- /**
- * 空;
- */
- NIL(BaseType.NIL),
-
- /**
- * 布尔型;
- */
- BOOLEAN(BaseType.BOOLEAN),
-
- /**
- * 8位的整数:
- */
- INT8(BaseType.INT8),
-
- /**
- * 16位整数;
- */
- INT16(BaseType.INT16),
-
- /**
- * 32位整数;
- */
- INT32(BaseType.INT32),
-
- /**
- * 64位整数;
- */
- INT64(BaseType.INT64),
-
- /**
- * 文本;
- */
- TEXT(BaseType.TEXT),
-
- /**
- * 二进制数据;
- */
- BYTES(BaseType.BYTES);
-
- public final byte CODE;
-
- private PrimitiveType(byte code) {
- this.CODE = code;
- }
-
- public static PrimitiveType valueOf(byte code) {
- for (PrimitiveType dataType : PrimitiveType.values()) {
- if (dataType.CODE == code) {
- return dataType;
- }
- }
- throw new IllegalArgumentException("Code[" + code + "] not suppported by PrimitiveType!");
- }
-
-}
+package com.jd.blockchain.binaryproto;
+
+/**
+ * 键值操作的数据类型;
+ *
+ * @author huanghaiquan
+ *
+ */
+public enum PrimitiveType {
+
+ /**
+ * 空;
+ */
+ NIL(BaseType.NIL),
+
+ /**
+ * 布尔型;
+ */
+ BOOLEAN(BaseType.BOOLEAN),
+
+ /**
+ * 8位的整数:
+ */
+ INT8(BaseType.INT8),
+
+ /**
+ * 16位整数;
+ */
+ INT16(BaseType.INT16),
+
+ /**
+ * 32位整数;
+ */
+ INT32(BaseType.INT32),
+
+ /**
+ * 64位整数;
+ */
+ INT64(BaseType.INT64),
+
+ /**
+ * 文本;
+ */
+ TEXT(BaseType.TEXT),
+
+ /**
+ * 二进制数据;
+ */
+ BYTES(BaseType.BYTES);
+
+ public final byte CODE;
+
+ private PrimitiveType(byte code) {
+ this.CODE = code;
+ }
+
+ public static PrimitiveType valueOf(byte code) {
+ for (PrimitiveType dataType : PrimitiveType.values()) {
+ if (dataType.CODE == code) {
+ return dataType;
+ }
+ }
+ throw new IllegalArgumentException("Code[" + code + "] not suppported by PrimitiveType!");
+ }
+
+}
diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ActionMessage.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ActionMessage.java
index 6b99fe9e..32645701 100644
--- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ActionMessage.java
+++ b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ActionMessage.java
@@ -1,25 +1,25 @@
-package com.jd.blockchain.consensus;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * @author huanghaiquan
- *
- */
-@Target({ ElementType.PARAMETER })
-@Retention(RetentionPolicy.RUNTIME)
-public @interface ActionMessage {
-
- /**
- * 请求参数转换器;
- *
- * 指定一个 {@link BinaryMessageConverter} 接口的实现类;
- *
- * @return
- */
- Class> converter();
-
-}
+package com.jd.blockchain.consensus;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * @author huanghaiquan
+ *
+ */
+@Target({ ElementType.PARAMETER })
+@Retention(RetentionPolicy.RUNTIME)
+public @interface ActionMessage {
+
+ /**
+ * 请求参数转换器;
+ *
+ * 指定一个 {@link BinaryMessageConverter} 接口的实现类;
+ *
+ * @return
+ */
+ Class> converter();
+
+}
diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusSecurityException.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusSecurityException.java
index 36968fd6..26850b29 100644
--- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusSecurityException.java
+++ b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusSecurityException.java
@@ -1,18 +1,18 @@
-package com.jd.blockchain.consensus;
-
-public class ConsensusSecurityException extends Exception{
-
- private static final long serialVersionUID = -164820276123627155L;
-
- public ConsensusSecurityException() {
- }
-
- public ConsensusSecurityException(String message) {
- super(message);
- }
-
- public ConsensusSecurityException(String message, Throwable cause) {
- super(message, cause);
- }
-
-}
+package com.jd.blockchain.consensus;
+
+public class ConsensusSecurityException extends Exception{
+
+ private static final long serialVersionUID = -164820276123627155L;
+
+ public ConsensusSecurityException() {
+ }
+
+ public ConsensusSecurityException(String message) {
+ super(message);
+ }
+
+ public ConsensusSecurityException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+}
diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusService.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusService.java
index f7cf1cf8..2326f5bb 100644
--- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusService.java
+++ b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/ConsensusService.java
@@ -1,12 +1,12 @@
-package com.jd.blockchain.consensus;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-@Target({ ElementType.TYPE })
-@Retention(RetentionPolicy.RUNTIME)
-public @interface ConsensusService {
-
-}
+package com.jd.blockchain.consensus;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Target({ ElementType.TYPE })
+@Retention(RetentionPolicy.RUNTIME)
+public @interface ConsensusService {
+
+}
diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/OrderedAction.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/OrderedAction.java
index f9415d64..be7f6014 100644
--- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/OrderedAction.java
+++ b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/OrderedAction.java
@@ -1,35 +1,35 @@
-package com.jd.blockchain.consensus;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * 标识一个共识方法调用模式为“有序的消息调用”;
- *
- * @author huanghaiquan
- *
- */
-@Target({ ElementType.METHOD })
-@Retention(RetentionPolicy.RUNTIME)
-public @interface OrderedAction {
-
- /**
- * 请求分组的索引器;
- *
- * 指定一个 {@link GroupIndexer} 接口的实现类,用于根据请求消息列表来生成共识的分组ID;
- * @return
- */
- Class> groupIndexer() ;
-
- /**
- * 回复消息转换器;
- *
- * 指定一个 {@link BinaryMessageConverter} 接口的实现类;
- *
- * @return
- */
- Class> responseConverter();
-
-}
+package com.jd.blockchain.consensus;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * 标识一个共识方法调用模式为“有序的消息调用”;
+ *
+ * @author huanghaiquan
+ *
+ */
+@Target({ ElementType.METHOD })
+@Retention(RetentionPolicy.RUNTIME)
+public @interface OrderedAction {
+
+ /**
+ * 请求分组的索引器;
+ *
+ * 指定一个 {@link GroupIndexer} 接口的实现类,用于根据请求消息列表来生成共识的分组ID;
+ * @return
+ */
+ Class> groupIndexer() ;
+
+ /**
+ * 回复消息转换器;
+ *
+ * 指定一个 {@link BinaryMessageConverter} 接口的实现类;
+ *
+ * @return
+ */
+ Class> responseConverter();
+
+}
diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/UnorderedAction.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/UnorderedAction.java
index aa62b9fe..3d7531ee 100644
--- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/UnorderedAction.java
+++ b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/UnorderedAction.java
@@ -1,22 +1,22 @@
-package com.jd.blockchain.consensus;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * @author huanghaiquan
- *
- */
-@Target({ ElementType.METHOD })
-@Retention(RetentionPolicy.RUNTIME)
-public @interface UnorderedAction {
- /**
- * 请求分组的索引器;
- *
- * 指定一个 {@link GroupIndexer} 接口的实现类,用于根据请求消息列表来生成共识的分组ID;
- * @return
- */
- Class> groupIndexer() ;
-}
+package com.jd.blockchain.consensus;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * @author huanghaiquan
+ *
+ */
+@Target({ ElementType.METHOD })
+@Retention(RetentionPolicy.RUNTIME)
+public @interface UnorderedAction {
+ /**
+ * 请求分组的索引器;
+ *
+ * 指定一个 {@link GroupIndexer} 接口的实现类,用于根据请求消息列表来生成共识的分组ID;
+ * @return
+ */
+ Class> groupIndexer() ;
+}
diff --git a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/action/ActionResponseData.java b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/action/ActionResponseData.java
index 3a8e3ffb..948269d0 100644
--- a/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/action/ActionResponseData.java
+++ b/source/consensus/consensus-framework/src/main/java/com/jd/blockchain/consensus/action/ActionResponseData.java
@@ -1,49 +1,49 @@
-package com.jd.blockchain.consensus.action;
-
-public class ActionResponseData implements ActionResponse {
-
- private byte[] message;
-
- private boolean error = false;
-
- private String errorMessage;
-
- private String errorType;
-
- @Override
- public byte[] getMessage() {
- return message;
- }
-
- public void setMessage(byte[] message) {
- this.message = message;
- }
-
- @Override
- public boolean getError() {
- return error;
- }
-
- public void setError(boolean error) {
- this.error = error;
- }
-
- @Override
- public String getErrorMessage() {
- return errorMessage;
- }
-
- public void setErrorMessage(String errorMessage) {
- this.errorMessage = errorMessage;
- }
-
- @Override
- public String getErrorType() {
- return errorType;
- }
-
- public void setErrorType(String errorType) {
- this.errorType = errorType;
- }
-
-}
+package com.jd.blockchain.consensus.action;
+
+public class ActionResponseData implements ActionResponse {
+
+ private byte[] message;
+
+ private boolean error = false;
+
+ private String errorMessage;
+
+ private String errorType;
+
+ @Override
+ public byte[] getMessage() {
+ return message;
+ }
+
+ public void setMessage(byte[] message) {
+ this.message = message;
+ }
+
+ @Override
+ public boolean getError() {
+ return error;
+ }
+
+ public void setError(boolean error) {
+ this.error = error;
+ }
+
+ @Override
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+
+ public void setErrorMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
+
+ @Override
+ public String getErrorType() {
+ return errorType;
+ }
+
+ public void setErrorType(String errorType) {
+ this.errorType = errorType;
+ }
+
+}
diff --git a/source/contract/pom.xml b/source/contract/pom.xml
index d88eb189..daee178f 100644
--- a/source/contract/pom.xml
+++ b/source/contract/pom.xml
@@ -1,19 +1,19 @@
-
- 4.0.0
-
- com.jd.blockchain
- jdchain-root
- 1.1.2.RELEASE
-
- contract
- pom
-
-
- contract-framework
- contract-jvm
- contract-maven-plugin
- contract-samples
-
-
+
+ 4.0.0
+
+ com.jd.blockchain
+ jdchain-root
+ 1.1.2.RELEASE
+
+ contract
+ pom
+
+
+ contract-framework
+ contract-jvm
+ contract-maven-plugin
+ contract-samples
+
+
\ No newline at end of file
diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AddressEncoding.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AddressEncoding.java
index a1bf5e9c..98d3af79 100644
--- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AddressEncoding.java
+++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AddressEncoding.java
@@ -1,65 +1,65 @@
-package com.jd.blockchain.crypto;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.Arrays;
-
-import com.jd.blockchain.utils.Bytes;
-import com.jd.blockchain.utils.io.BytesEncoding;
-import com.jd.blockchain.utils.io.BytesUtils;
-import com.jd.blockchain.utils.io.NumberMask;
-import com.jd.blockchain.utils.security.RipeMD160Utils;
-import com.jd.blockchain.utils.security.ShaUtils;
-
-public class AddressEncoding {
-
- /**
- * 将区块链地址写入到输出流;
- *
- * 现将地址按 Base58 解码为字节数组,并将字节数组以 {@link BytesEncoding} 的方式写入输出流;
- *
- * 如果指定的地址为 null,则仅写入空字节数组;注:此种情况下,输出流并不是完全没有写入,而是实际上会被写入一个表示内容长度为 0 的头部字节;
- *
- * @param address
- * 要写入的区块链地址;
- * @param out
- * 输出流;
- * @return 写入的地址的字节数;如果指定地址为 null,则返回值为写入的头部字节数;;
- */
- public static int writeAddress(Bytes address, OutputStream out) {
- return address.writeTo(out);
- }
-
- /**
- * 从流中读取区块链地址;
- *
- * @param in
- * @return
- * @throws IOException
- */
- public static Bytes readAddress(InputStream in) throws IOException {
- byte[] bytesAddress = BytesEncoding.read(NumberMask.TINY, in);
- if (bytesAddress.length == 0) {
- return null;
- }
- return new Bytes(bytesAddress);
- }
-
- /**
- * 从公钥生成地址;
- *
- * @param pubKey
- * @return
- */
- public static Bytes generateAddress(PubKey pubKey) {
- byte[] h1Bytes = ShaUtils.hash_256(pubKey.getRawKeyBytes());
- byte[] h2Bytes = RipeMD160Utils.hash(h1Bytes);
- byte[] xBytes = BytesUtils.concat(new byte[] { AddressVersion.V1.CODE}, BytesUtils.toBytes(pubKey.getAlgorithm()), h2Bytes);
- byte[] checksum = Arrays.copyOf(ShaUtils.hash_256(ShaUtils.hash_256(xBytes)), 4);
- byte[] addressBytes = BytesUtils.concat(xBytes, checksum);
-
- return new Bytes(addressBytes);
- }
-
-}
+package com.jd.blockchain.crypto;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Arrays;
+
+import com.jd.blockchain.utils.Bytes;
+import com.jd.blockchain.utils.io.BytesEncoding;
+import com.jd.blockchain.utils.io.BytesUtils;
+import com.jd.blockchain.utils.io.NumberMask;
+import com.jd.blockchain.utils.security.RipeMD160Utils;
+import com.jd.blockchain.utils.security.ShaUtils;
+
+public class AddressEncoding {
+
+ /**
+ * 将区块链地址写入到输出流;
+ *
+ * 现将地址按 Base58 解码为字节数组,并将字节数组以 {@link BytesEncoding} 的方式写入输出流;
+ *
+ * 如果指定的地址为 null,则仅写入空字节数组;注:此种情况下,输出流并不是完全没有写入,而是实际上会被写入一个表示内容长度为 0 的头部字节;
+ *
+ * @param address
+ * 要写入的区块链地址;
+ * @param out
+ * 输出流;
+ * @return 写入的地址的字节数;如果指定地址为 null,则返回值为写入的头部字节数;;
+ */
+ public static int writeAddress(Bytes address, OutputStream out) {
+ return address.writeTo(out);
+ }
+
+ /**
+ * 从流中读取区块链地址;
+ *
+ * @param in
+ * @return
+ * @throws IOException
+ */
+ public static Bytes readAddress(InputStream in) throws IOException {
+ byte[] bytesAddress = BytesEncoding.read(NumberMask.TINY, in);
+ if (bytesAddress.length == 0) {
+ return null;
+ }
+ return new Bytes(bytesAddress);
+ }
+
+ /**
+ * 从公钥生成地址;
+ *
+ * @param pubKey
+ * @return
+ */
+ public static Bytes generateAddress(PubKey pubKey) {
+ byte[] h1Bytes = ShaUtils.hash_256(pubKey.getRawKeyBytes());
+ byte[] h2Bytes = RipeMD160Utils.hash(h1Bytes);
+ byte[] xBytes = BytesUtils.concat(new byte[] { AddressVersion.V1.CODE}, BytesUtils.toBytes(pubKey.getAlgorithm()), h2Bytes);
+ byte[] checksum = Arrays.copyOf(ShaUtils.hash_256(ShaUtils.hash_256(xBytes)), 4);
+ byte[] addressBytes = BytesUtils.concat(xBytes, checksum);
+
+ return new Bytes(addressBytes);
+ }
+
+}
diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AddressVersion.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AddressVersion.java
index 5e741abc..720214f9 100644
--- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AddressVersion.java
+++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/AddressVersion.java
@@ -1,24 +1,24 @@
-package com.jd.blockchain.crypto;
-
-/**
- * The version of Blockchain Address generation rule;
- *
- *
- *
- * @author huanghaiquan
- *
- */
-public enum AddressVersion {
-
- V1((byte) 0x91);
-
- // Note: Implementor can only add new enum items, cann't remove or modify
- // existing enum items;
-
- public final byte CODE;
-
- AddressVersion(byte code) {
- CODE = code;
- }
-
-}
+package com.jd.blockchain.crypto;
+
+/**
+ * The version of Blockchain Address generation rule;
+ *
+ *
+ *
+ * @author huanghaiquan
+ *
+ */
+public enum AddressVersion {
+
+ V1((byte) 0x91);
+
+ // Note: Implementor can only add new enum items, cann't remove or modify
+ // existing enum items;
+
+ public final byte CODE;
+
+ AddressVersion(byte code) {
+ CODE = code;
+ }
+
+}
diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoKey.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoKey.java
index ea73ef25..69c3b422 100644
--- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoKey.java
+++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/CryptoKey.java
@@ -1,25 +1,25 @@
-package com.jd.blockchain.crypto;
-
-/**
- * 密钥;
- *
- * @author huanghaiquan
- *
- */
-public interface CryptoKey extends CryptoBytes {
-
- /**
- * 密钥的类型;
- * @return
- */
- CryptoKeyType getKeyType();
-
- /**
- * 原始的密钥数据;
- *
- * @return
- */
- byte[] getRawKeyBytes();
-
-
+package com.jd.blockchain.crypto;
+
+/**
+ * 密钥;
+ *
+ * @author huanghaiquan
+ *
+ */
+public interface CryptoKey extends CryptoBytes {
+
+ /**
+ * 密钥的类型;
+ * @return
+ */
+ CryptoKeyType getKeyType();
+
+ /**
+ * 原始的密钥数据;
+ *
+ * @return
+ */
+ byte[] getRawKeyBytes();
+
+
}
\ No newline at end of file
diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/PrivKey.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/PrivKey.java
index 78af68c4..0aee8d26 100644
--- a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/PrivKey.java
+++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/PrivKey.java
@@ -1,29 +1,29 @@
-package com.jd.blockchain.crypto;
-
-/**
- * 私钥;
- *
- * @author huanghaiquan
- *
- */
-public class PrivKey extends BaseCryptoKey {
-
- private static final long serialVersionUID = 6265440395252295646L;
-
- public PrivKey(short algorithm, byte[] rawCryptoBytes) {
- super(algorithm, rawCryptoBytes, CryptoKeyType.PRIVATE);
- }
-
- public PrivKey(CryptoAlgorithm algorithm, byte[] rawCryptoBytes) {
- super(algorithm, rawCryptoBytes, CryptoKeyType.PRIVATE);
- }
-
- public PrivKey(byte[] cryptoBytes) {
- super(cryptoBytes);
- }
-
- @Override
- public CryptoKeyType getKeyType() {
- return CryptoKeyType.PRIVATE;
- }
+package com.jd.blockchain.crypto;
+
+/**
+ * 私钥;
+ *
+ * @author huanghaiquan
+ *
+ */
+public class PrivKey extends BaseCryptoKey {
+
+ private static final long serialVersionUID = 6265440395252295646L;
+
+ public PrivKey(short algorithm, byte[] rawCryptoBytes) {
+ super(algorithm, rawCryptoBytes, CryptoKeyType.PRIVATE);
+ }
+
+ public PrivKey(CryptoAlgorithm algorithm, byte[] rawCryptoBytes) {
+ super(algorithm, rawCryptoBytes, CryptoKeyType.PRIVATE);
+ }
+
+ public PrivKey(byte[] cryptoBytes) {
+ super(cryptoBytes);
+ }
+
+ @Override
+ public CryptoKeyType getKeyType() {
+ return CryptoKeyType.PRIVATE;
+ }
}
\ No newline at end of file
diff --git a/source/gateway/src/main/java/com/jd/blockchain/gateway/GatewayConfiguration.java b/source/gateway/src/main/java/com/jd/blockchain/gateway/GatewayConfiguration.java
index c498d29a..704bf3ab 100644
--- a/source/gateway/src/main/java/com/jd/blockchain/gateway/GatewayConfiguration.java
+++ b/source/gateway/src/main/java/com/jd/blockchain/gateway/GatewayConfiguration.java
@@ -1,14 +1,14 @@
-package com.jd.blockchain.gateway;
-
-import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
-import org.springframework.boot.autoconfigure.SpringBootApplication;
-import org.springframework.boot.context.properties.EnableConfigurationProperties;
-import org.springframework.context.annotation.ComponentScan;
-
-@EnableAutoConfiguration
-@EnableConfigurationProperties
-@SpringBootApplication
-@ComponentScan
-public class GatewayConfiguration {
-}
-
+package com.jd.blockchain.gateway;
+
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.ComponentScan;
+
+@EnableAutoConfiguration
+@EnableConfigurationProperties
+@SpringBootApplication
+@ComponentScan
+public class GatewayConfiguration {
+}
+
diff --git a/source/gateway/src/main/java/com/jd/blockchain/gateway/GatewayServerBooter.java b/source/gateway/src/main/java/com/jd/blockchain/gateway/GatewayServerBooter.java
index 18866f76..f743b4ac 100644
--- a/source/gateway/src/main/java/com/jd/blockchain/gateway/GatewayServerBooter.java
+++ b/source/gateway/src/main/java/com/jd/blockchain/gateway/GatewayServerBooter.java
@@ -1,178 +1,178 @@
-package com.jd.blockchain.gateway;
-
-import java.io.File;
-import java.io.InputStream;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.commons.io.FileUtils;
-import org.springframework.boot.SpringApplication;
-import org.springframework.context.ConfigurableApplicationContext;
-import org.springframework.core.io.ClassPathResource;
-
-import com.jd.blockchain.crypto.AsymmetricKeypair;
-import com.jd.blockchain.crypto.KeyGenUtils;
-import com.jd.blockchain.crypto.PrivKey;
-import com.jd.blockchain.crypto.PubKey;
-import com.jd.blockchain.gateway.web.BlockBrowserController;
-import com.jd.blockchain.utils.ArgumentSet;
-import com.jd.blockchain.utils.ArgumentSet.ArgEntry;
-import com.jd.blockchain.utils.BaseConstant;
-import com.jd.blockchain.utils.ConsoleUtils;
-
-
-public class GatewayServerBooter {
-
- private static final String DEFAULT_GATEWAY_PROPS = "application-gw.properties";
-
- // 当前参与方在初始化配置中的参与方列表的编号;
- private static final String HOST_ARG = "-c";
-
- //sp;针对spring.config.location这个参数进行包装;
- private static final String SPRING_CF_LOCATION = BaseConstant.SPRING_CF_LOCATION;
-
- // 是否输出调试信息;
- private static final String DEBUG_OPT = "-debug";
-
- public static void main(String[] args) {
- boolean debug = false;
- try {
- ArgumentSet arguments = ArgumentSet.resolve(args, ArgumentSet.setting().prefix(HOST_ARG, SPRING_CF_LOCATION).option(DEBUG_OPT));
- debug = arguments.hasOption(DEBUG_OPT);
- ArgEntry argHost = arguments.getArg(HOST_ARG);
- String configFile = argHost == null ? null : argHost.getValue();
- GatewayConfigProperties configProps;
- if (configFile == null) {
- ConsoleUtils.info("Load build-in default configuration ...");
- ClassPathResource configResource = new ClassPathResource("gateway.conf");
- try (InputStream in = configResource.getInputStream()) {
- configProps = GatewayConfigProperties.resolve(in);
- }
- } else {
- ConsoleUtils.info("Load configuration ...");
- configProps = GatewayConfigProperties.resolve(argHost.getValue());
- }
-
- //spring config location;
- String springConfigLocation=null;
- ArgumentSet.ArgEntry spConfigLocation = arguments.getArg(SPRING_CF_LOCATION);
- if (spConfigLocation != null) {
- springConfigLocation = spConfigLocation.getValue();
- }else {
- //if no the config file, then should tip as follows. but it's not a good feeling, so we create it by inputStream;
- ConsoleUtils.info("no param:-sp, format: -sp /x/xx.properties, use the default application-gw.properties ");
- ClassPathResource configResource = new ClassPathResource(DEFAULT_GATEWAY_PROPS);
- InputStream in = configResource.getInputStream();
-
- // 将文件写入至config目录下
- String configPath = bootPath() + "config" + File.separator + DEFAULT_GATEWAY_PROPS;
- File targetFile = new File(configPath);
-
- // 先将原来文件删除再Copy
- if (targetFile.exists()) {
- FileUtils.forceDelete(targetFile);
- }
-
- FileUtils.copyInputStreamToFile(in, targetFile);
- springConfigLocation = "file:" + targetFile.getAbsolutePath();
- }
-
- // 启动服务器;
- ConsoleUtils.info("Starting web server......");
- GatewayServerBooter booter = new GatewayServerBooter(configProps,springConfigLocation);
- booter.start();
-
- ConsoleUtils.info("Peer[%s] is connected success!", configProps.masterPeerAddress().toString());
- } catch (Exception e) {
- ConsoleUtils.error("Error!! %s", e.getMessage());
- if (debug) {
- e.printStackTrace();
- }
- }
- }
-
- private volatile ConfigurableApplicationContext appCtx;
- private GatewayConfigProperties config;
- private AsymmetricKeypair defaultKeyPair;
- private String springConfigLocation;
- public GatewayServerBooter(GatewayConfigProperties config, String springConfigLocation) {
- this.config = config;
- this.springConfigLocation = springConfigLocation;
-
- String base58Pwd = config.keys().getDefault().getPrivKeyPassword();
- if (base58Pwd == null || base58Pwd.length() == 0) {
- base58Pwd = KeyGenUtils.readPasswordString();
- }
-
- // 加载密钥;
- PubKey pubKey = KeyGenUtils.decodePubKey(config.keys().getDefault().getPubKeyValue());
-
- PrivKey privKey = null;
- String base58PrivKey = config.keys().getDefault().getPrivKeyValue();
- if (base58PrivKey == null) {
- //注:GatewayConfigProperties 确保了 PrivKeyValue 和 PrivKeyPath 必有其一;
- privKey = KeyGenUtils.readPrivKey(config.keys().getDefault().getPrivKeyPath(), base58Pwd);
- } else {
- privKey = KeyGenUtils.decodePrivKey(base58PrivKey, base58Pwd);
- }
- defaultKeyPair = new AsymmetricKeypair(pubKey, privKey);
- }
-
- public synchronized void start() {
- if (this.appCtx != null) {
- throw new IllegalStateException("Gateway server is running already.");
- }
- this.appCtx = startServer(config.http().getHost(), config.http().getPort(), springConfigLocation,
- config.http().getContextPath());
-
- ConsoleUtils.info("\r\n\r\nStart connecting to peer ....");
- BlockBrowserController blockBrowserController = appCtx.getBean(BlockBrowserController.class);
- blockBrowserController.setDataRetrievalUrl(config.dataRetrievalUrl());
- blockBrowserController.setSchemaRetrievalUrl(config.getSchemaRetrievalUrl());
- PeerConnector peerConnector = appCtx.getBean(PeerConnector.class);
- peerConnector.connect(config.masterPeerAddress(), defaultKeyPair, config.providerConfig().getProviders());
- ConsoleUtils.info("Peer[%s] is connected success!", config.masterPeerAddress().toString());
- }
-
- public synchronized void close() {
- if (this.appCtx == null) {
- return;
- }
- this.appCtx.close();
- }
-
- private static ConfigurableApplicationContext startServer(String host, int port, String springConfigLocation, String contextPath) {
- List argList = new ArrayList();
- argList.add(String.format("--server.address=%s", host));
- argList.add(String.format("--server.port=%s", port));
-
- if(springConfigLocation != null){
- argList.add(String.format("--spring.config.location=%s", springConfigLocation));
- }
-
- if (contextPath != null) {
- argList.add(String.format("--server.context-path=%s", contextPath));
- }
-
- String[] args = argList.toArray(new String[argList.size()]);
-
- // 启动服务器;
- ConfigurableApplicationContext appCtx = SpringApplication.run(GatewayConfiguration.class, args);
- return appCtx;
- }
-
- private static String bootPath() throws Exception {
- URL url = GatewayServerBooter.class.getProtectionDomain().getCodeSource().getLocation();
- String currPath = java.net.URLDecoder.decode(url.getPath(), "UTF-8");
- // 处理打包至SpringBoot问题
- if (currPath.contains("!/")) {
- currPath = currPath.substring(5, currPath.indexOf("!/"));
- }
- if (currPath.endsWith(".jar")) {
- currPath = currPath.substring(0, currPath.lastIndexOf("/") + 1);
- }
- System.out.printf("Current Project Boot Path = %s \r\n", currPath);
- return new File(currPath).getParent() + File.separator;
- }
+package com.jd.blockchain.gateway;
+
+import java.io.File;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.io.FileUtils;
+import org.springframework.boot.SpringApplication;
+import org.springframework.context.ConfigurableApplicationContext;
+import org.springframework.core.io.ClassPathResource;
+
+import com.jd.blockchain.crypto.AsymmetricKeypair;
+import com.jd.blockchain.crypto.KeyGenUtils;
+import com.jd.blockchain.crypto.PrivKey;
+import com.jd.blockchain.crypto.PubKey;
+import com.jd.blockchain.gateway.web.BlockBrowserController;
+import com.jd.blockchain.utils.ArgumentSet;
+import com.jd.blockchain.utils.ArgumentSet.ArgEntry;
+import com.jd.blockchain.utils.BaseConstant;
+import com.jd.blockchain.utils.ConsoleUtils;
+
+
+public class GatewayServerBooter {
+
+ private static final String DEFAULT_GATEWAY_PROPS = "application-gw.properties";
+
+ // 当前参与方在初始化配置中的参与方列表的编号;
+ private static final String HOST_ARG = "-c";
+
+ //sp;针对spring.config.location这个参数进行包装;
+ private static final String SPRING_CF_LOCATION = BaseConstant.SPRING_CF_LOCATION;
+
+ // 是否输出调试信息;
+ private static final String DEBUG_OPT = "-debug";
+
+ public static void main(String[] args) {
+ boolean debug = false;
+ try {
+ ArgumentSet arguments = ArgumentSet.resolve(args, ArgumentSet.setting().prefix(HOST_ARG, SPRING_CF_LOCATION).option(DEBUG_OPT));
+ debug = arguments.hasOption(DEBUG_OPT);
+ ArgEntry argHost = arguments.getArg(HOST_ARG);
+ String configFile = argHost == null ? null : argHost.getValue();
+ GatewayConfigProperties configProps;
+ if (configFile == null) {
+ ConsoleUtils.info("Load build-in default configuration ...");
+ ClassPathResource configResource = new ClassPathResource("gateway.conf");
+ try (InputStream in = configResource.getInputStream()) {
+ configProps = GatewayConfigProperties.resolve(in);
+ }
+ } else {
+ ConsoleUtils.info("Load configuration ...");
+ configProps = GatewayConfigProperties.resolve(argHost.getValue());
+ }
+
+ //spring config location;
+ String springConfigLocation=null;
+ ArgumentSet.ArgEntry spConfigLocation = arguments.getArg(SPRING_CF_LOCATION);
+ if (spConfigLocation != null) {
+ springConfigLocation = spConfigLocation.getValue();
+ }else {
+ //if no the config file, then should tip as follows. but it's not a good feeling, so we create it by inputStream;
+ ConsoleUtils.info("no param:-sp, format: -sp /x/xx.properties, use the default application-gw.properties ");
+ ClassPathResource configResource = new ClassPathResource(DEFAULT_GATEWAY_PROPS);
+ InputStream in = configResource.getInputStream();
+
+ // 将文件写入至config目录下
+ String configPath = bootPath() + "config" + File.separator + DEFAULT_GATEWAY_PROPS;
+ File targetFile = new File(configPath);
+
+ // 先将原来文件删除再Copy
+ if (targetFile.exists()) {
+ FileUtils.forceDelete(targetFile);
+ }
+
+ FileUtils.copyInputStreamToFile(in, targetFile);
+ springConfigLocation = "file:" + targetFile.getAbsolutePath();
+ }
+
+ // 启动服务器;
+ ConsoleUtils.info("Starting web server......");
+ GatewayServerBooter booter = new GatewayServerBooter(configProps,springConfigLocation);
+ booter.start();
+
+ ConsoleUtils.info("Peer[%s] is connected success!", configProps.masterPeerAddress().toString());
+ } catch (Exception e) {
+ ConsoleUtils.error("Error!! %s", e.getMessage());
+ if (debug) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ private volatile ConfigurableApplicationContext appCtx;
+ private GatewayConfigProperties config;
+ private AsymmetricKeypair defaultKeyPair;
+ private String springConfigLocation;
+ public GatewayServerBooter(GatewayConfigProperties config, String springConfigLocation) {
+ this.config = config;
+ this.springConfigLocation = springConfigLocation;
+
+ String base58Pwd = config.keys().getDefault().getPrivKeyPassword();
+ if (base58Pwd == null || base58Pwd.length() == 0) {
+ base58Pwd = KeyGenUtils.readPasswordString();
+ }
+
+ // 加载密钥;
+ PubKey pubKey = KeyGenUtils.decodePubKey(config.keys().getDefault().getPubKeyValue());
+
+ PrivKey privKey = null;
+ String base58PrivKey = config.keys().getDefault().getPrivKeyValue();
+ if (base58PrivKey == null) {
+ //注:GatewayConfigProperties 确保了 PrivKeyValue 和 PrivKeyPath 必有其一;
+ privKey = KeyGenUtils.readPrivKey(config.keys().getDefault().getPrivKeyPath(), base58Pwd);
+ } else {
+ privKey = KeyGenUtils.decodePrivKey(base58PrivKey, base58Pwd);
+ }
+ defaultKeyPair = new AsymmetricKeypair(pubKey, privKey);
+ }
+
+ public synchronized void start() {
+ if (this.appCtx != null) {
+ throw new IllegalStateException("Gateway server is running already.");
+ }
+ this.appCtx = startServer(config.http().getHost(), config.http().getPort(), springConfigLocation,
+ config.http().getContextPath());
+
+ ConsoleUtils.info("\r\n\r\nStart connecting to peer ....");
+ BlockBrowserController blockBrowserController = appCtx.getBean(BlockBrowserController.class);
+ blockBrowserController.setDataRetrievalUrl(config.dataRetrievalUrl());
+ blockBrowserController.setSchemaRetrievalUrl(config.getSchemaRetrievalUrl());
+ PeerConnector peerConnector = appCtx.getBean(PeerConnector.class);
+ peerConnector.connect(config.masterPeerAddress(), defaultKeyPair, config.providerConfig().getProviders());
+ ConsoleUtils.info("Peer[%s] is connected success!", config.masterPeerAddress().toString());
+ }
+
+ public synchronized void close() {
+ if (this.appCtx == null) {
+ return;
+ }
+ this.appCtx.close();
+ }
+
+ private static ConfigurableApplicationContext startServer(String host, int port, String springConfigLocation, String contextPath) {
+ List argList = new ArrayList();
+ argList.add(String.format("--server.address=%s", host));
+ argList.add(String.format("--server.port=%s", port));
+
+ if(springConfigLocation != null){
+ argList.add(String.format("--spring.config.location=%s", springConfigLocation));
+ }
+
+ if (contextPath != null) {
+ argList.add(String.format("--server.context-path=%s", contextPath));
+ }
+
+ String[] args = argList.toArray(new String[argList.size()]);
+
+ // 启动服务器;
+ ConfigurableApplicationContext appCtx = SpringApplication.run(GatewayConfiguration.class, args);
+ return appCtx;
+ }
+
+ private static String bootPath() throws Exception {
+ URL url = GatewayServerBooter.class.getProtectionDomain().getCodeSource().getLocation();
+ String currPath = java.net.URLDecoder.decode(url.getPath(), "UTF-8");
+ // 处理打包至SpringBoot问题
+ if (currPath.contains("!/")) {
+ currPath = currPath.substring(5, currPath.indexOf("!/"));
+ }
+ if (currPath.endsWith(".jar")) {
+ currPath = currPath.substring(0, currPath.lastIndexOf("/") + 1);
+ }
+ System.out.printf("Current Project Boot Path = %s \r\n", currPath);
+ return new File(currPath).getParent() + File.separator;
+ }
}
\ No newline at end of file
diff --git a/source/gateway/src/main/java/com/jd/blockchain/gateway/web/GatewayWebSecurityConfigurer.java b/source/gateway/src/main/java/com/jd/blockchain/gateway/web/GatewayWebSecurityConfigurer.java
index 857d18ae..504f09b8 100644
--- a/source/gateway/src/main/java/com/jd/blockchain/gateway/web/GatewayWebSecurityConfigurer.java
+++ b/source/gateway/src/main/java/com/jd/blockchain/gateway/web/GatewayWebSecurityConfigurer.java
@@ -1,17 +1,17 @@
-package com.jd.blockchain.gateway.web;
-
-import org.springframework.context.annotation.Configuration;
-import org.springframework.security.config.annotation.web.builders.HttpSecurity;
-import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
-import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
-
-@Configuration
-@EnableWebSecurity
-public class GatewayWebSecurityConfigurer extends WebSecurityConfigurerAdapter {
-
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.authorizeRequests().anyRequest().permitAll();
- http.csrf().disable();
- }
-}
+package com.jd.blockchain.gateway.web;
+
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+
+@Configuration
+@EnableWebSecurity
+public class GatewayWebSecurityConfigurer extends WebSecurityConfigurerAdapter {
+
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http.authorizeRequests().anyRequest().permitAll();
+ http.csrf().disable();
+ }
+}
diff --git a/source/gateway/src/main/resources/gateway.conf b/source/gateway/src/main/resources/gateway.conf
index 6b1a723e..c4262cc5 100644
--- a/source/gateway/src/main/resources/gateway.conf
+++ b/source/gateway/src/main/resources/gateway.conf
@@ -1,31 +1,31 @@
-#网关的HTTP服务地址;
-http.host=0.0.0.0
-#网关的HTTP服务端口;
-http.port=8081
-#网关的HTTP服务上下文路径,可选;
-#http.context-path=
-
-#共识节点的服务地址(与该网关节点连接的Peer节点的IP地址);
-peer.host=127.0.0.1
-#共识节点的服务端口(与该网关节点连接的Peer节点的端口);
-peer.port=12000
-#共识节点的服务是否启用安全证书;
-peer.secure=false
-#共识节点的服务提供解析器
-#BftSmart共识Provider:com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider
-#简单消息共识Provider:com.jd.blockchain.consensus.mq.MsgQueueConsensusProvider
-peer.providers=com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider
-
-#数据检索服务对应URL,格式:http://{ip}:{port},例如:http://127.0.0.1:10001
-#若该值不配置或配置不正确,则浏览器模糊查询部分无法正常显示
-data.retrieval.url=http://127.0.0.1:10001
-schema.retrieval.url=http://192.168.151.39:8082
-
-#默认公钥的内容(Base58编码数据);
-keys.default.pubkey=3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9
-#默认私钥的路径;在 pk-path 和 pk 之间必须设置其一;
-keys.default.privkey-path=
-#默认私钥的内容(加密的Base58编码数据);在 pk-path 和 pk 之间必须设置其一;
-keys.default.privkey=177gjzHTznYdPgWqZrH43W3yp37onm74wYXT4v9FukpCHBrhRysBBZh7Pzdo5AMRyQGJD7x
-#默认私钥的解码密码;
+#网关的HTTP服务地址;
+http.host=0.0.0.0
+#网关的HTTP服务端口;
+http.port=8081
+#网关的HTTP服务上下文路径,可选;
+#http.context-path=
+
+#共识节点的服务地址(与该网关节点连接的Peer节点的IP地址);
+peer.host=127.0.0.1
+#共识节点的服务端口(与该网关节点连接的Peer节点的端口);
+peer.port=12000
+#共识节点的服务是否启用安全证书;
+peer.secure=false
+#共识节点的服务提供解析器
+#BftSmart共识Provider:com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider
+#简单消息共识Provider:com.jd.blockchain.consensus.mq.MsgQueueConsensusProvider
+peer.providers=com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider
+
+#数据检索服务对应URL,格式:http://{ip}:{port},例如:http://127.0.0.1:10001
+#若该值不配置或配置不正确,则浏览器模糊查询部分无法正常显示
+data.retrieval.url=http://127.0.0.1:10001
+schema.retrieval.url=http://192.168.151.39:8082
+
+#默认公钥的内容(Base58编码数据);
+keys.default.pubkey=3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9
+#默认私钥的路径;在 pk-path 和 pk 之间必须设置其一;
+keys.default.privkey-path=
+#默认私钥的内容(加密的Base58编码数据);在 pk-path 和 pk 之间必须设置其一;
+keys.default.privkey=177gjzHTznYdPgWqZrH43W3yp37onm74wYXT4v9FukpCHBrhRysBBZh7Pzdo5AMRyQGJD7x
+#默认私钥的解码密码;
keys.default.privkey-password=DYu3G8aGTMBW1WrTw76zxQJQU4DHLw9MLyy7peG4LKkY
\ No newline at end of file
diff --git a/source/gateway/src/test/java/test/com/jd/blockchain/gateway/data/HashDigestDeserializer.java b/source/gateway/src/test/java/test/com/jd/blockchain/gateway/data/HashDigestDeserializer.java
index 448cd365..c6781f40 100644
--- a/source/gateway/src/test/java/test/com/jd/blockchain/gateway/data/HashDigestDeserializer.java
+++ b/source/gateway/src/test/java/test/com/jd/blockchain/gateway/data/HashDigestDeserializer.java
@@ -1,31 +1,31 @@
-package test.com.jd.blockchain.gateway.data;
-
-import java.lang.reflect.Type;
-
-import com.alibaba.fastjson.parser.DefaultJSONParser;
-import com.alibaba.fastjson.parser.JSONToken;
-import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
-import com.jd.blockchain.crypto.HashDigest;
-import com.jd.blockchain.utils.codec.Base58Utils;
-
-public class HashDigestDeserializer implements ObjectDeserializer{
-
- public static final HashDigestDeserializer INSTANCE = new HashDigestDeserializer();
-
- @SuppressWarnings("unchecked")
- @Override
- public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
- if (type instanceof Class && HashDigest.class.isAssignableFrom((Class>) type)) {
- String base58Str = parser.parseObject(String.class);
- byte[] hashBytes = Base58Utils.decode(base58Str);
- return (T) new HashDigest(hashBytes);
- }
- return (T) parser.parse(fieldName);
- }
-
- @Override
- public int getFastMatchToken() {
- return JSONToken.LBRACE;
- }
-
-}
+package test.com.jd.blockchain.gateway.data;
+
+import java.lang.reflect.Type;
+
+import com.alibaba.fastjson.parser.DefaultJSONParser;
+import com.alibaba.fastjson.parser.JSONToken;
+import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
+import com.jd.blockchain.crypto.HashDigest;
+import com.jd.blockchain.utils.codec.Base58Utils;
+
+public class HashDigestDeserializer implements ObjectDeserializer{
+
+ public static final HashDigestDeserializer INSTANCE = new HashDigestDeserializer();
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
+ if (type instanceof Class && HashDigest.class.isAssignableFrom((Class>) type)) {
+ String base58Str = parser.parseObject(String.class);
+ byte[] hashBytes = Base58Utils.decode(base58Str);
+ return (T) new HashDigest(hashBytes);
+ }
+ return (T) parser.parse(fieldName);
+ }
+
+ @Override
+ public int getFastMatchToken() {
+ return JSONToken.LBRACE;
+ }
+
+}
diff --git a/source/gateway/src/test/java/test/com/jd/blockchain/gateway/data/HashDigestSerializer.java b/source/gateway/src/test/java/test/com/jd/blockchain/gateway/data/HashDigestSerializer.java
index 14200484..58207dc7 100644
--- a/source/gateway/src/test/java/test/com/jd/blockchain/gateway/data/HashDigestSerializer.java
+++ b/source/gateway/src/test/java/test/com/jd/blockchain/gateway/data/HashDigestSerializer.java
@@ -1,27 +1,27 @@
-package test.com.jd.blockchain.gateway.data;
-
-import java.io.IOException;
-import java.lang.reflect.Type;
-
-import com.alibaba.fastjson.serializer.JSONSerializer;
-import com.alibaba.fastjson.serializer.ObjectSerializer;
-import com.alibaba.fastjson.serializer.SerializeWriter;
-import com.jd.blockchain.crypto.HashDigest;
-
-public class HashDigestSerializer implements ObjectSerializer {
-
- public static HashDigestSerializer INSTANCE = new HashDigestSerializer();
-
- @Override
- public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features)
- throws IOException {
- SerializeWriter out = serializer.out;
- if (object == null) {
- out.writeNull();
- return;
- }
- HashDigest hash = (HashDigest) object;
- out.writeString(hash.toBase58());
- }
-
-}
+package test.com.jd.blockchain.gateway.data;
+
+import java.io.IOException;
+import java.lang.reflect.Type;
+
+import com.alibaba.fastjson.serializer.JSONSerializer;
+import com.alibaba.fastjson.serializer.ObjectSerializer;
+import com.alibaba.fastjson.serializer.SerializeWriter;
+import com.jd.blockchain.crypto.HashDigest;
+
+public class HashDigestSerializer implements ObjectSerializer {
+
+ public static HashDigestSerializer INSTANCE = new HashDigestSerializer();
+
+ @Override
+ public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features)
+ throws IOException {
+ SerializeWriter out = serializer.out;
+ if (object == null) {
+ out.writeNull();
+ return;
+ }
+ HashDigest hash = (HashDigest) object;
+ out.writeString(hash.toBase58());
+ }
+
+}
diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ContractAccount.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ContractAccount.java
index 19c76463..d8a716bc 100644
--- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ContractAccount.java
+++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ContractAccount.java
@@ -1,73 +1,73 @@
-package com.jd.blockchain.ledger.core;
-
-import com.jd.blockchain.crypto.PubKey;
-import com.jd.blockchain.ledger.BytesValue;
-import com.jd.blockchain.ledger.ContractInfo;
-import com.jd.blockchain.ledger.TypedValue;
-import com.jd.blockchain.utils.Bytes;
-
-public class ContractAccount extends AccountDecorator implements ContractInfo {
-
- private static final String CONTRACT_INFO_PREFIX = "INFO" + LedgerConsts.KEY_SEPERATOR;
-
- private static final String CHAIN_CODE_KEY = "CHAIN-CODE";
-
- public ContractAccount(CompositeAccount mklAccount) {
- super(mklAccount);
- }
-
- @Override
- public Bytes getAddress() {
- return getID().getAddress();
- }
-
- @Override
- public PubKey getPubKey() {
- return getID().getPubKey();
- }
-
-// public MerkleProof getChaincodeProof() {
-// return getHeaders().getProof(CHAIN_CODE_KEY);
-// }
-//
-// public MerkleProof getPropertyProof(Bytes key) {
-// return getHeaders().getProof(encodePropertyKey(key));
-// }
-
- public long setChaincode(byte[] chaincode, long version) {
- TypedValue bytesValue = TypedValue.fromBytes(chaincode);
- return getHeaders().setValue(CHAIN_CODE_KEY, bytesValue, version);
- }
-
- public byte[] getChainCode() {
- return getHeaders().getValue(CHAIN_CODE_KEY).getBytes().toBytes();
- }
-
- public byte[] getChainCode(long version) {
- return getHeaders().getValue(CHAIN_CODE_KEY, version).getBytes().toBytes();
- }
-
- public long getChaincodeVersion() {
- return getHeaders().getVersion(CHAIN_CODE_KEY);
- }
-
- public long setProperty(String key, String value, long version) {
- TypedValue bytesValue = TypedValue.fromText(value);
- return getHeaders().setValue(encodePropertyKey(key), bytesValue, version);
- }
-
- public String getProperty(String key) {
- BytesValue bytesValue = getHeaders().getValue(encodePropertyKey(key));
- return TypedValue.wrap(bytesValue).stringValue();
- }
-
- public String getProperty(String key, long version) {
- BytesValue bytesValue = getHeaders().getValue(encodePropertyKey(key), version);
- return TypedValue.wrap(bytesValue).stringValue();
- }
-
- private String encodePropertyKey(String key) {
- return CONTRACT_INFO_PREFIX.concat(key);
- }
-
+package com.jd.blockchain.ledger.core;
+
+import com.jd.blockchain.crypto.PubKey;
+import com.jd.blockchain.ledger.BytesValue;
+import com.jd.blockchain.ledger.ContractInfo;
+import com.jd.blockchain.ledger.TypedValue;
+import com.jd.blockchain.utils.Bytes;
+
+public class ContractAccount extends AccountDecorator implements ContractInfo {
+
+ private static final String CONTRACT_INFO_PREFIX = "INFO" + LedgerConsts.KEY_SEPERATOR;
+
+ private static final String CHAIN_CODE_KEY = "CHAIN-CODE";
+
+ public ContractAccount(CompositeAccount mklAccount) {
+ super(mklAccount);
+ }
+
+ @Override
+ public Bytes getAddress() {
+ return getID().getAddress();
+ }
+
+ @Override
+ public PubKey getPubKey() {
+ return getID().getPubKey();
+ }
+
+// public MerkleProof getChaincodeProof() {
+// return getHeaders().getProof(CHAIN_CODE_KEY);
+// }
+//
+// public MerkleProof getPropertyProof(Bytes key) {
+// return getHeaders().getProof(encodePropertyKey(key));
+// }
+
+ public long setChaincode(byte[] chaincode, long version) {
+ TypedValue bytesValue = TypedValue.fromBytes(chaincode);
+ return getHeaders().setValue(CHAIN_CODE_KEY, bytesValue, version);
+ }
+
+ public byte[] getChainCode() {
+ return getHeaders().getValue(CHAIN_CODE_KEY).getBytes().toBytes();
+ }
+
+ public byte[] getChainCode(long version) {
+ return getHeaders().getValue(CHAIN_CODE_KEY, version).getBytes().toBytes();
+ }
+
+ public long getChaincodeVersion() {
+ return getHeaders().getVersion(CHAIN_CODE_KEY);
+ }
+
+ public long setProperty(String key, String value, long version) {
+ TypedValue bytesValue = TypedValue.fromText(value);
+ return getHeaders().setValue(encodePropertyKey(key), bytesValue, version);
+ }
+
+ public String getProperty(String key) {
+ BytesValue bytesValue = getHeaders().getValue(encodePropertyKey(key));
+ return TypedValue.wrap(bytesValue).stringValue();
+ }
+
+ public String getProperty(String key, long version) {
+ BytesValue bytesValue = getHeaders().getValue(encodePropertyKey(key), version);
+ return TypedValue.wrap(bytesValue).stringValue();
+ }
+
+ private String encodePropertyKey(String key) {
+ return CONTRACT_INFO_PREFIX.concat(key);
+ }
+
}
\ No newline at end of file
diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ContractAccountSet.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ContractAccountSet.java
index c4ee0408..ae11cb0e 100644
--- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ContractAccountSet.java
+++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ContractAccountSet.java
@@ -1,131 +1,131 @@
-package com.jd.blockchain.ledger.core;
-
-import com.jd.blockchain.crypto.HashDigest;
-import com.jd.blockchain.crypto.PubKey;
-import com.jd.blockchain.ledger.BlockchainIdentity;
-import com.jd.blockchain.ledger.CryptoSetting;
-import com.jd.blockchain.ledger.DigitalSignature;
-import com.jd.blockchain.ledger.MerkleProof;
-import com.jd.blockchain.storage.service.ExPolicyKVStorage;
-import com.jd.blockchain.storage.service.VersioningKVStorage;
-import com.jd.blockchain.utils.Bytes;
-import com.jd.blockchain.utils.Transactional;
-
-public class ContractAccountSet implements Transactional, ContractAccountQuery {
-
- private MerkleAccountSet accountSet;
-
- public ContractAccountSet(CryptoSetting cryptoSetting, String prefix, ExPolicyKVStorage exStorage,
- VersioningKVStorage verStorage, AccountAccessPolicy accessPolicy) {
- accountSet = new MerkleAccountSet(cryptoSetting, Bytes.fromString(prefix), exStorage, verStorage, accessPolicy);
- }
-
- public ContractAccountSet(HashDigest dataRootHash, CryptoSetting cryptoSetting, String prefix,
- ExPolicyKVStorage exStorage, VersioningKVStorage verStorage, boolean readonly,
- AccountAccessPolicy accessPolicy) {
- accountSet = new MerkleAccountSet(dataRootHash, cryptoSetting, Bytes.fromString(prefix), exStorage, verStorage,
- readonly, accessPolicy);
- }
-
- @Override
- public BlockchainIdentity[] getHeaders(int fromIndex, int count) {
- return accountSet.getHeaders(fromIndex, count);
- }
-
- public boolean isReadonly() {
- return accountSet.isReadonly();
- }
-
- void setReadonly() {
- accountSet.setReadonly();
- }
-
- @Override
- public HashDigest getRootHash() {
- return accountSet.getRootHash();
- }
-
- /**
- * 返回合约总数;
- *
- * @return
- */
- @Override
- public long getTotal() {
- return accountSet.getTotal();
- }
-
- @Override
- public MerkleProof getProof(Bytes address) {
- return accountSet.getProof(address);
- }
-
- @Override
- public boolean contains(Bytes address) {
- return accountSet.contains(address);
- }
-
- @Override
- public ContractAccount getAccount(Bytes address) {
- CompositeAccount accBase = accountSet.getAccount(address);
- return new ContractAccount(accBase);
- }
-
- @Override
- public ContractAccount getAccount(String address) {
- return getAccount(Bytes.fromBase58(address));
- }
-
- @Override
- public ContractAccount getAccount(Bytes address, long version) {
- CompositeAccount accBase = accountSet.getAccount(address, version);
- return new ContractAccount(accBase);
- }
-
- /**
- * 部署一项新的合约链码;
- *
- * @param address 合约账户地址;
- * @param pubKey 合约账户公钥;
- * @param addressSignature 地址签名;合约账户的私钥对地址的签名;
- * @param chaincode 链码内容;
- * @return 合约账户;
- */
- public ContractAccount deploy(Bytes address, PubKey pubKey, DigitalSignature addressSignature, byte[] chaincode) {
- // TODO: 校验和记录合约地址签名;
- CompositeAccount accBase = accountSet.register(address, pubKey);
- ContractAccount contractAcc = new ContractAccount(accBase);
- contractAcc.setChaincode(chaincode, -1);
- return contractAcc;
- }
-
- /**
- * 更新指定账户的链码;
- *
- * @param address 合约账户地址;
- * @param chaincode 链码内容;
- * @param version 链码版本;
- * @return 返回链码的新版本号;
- */
- public long update(Bytes address, byte[] chaincode, long version) {
- CompositeAccount accBase = accountSet.getAccount(address);
- ContractAccount contractAcc = new ContractAccount(accBase);
- return contractAcc.setChaincode(chaincode, version);
- }
-
- @Override
- public boolean isUpdated() {
- return accountSet.isUpdated();
- }
-
- @Override
- public void commit() {
- accountSet.commit();
- }
-
- @Override
- public void cancel() {
- accountSet.cancel();
- }
-
+package com.jd.blockchain.ledger.core;
+
+import com.jd.blockchain.crypto.HashDigest;
+import com.jd.blockchain.crypto.PubKey;
+import com.jd.blockchain.ledger.BlockchainIdentity;
+import com.jd.blockchain.ledger.CryptoSetting;
+import com.jd.blockchain.ledger.DigitalSignature;
+import com.jd.blockchain.ledger.MerkleProof;
+import com.jd.blockchain.storage.service.ExPolicyKVStorage;
+import com.jd.blockchain.storage.service.VersioningKVStorage;
+import com.jd.blockchain.utils.Bytes;
+import com.jd.blockchain.utils.Transactional;
+
+public class ContractAccountSet implements Transactional, ContractAccountQuery {
+
+ private MerkleAccountSet accountSet;
+
+ public ContractAccountSet(CryptoSetting cryptoSetting, String prefix, ExPolicyKVStorage exStorage,
+ VersioningKVStorage verStorage, AccountAccessPolicy accessPolicy) {
+ accountSet = new MerkleAccountSet(cryptoSetting, Bytes.fromString(prefix), exStorage, verStorage, accessPolicy);
+ }
+
+ public ContractAccountSet(HashDigest dataRootHash, CryptoSetting cryptoSetting, String prefix,
+ ExPolicyKVStorage exStorage, VersioningKVStorage verStorage, boolean readonly,
+ AccountAccessPolicy accessPolicy) {
+ accountSet = new MerkleAccountSet(dataRootHash, cryptoSetting, Bytes.fromString(prefix), exStorage, verStorage,
+ readonly, accessPolicy);
+ }
+
+ @Override
+ public BlockchainIdentity[] getHeaders(int fromIndex, int count) {
+ return accountSet.getHeaders(fromIndex, count);
+ }
+
+ public boolean isReadonly() {
+ return accountSet.isReadonly();
+ }
+
+ void setReadonly() {
+ accountSet.setReadonly();
+ }
+
+ @Override
+ public HashDigest getRootHash() {
+ return accountSet.getRootHash();
+ }
+
+ /**
+ * 返回合约总数;
+ *
+ * @return
+ */
+ @Override
+ public long getTotal() {
+ return accountSet.getTotal();
+ }
+
+ @Override
+ public MerkleProof getProof(Bytes address) {
+ return accountSet.getProof(address);
+ }
+
+ @Override
+ public boolean contains(Bytes address) {
+ return accountSet.contains(address);
+ }
+
+ @Override
+ public ContractAccount getAccount(Bytes address) {
+ CompositeAccount accBase = accountSet.getAccount(address);
+ return new ContractAccount(accBase);
+ }
+
+ @Override
+ public ContractAccount getAccount(String address) {
+ return getAccount(Bytes.fromBase58(address));
+ }
+
+ @Override
+ public ContractAccount getAccount(Bytes address, long version) {
+ CompositeAccount accBase = accountSet.getAccount(address, version);
+ return new ContractAccount(accBase);
+ }
+
+ /**
+ * 部署一项新的合约链码;
+ *
+ * @param address 合约账户地址;
+ * @param pubKey 合约账户公钥;
+ * @param addressSignature 地址签名;合约账户的私钥对地址的签名;
+ * @param chaincode 链码内容;
+ * @return 合约账户;
+ */
+ public ContractAccount deploy(Bytes address, PubKey pubKey, DigitalSignature addressSignature, byte[] chaincode) {
+ // TODO: 校验和记录合约地址签名;
+ CompositeAccount accBase = accountSet.register(address, pubKey);
+ ContractAccount contractAcc = new ContractAccount(accBase);
+ contractAcc.setChaincode(chaincode, -1);
+ return contractAcc;
+ }
+
+ /**
+ * 更新指定账户的链码;
+ *
+ * @param address 合约账户地址;
+ * @param chaincode 链码内容;
+ * @param version 链码版本;
+ * @return 返回链码的新版本号;
+ */
+ public long update(Bytes address, byte[] chaincode, long version) {
+ CompositeAccount accBase = accountSet.getAccount(address);
+ ContractAccount contractAcc = new ContractAccount(accBase);
+ return contractAcc.setChaincode(chaincode, version);
+ }
+
+ @Override
+ public boolean isUpdated() {
+ return accountSet.isUpdated();
+ }
+
+ @Override
+ public void commit() {
+ accountSet.commit();
+ }
+
+ @Override
+ public void cancel() {
+ accountSet.cancel();
+ }
+
}
\ No newline at end of file
diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DataAccount.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DataAccount.java
index 4814cdf6..6f99bf51 100644
--- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DataAccount.java
+++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DataAccount.java
@@ -1,234 +1,234 @@
-package com.jd.blockchain.ledger.core;
-
-public class DataAccount extends AccountDecorator {
-
- public DataAccount(CompositeAccount mklAccount) {
- super(mklAccount);
- }
-
-// /**
-// * Create or update the value associated the specified key if the version
-// * checking is passed.
-// *
-// * The value of the key will be updated only if it's latest version equals the
-// * specified version argument.
-// * If the key doesn't exist, the version checking will be ignored, and key will
-// * be created with a new sequence number as id.
-// * It also could specify the version argument to -1 to ignore the version
-// * checking.
-// *
-// * If updating is performed, the version of the key increase by 1.
-// * If creating is performed, the version of the key initialize by 0.
-// *
-// * @param key The key of data;
-// * @param value The value of data;
-// * @param version The expected version of the key.
-// * @return The new version of the key.
-// * If the key is new created success, then return 0;
-// * If the key is updated success, then return the new version;
-// * If this operation fail by version checking or other reason, then
-// * return -1;
-// */
-// public long setBytes(Bytes key, BytesValue value, long version) {
-// return super.getDataset().setValue(key, value, version);
-// }
-
-//
-// /**
-// * Create or update the value associated the specified key if the version
-// * checking is passed.
-// *
-// * The value of the key will be updated only if it's latest version equals the
-// * specified version argument.
-// * If the key doesn't exist, the version checking will be ignored, and key will
-// * be created with a new sequence number as id.
-// * It also could specify the version argument to -1 to ignore the version
-// * checking.
-// *
-// * If updating is performed, the version of the key increase by 1.
-// * If creating is performed, the version of the key initialize by 0.
-// *
-// * @param key The key of data;
-// * @param value The value of data;
-// * @param version The expected version of the key.
-// * @return The new version of the key.
-// * If the key is new created success, then return 0;
-// * If the key is updated success, then return the new version;
-// * If this operation fail by version checking or other reason, then
-// * return -1;
-// */
-// public long setBytes(Bytes key, String value, long version) {
-// BytesValue bytesValue = TypedValue.fromText(value);
-// return baseAccount.setValue(key, bytesValue, version);
-// }
-//
-// /**
-// * Create or update the value associated the specified key if the version
-// * checking is passed.
-// *
-// * The value of the key will be updated only if it's latest version equals the
-// * specified version argument.
-// * If the key doesn't exist, the version checking will be ignored, and key will
-// * be created with a new sequence number as id.
-// * It also could specify the version argument to -1 to ignore the version
-// * checking.
-// *
-// * If updating is performed, the version of the key increase by 1.
-// * If creating is performed, the version of the key initialize by 0.
-// *
-// * @param key The key of data;
-// * @param value The value of data;
-// * @param version The expected version of the key.
-// * @return The new version of the key.
-// * If the key is new created success, then return 0;
-// * If the key is updated success, then return the new version;
-// * If this operation fail by version checking or other reason, then
-// * return -1;
-// */
-// public long setBytes(Bytes key, byte[] value, long version) {
-// BytesValue bytesValue = TypedValue.fromBytes(value);
-// return baseAccount.setValue(key, bytesValue, version);
-// }
-//
-// /**
-// * Return the latest version entry associated the specified key; If the key
-// * doesn't exist, then return -1;
-// *
-// * @param key
-// * @return
-// */
-// public long getDataVersion(String key) {
-// return baseAccount.getVersion(Bytes.fromString(key));
-// }
-//
-// /**
-// * Return the latest version entry associated the specified key; If the key
-// * doesn't exist, then return -1;
-// *
-// * @param key
-// * @return
-// */
-// public long getDataVersion(Bytes key) {
-// return baseAccount.getVersion(key);
-// }
-//
-// /**
-// * return the latest version's value;
-// *
-// * @param key
-// * @return return null if not exist;
-// */
-// public BytesValue getBytes(String key) {
-// return baseAccount.getValue(Bytes.fromString(key));
-// }
-//
-// /**
-// * return the latest version's value;
-// *
-// * @param key
-// * @return return null if not exist;
-// */
-// public BytesValue getBytes(Bytes key) {
-// return baseAccount.getValue(key);
-// }
-//
-// /**
-// * return the specified version's value;
-// *
-// * @param key
-// * @param version
-// * @return return null if not exist;
-// */
-// public BytesValue getBytes(String key, long version) {
-// return baseAccount.getValue(Bytes.fromString(key), version);
-// }
-//
-// /**
-// * return the specified version's value;
-// *
-// * @param key
-// * @param version
-// * @return return null if not exist;
-// */
-// public BytesValue getBytes(Bytes key, long version) {
-// return baseAccount.getValue(key, version);
-// }
-
-
-
-
-// /**
-// * @param key
-// * @param version
-// * @return
-// */
-// public KVDataEntry getDataEntry(String key, long version) {
-// return getDataEntry(Bytes.fromString(key), version);
-// }
-//
-// /**
-// * @param key
-// * @param version
-// * @return
-// */
-// public KVDataEntry getDataEntry(Bytes key, long version) {
-// BytesValue value = baseAccount.getValue(key, version);
-// if (value == null) {
-// return new KVDataObject(key.toUTF8String(), -1, null);
-// }else {
-// return new KVDataObject(key.toUTF8String(), version, value);
-// }
-// }
-//
-// /**
-// * return the specified index's KVDataEntry;
-// *
-// * @param fromIndex
-// * @param count
-// * @return return null if not exist;
-// */
-//
-// public KVDataEntry[] getDataEntries(int fromIndex, int count) {
-// if (count == 0 || getDataEntriesTotalCount() == 0) {
-// return null;
-// }
-//
-// if (count == -1 || count > getDataEntriesTotalCount()) {
-// fromIndex = 0;
-// count = (int)getDataEntriesTotalCount();
-// }
-//
-// if (fromIndex < 0 || fromIndex > getDataEntriesTotalCount() - 1) {
-// fromIndex = 0;
-// }
-//
-// KVDataEntry[] kvDataEntries = new KVDataEntry[count];
-// byte[] value;
-// String key;
-// long ver;
-// for (int i = 0; i < count; i++) {
-// value = baseAccount.dataset.getValuesAtIndex(fromIndex);
-// key = baseAccount.dataset.getKeyAtIndex(fromIndex);
-// ver = baseAccount.dataset.getVersion(key);
-// BytesValue decodeData = BinaryProtocol.decode(value);
-// kvDataEntries[i] = new KVDataObject(key, ver, decodeData);
-// fromIndex++;
-// }
-//
-// return kvDataEntries;
-// }
-//
-// /**
-// * return the dataAccount's kv total count;
-// *
-// * @param
-// * @param
-// * @return return total count;
-// */
-// public long getDataEntriesTotalCount() {
-// if(baseAccount == null){
-// return 0;
-// }
-// return baseAccount.dataset.getDataCount();
-// }
+package com.jd.blockchain.ledger.core;
+
+public class DataAccount extends AccountDecorator {
+
+ public DataAccount(CompositeAccount mklAccount) {
+ super(mklAccount);
+ }
+
+// /**
+// * Create or update the value associated the specified key if the version
+// * checking is passed.
+// *
+// * The value of the key will be updated only if it's latest version equals the
+// * specified version argument.
+// * If the key doesn't exist, the version checking will be ignored, and key will
+// * be created with a new sequence number as id.
+// * It also could specify the version argument to -1 to ignore the version
+// * checking.
+// *
+// * If updating is performed, the version of the key increase by 1.
+// * If creating is performed, the version of the key initialize by 0.
+// *
+// * @param key The key of data;
+// * @param value The value of data;
+// * @param version The expected version of the key.
+// * @return The new version of the key.
+// * If the key is new created success, then return 0;
+// * If the key is updated success, then return the new version;
+// * If this operation fail by version checking or other reason, then
+// * return -1;
+// */
+// public long setBytes(Bytes key, BytesValue value, long version) {
+// return super.getDataset().setValue(key, value, version);
+// }
+
+//
+// /**
+// * Create or update the value associated the specified key if the version
+// * checking is passed.
+// *
+// * The value of the key will be updated only if it's latest version equals the
+// * specified version argument.
+// * If the key doesn't exist, the version checking will be ignored, and key will
+// * be created with a new sequence number as id.
+// * It also could specify the version argument to -1 to ignore the version
+// * checking.
+// *
+// * If updating is performed, the version of the key increase by 1.
+// * If creating is performed, the version of the key initialize by 0.
+// *
+// * @param key The key of data;
+// * @param value The value of data;
+// * @param version The expected version of the key.
+// * @return The new version of the key.
+// * If the key is new created success, then return 0;
+// * If the key is updated success, then return the new version;
+// * If this operation fail by version checking or other reason, then
+// * return -1;
+// */
+// public long setBytes(Bytes key, String value, long version) {
+// BytesValue bytesValue = TypedValue.fromText(value);
+// return baseAccount.setValue(key, bytesValue, version);
+// }
+//
+// /**
+// * Create or update the value associated the specified key if the version
+// * checking is passed.
+// *
+// * The value of the key will be updated only if it's latest version equals the
+// * specified version argument.
+// * If the key doesn't exist, the version checking will be ignored, and key will
+// * be created with a new sequence number as id.
+// * It also could specify the version argument to -1 to ignore the version
+// * checking.
+// *
+// * If updating is performed, the version of the key increase by 1.
+// * If creating is performed, the version of the key initialize by 0.
+// *
+// * @param key The key of data;
+// * @param value The value of data;
+// * @param version The expected version of the key.
+// * @return The new version of the key.
+// * If the key is new created success, then return 0;
+// * If the key is updated success, then return the new version;
+// * If this operation fail by version checking or other reason, then
+// * return -1;
+// */
+// public long setBytes(Bytes key, byte[] value, long version) {
+// BytesValue bytesValue = TypedValue.fromBytes(value);
+// return baseAccount.setValue(key, bytesValue, version);
+// }
+//
+// /**
+// * Return the latest version entry associated the specified key; If the key
+// * doesn't exist, then return -1;
+// *
+// * @param key
+// * @return
+// */
+// public long getDataVersion(String key) {
+// return baseAccount.getVersion(Bytes.fromString(key));
+// }
+//
+// /**
+// * Return the latest version entry associated the specified key; If the key
+// * doesn't exist, then return -1;
+// *
+// * @param key
+// * @return
+// */
+// public long getDataVersion(Bytes key) {
+// return baseAccount.getVersion(key);
+// }
+//
+// /**
+// * return the latest version's value;
+// *
+// * @param key
+// * @return return null if not exist;
+// */
+// public BytesValue getBytes(String key) {
+// return baseAccount.getValue(Bytes.fromString(key));
+// }
+//
+// /**
+// * return the latest version's value;
+// *
+// * @param key
+// * @return return null if not exist;
+// */
+// public BytesValue getBytes(Bytes key) {
+// return baseAccount.getValue(key);
+// }
+//
+// /**
+// * return the specified version's value;
+// *
+// * @param key
+// * @param version
+// * @return return null if not exist;
+// */
+// public BytesValue getBytes(String key, long version) {
+// return baseAccount.getValue(Bytes.fromString(key), version);
+// }
+//
+// /**
+// * return the specified version's value;
+// *
+// * @param key
+// * @param version
+// * @return return null if not exist;
+// */
+// public BytesValue getBytes(Bytes key, long version) {
+// return baseAccount.getValue(key, version);
+// }
+
+
+
+
+// /**
+// * @param key
+// * @param version
+// * @return
+// */
+// public KVDataEntry getDataEntry(String key, long version) {
+// return getDataEntry(Bytes.fromString(key), version);
+// }
+//
+// /**
+// * @param key
+// * @param version
+// * @return
+// */
+// public KVDataEntry getDataEntry(Bytes key, long version) {
+// BytesValue value = baseAccount.getValue(key, version);
+// if (value == null) {
+// return new KVDataObject(key.toUTF8String(), -1, null);
+// }else {
+// return new KVDataObject(key.toUTF8String(), version, value);
+// }
+// }
+//
+// /**
+// * return the specified index's KVDataEntry;
+// *
+// * @param fromIndex
+// * @param count
+// * @return return null if not exist;
+// */
+//
+// public KVDataEntry[] getDataEntries(int fromIndex, int count) {
+// if (count == 0 || getDataEntriesTotalCount() == 0) {
+// return null;
+// }
+//
+// if (count == -1 || count > getDataEntriesTotalCount()) {
+// fromIndex = 0;
+// count = (int)getDataEntriesTotalCount();
+// }
+//
+// if (fromIndex < 0 || fromIndex > getDataEntriesTotalCount() - 1) {
+// fromIndex = 0;
+// }
+//
+// KVDataEntry[] kvDataEntries = new KVDataEntry[count];
+// byte[] value;
+// String key;
+// long ver;
+// for (int i = 0; i < count; i++) {
+// value = baseAccount.dataset.getValuesAtIndex(fromIndex);
+// key = baseAccount.dataset.getKeyAtIndex(fromIndex);
+// ver = baseAccount.dataset.getVersion(key);
+// BytesValue decodeData = BinaryProtocol.decode(value);
+// kvDataEntries[i] = new KVDataObject(key, ver, decodeData);
+// fromIndex++;
+// }
+//
+// return kvDataEntries;
+// }
+//
+// /**
+// * return the dataAccount's kv total count;
+// *
+// * @param
+// * @param
+// * @return return total count;
+// */
+// public long getDataEntriesTotalCount() {
+// if(baseAccount == null){
+// return 0;
+// }
+// return baseAccount.dataset.getDataCount();
+// }
}
\ No newline at end of file
diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DataAccountSet.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DataAccountSet.java
index 0f849c1d..312d2f45 100644
--- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DataAccountSet.java
+++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DataAccountSet.java
@@ -1,113 +1,113 @@
-package com.jd.blockchain.ledger.core;
-
-import com.jd.blockchain.crypto.HashDigest;
-import com.jd.blockchain.crypto.PubKey;
-import com.jd.blockchain.ledger.BlockchainIdentity;
-import com.jd.blockchain.ledger.CryptoSetting;
-import com.jd.blockchain.ledger.DigitalSignature;
-import com.jd.blockchain.ledger.MerkleProof;
-import com.jd.blockchain.storage.service.ExPolicyKVStorage;
-import com.jd.blockchain.storage.service.VersioningKVStorage;
-import com.jd.blockchain.utils.Bytes;
-import com.jd.blockchain.utils.Transactional;
-
-public class DataAccountSet implements Transactional, DataAccountQuery {
-
- private MerkleAccountSet accountSet;
-
- public DataAccountSet(CryptoSetting cryptoSetting, String prefix, ExPolicyKVStorage exStorage,
- VersioningKVStorage verStorage, AccountAccessPolicy accessPolicy) {
- accountSet = new MerkleAccountSet(cryptoSetting, Bytes.fromString(prefix), exStorage, verStorage, accessPolicy);
- }
-
- public DataAccountSet(HashDigest dataRootHash, CryptoSetting cryptoSetting, String prefix,
- ExPolicyKVStorage exStorage, VersioningKVStorage verStorage, boolean readonly,
- AccountAccessPolicy accessPolicy) {
- accountSet = new MerkleAccountSet(dataRootHash, cryptoSetting, Bytes.fromString(prefix), exStorage, verStorage,
- readonly, accessPolicy);
- }
-
- @Override
- public BlockchainIdentity[] getHeaders(int fromIndex, int count) {
- return accountSet.getHeaders(fromIndex, count);
- }
-
- public boolean isReadonly() {
- return accountSet.isReadonly();
- }
-
- void setReadonly() {
- accountSet.setReadonly();
- }
-
- @Override
- public HashDigest getRootHash() {
- return accountSet.getRootHash();
- }
-
- @Override
- public long getTotal() {
- return accountSet.getTotal();
- }
-
- @Override
- public boolean contains(Bytes address) {
- return accountSet.contains(address);
- }
-
- /**
- * 返回账户的存在性证明;
- */
- @Override
- public MerkleProof getProof(Bytes address) {
- return accountSet.getProof(address);
- }
-
- public DataAccount register(Bytes address, PubKey pubKey, DigitalSignature addressSignature) {
- // TODO: 未实现对地址签名的校验和记录;
- CompositeAccount accBase = accountSet.register(address, pubKey);
- return new DataAccount(accBase);
- }
-
- @Override
- public DataAccount getAccount(String address) {
- return getAccount(Bytes.fromBase58(address));
- }
-
- /**
- * 返回数据账户;
- * 如果不存在,则返回 null;
- *
- * @param address
- * @return
- */
- @Override
- public DataAccount getAccount(Bytes address) {
- CompositeAccount accBase = accountSet.getAccount(address);
- if (accBase == null) {
- return null;
- }
- return new DataAccount(accBase);
- }
-
- @Override
- public DataAccount getAccount(Bytes address, long version) {
- CompositeAccount accBase = accountSet.getAccount(address, version);
- return new DataAccount(accBase);
- }
-
- @Override
- public boolean isUpdated() {
- return accountSet.isUpdated();
- }
-
- @Override
- public void commit() {
- accountSet.commit();
- }
-
- @Override
- public void cancel() {
- accountSet.cancel();
- }
+package com.jd.blockchain.ledger.core;
+
+import com.jd.blockchain.crypto.HashDigest;
+import com.jd.blockchain.crypto.PubKey;
+import com.jd.blockchain.ledger.BlockchainIdentity;
+import com.jd.blockchain.ledger.CryptoSetting;
+import com.jd.blockchain.ledger.DigitalSignature;
+import com.jd.blockchain.ledger.MerkleProof;
+import com.jd.blockchain.storage.service.ExPolicyKVStorage;
+import com.jd.blockchain.storage.service.VersioningKVStorage;
+import com.jd.blockchain.utils.Bytes;
+import com.jd.blockchain.utils.Transactional;
+
+public class DataAccountSet implements Transactional, DataAccountQuery {
+
+ private MerkleAccountSet accountSet;
+
+ public DataAccountSet(CryptoSetting cryptoSetting, String prefix, ExPolicyKVStorage exStorage,
+ VersioningKVStorage verStorage, AccountAccessPolicy accessPolicy) {
+ accountSet = new MerkleAccountSet(cryptoSetting, Bytes.fromString(prefix), exStorage, verStorage, accessPolicy);
+ }
+
+ public DataAccountSet(HashDigest dataRootHash, CryptoSetting cryptoSetting, String prefix,
+ ExPolicyKVStorage exStorage, VersioningKVStorage verStorage, boolean readonly,
+ AccountAccessPolicy accessPolicy) {
+ accountSet = new MerkleAccountSet(dataRootHash, cryptoSetting, Bytes.fromString(prefix), exStorage, verStorage,
+ readonly, accessPolicy);
+ }
+
+ @Override
+ public BlockchainIdentity[] getHeaders(int fromIndex, int count) {
+ return accountSet.getHeaders(fromIndex, count);
+ }
+
+ public boolean isReadonly() {
+ return accountSet.isReadonly();
+ }
+
+ void setReadonly() {
+ accountSet.setReadonly();
+ }
+
+ @Override
+ public HashDigest getRootHash() {
+ return accountSet.getRootHash();
+ }
+
+ @Override
+ public long getTotal() {
+ return accountSet.getTotal();
+ }
+
+ @Override
+ public boolean contains(Bytes address) {
+ return accountSet.contains(address);
+ }
+
+ /**
+ * 返回账户的存在性证明;
+ */
+ @Override
+ public MerkleProof getProof(Bytes address) {
+ return accountSet.getProof(address);
+ }
+
+ public DataAccount register(Bytes address, PubKey pubKey, DigitalSignature addressSignature) {
+ // TODO: 未实现对地址签名的校验和记录;
+ CompositeAccount accBase = accountSet.register(address, pubKey);
+ return new DataAccount(accBase);
+ }
+
+ @Override
+ public DataAccount getAccount(String address) {
+ return getAccount(Bytes.fromBase58(address));
+ }
+
+ /**
+ * 返回数据账户;
+ * 如果不存在,则返回 null;
+ *
+ * @param address
+ * @return
+ */
+ @Override
+ public DataAccount getAccount(Bytes address) {
+ CompositeAccount accBase = accountSet.getAccount(address);
+ if (accBase == null) {
+ return null;
+ }
+ return new DataAccount(accBase);
+ }
+
+ @Override
+ public DataAccount getAccount(Bytes address, long version) {
+ CompositeAccount accBase = accountSet.getAccount(address, version);
+ return new DataAccount(accBase);
+ }
+
+ @Override
+ public boolean isUpdated() {
+ return accountSet.isUpdated();
+ }
+
+ @Override
+ public void commit() {
+ accountSet.commit();
+ }
+
+ @Override
+ public void cancel() {
+ accountSet.cancel();
+ }
}
\ No newline at end of file
diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerAdminDataset.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerAdminDataset.java
index dfd06a1e..f73a5ccb 100644
--- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerAdminDataset.java
+++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerAdminDataset.java
@@ -1,481 +1,481 @@
-package com.jd.blockchain.ledger.core;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.jd.blockchain.binaryproto.BinaryProtocol;
-import com.jd.blockchain.binaryproto.DataContractRegistry;
-import com.jd.blockchain.crypto.Crypto;
-import com.jd.blockchain.crypto.HashDigest;
-import com.jd.blockchain.crypto.HashFunction;
-import com.jd.blockchain.ledger.LedgerAdminSettings;
-import com.jd.blockchain.ledger.LedgerException;
-import com.jd.blockchain.ledger.LedgerInitSetting;
-import com.jd.blockchain.ledger.LedgerMetadata;
-import com.jd.blockchain.ledger.LedgerMetadata_V2;
-import com.jd.blockchain.ledger.LedgerSettings;
-import com.jd.blockchain.ledger.ParticipantNode;
-import com.jd.blockchain.ledger.RolePrivilegeSettings;
-import com.jd.blockchain.ledger.UserAuthorizationSettings;
-import com.jd.blockchain.storage.service.ExPolicyKVStorage;
-import com.jd.blockchain.storage.service.ExPolicyKVStorage.ExPolicy;
-import com.jd.blockchain.storage.service.VersioningKVStorage;
-import com.jd.blockchain.utils.Bytes;
-import com.jd.blockchain.utils.Transactional;
-
-public class LedgerAdminDataset implements Transactional, LedgerAdminDataQuery, LedgerAdminSettings {
-
- static {
- DataContractRegistry.register(LedgerMetadata.class);
- DataContractRegistry.register(LedgerMetadata_V2.class);
- }
-
- private static Logger LOGGER = LoggerFactory.getLogger(LedgerAdminDataset.class);
-
- public static final String LEDGER_META_PREFIX = "MTA" + LedgerConsts.KEY_SEPERATOR;
- public static final String LEDGER_PARTICIPANT_PREFIX = "PAR" + LedgerConsts.KEY_SEPERATOR;
- public static final String LEDGER_SETTING_PREFIX = "SET" + LedgerConsts.KEY_SEPERATOR;
- public static final String ROLE_PRIVILEGE_PREFIX = "RPV" + LedgerConsts.KEY_SEPERATOR;
- public static final String USER_ROLE_PREFIX = "URO" + LedgerConsts.KEY_SEPERATOR;
-
- private final Bytes metaPrefix;
- private final Bytes settingPrefix;
-
- private LedgerMetadata_V2 origMetadata;
-
- private LedgerMetadataInfo metadata;
-
- /**
- * 原来的账本设置;
- *
- *
- * 对 LedgerMetadata 修改的新配置不能立即生效,需要达成共识后,在下一次区块计算中才生效;
- */
- private LedgerSettings previousSettings;
-
- private HashDigest previousSettingHash;
-
- /**
- * 账本的参与节点;
- */
- private ParticipantDataset participants;
-
- /**
- * “角色-权限”数据集;
- */
- private RolePrivilegeDataset rolePrivileges;
-
- /**
- * “用户-角色”数据集;
- */
- private UserRoleDataset userRoles;
-
- /**
- * 账本参数配置;
- */
- private LedgerSettings settings;
-
- private ExPolicyKVStorage storage;
-
- private HashDigest adminDataHash;
-
- private boolean readonly;
-
- private boolean updated;
-
- public HashDigest getHash() {
- return adminDataHash;
- }
-
- public boolean isReadonly() {
- return readonly;
- }
-
- void setReadonly() {
- this.readonly = true;
- }
-
- public LedgerSettings getPreviousSetting() {
- return previousSettings;
- }
-
- @Override
- public RolePrivilegeSettings getRolePrivileges() {
- return rolePrivileges;
- }
-
- @Override
- public UserAuthorizationSettings getAuthorizations() {
- return userRoles;
- }
-
- @Override
- public LedgerAdminSettings getAdminInfo() {
- return this;
- }
-
- /**
- * 初始化账本的管理账户;
- *
- *
- *
- * 只在新建账本时调用此方法;
- *
- * @param ledgerSeed
- * @param settings
- * @param partiList
- * @param exPolicyStorage
- * @param versioningStorage
- */
- public LedgerAdminDataset(LedgerInitSetting initSetting, String keyPrefix, ExPolicyKVStorage exPolicyStorage,
- VersioningKVStorage versioningStorage) {
- this.metaPrefix = Bytes.fromString(keyPrefix + LEDGER_META_PREFIX);
- this.settingPrefix = Bytes.fromString(keyPrefix + LEDGER_SETTING_PREFIX);
-
- ParticipantNode[] parties = initSetting.getConsensusParticipants();
- if (parties.length == 0) {
- throw new LedgerException("No participant!");
- }
-
- // 初始化元数据;
- this.metadata = new LedgerMetadataInfo();
- this.metadata.setSeed(initSetting.getLedgerSeed());
- // 新配置;
- this.settings = new LedgerConfiguration(initSetting.getConsensusProvider(), initSetting.getConsensusSettings(),
- initSetting.getCryptoSetting());
- this.previousSettings = new LedgerConfiguration(settings);
- this.previousSettingHash = null;
- this.adminDataHash = null;
-
- // 基于原配置初始化参与者列表;
- String partiPrefix = keyPrefix + LEDGER_PARTICIPANT_PREFIX;
- this.participants = new ParticipantDataset(previousSettings.getCryptoSetting(), partiPrefix, exPolicyStorage,
- versioningStorage);
-
- for (ParticipantNode p : parties) {
- this.participants.addConsensusParticipant(p);
- }
-
- String rolePrivilegePrefix = keyPrefix + ROLE_PRIVILEGE_PREFIX;
- this.rolePrivileges = new RolePrivilegeDataset(this.settings.getCryptoSetting(), rolePrivilegePrefix,
- exPolicyStorage, versioningStorage);
-
- String userRolePrefix = keyPrefix + USER_ROLE_PREFIX;
- this.userRoles = new UserRoleDataset(this.settings.getCryptoSetting(), userRolePrefix, exPolicyStorage,
- versioningStorage);
-
- // 初始化其它属性;
- this.storage = exPolicyStorage;
- this.readonly = false;
- }
-
- public LedgerAdminDataset(HashDigest adminAccountHash, String keyPrefix, ExPolicyKVStorage kvStorage,
- VersioningKVStorage versioningKVStorage, boolean readonly) {
- this.metaPrefix = Bytes.fromString(keyPrefix + LEDGER_META_PREFIX);
- this.settingPrefix = Bytes.fromString(keyPrefix + LEDGER_SETTING_PREFIX);
- this.storage = kvStorage;
- this.readonly = readonly;
- this.origMetadata = loadAndVerifyMetadata(adminAccountHash);
- this.metadata = new LedgerMetadataInfo(origMetadata);
- this.settings = loadAndVerifySettings(metadata.getSettingsHash());
- // 复制记录一份配置作为上一个区块的原始配置,该实例仅供读取,不做修改,也不会回写到存储;
- this.previousSettings = new LedgerConfiguration(settings);
- this.previousSettingHash = metadata.getSettingsHash();
- this.adminDataHash = adminAccountHash;
-
- String partiPrefix = keyPrefix + LEDGER_PARTICIPANT_PREFIX;
- this.participants = new ParticipantDataset(metadata.getParticipantsHash(), previousSettings.getCryptoSetting(),
- partiPrefix, kvStorage, versioningKVStorage, readonly);
-
- String rolePrivilegePrefix = keyPrefix + ROLE_PRIVILEGE_PREFIX;
- this.rolePrivileges = new RolePrivilegeDataset(metadata.getRolePrivilegesHash(),
- previousSettings.getCryptoSetting(), rolePrivilegePrefix, kvStorage, versioningKVStorage, readonly);
-
- String userRolePrefix = keyPrefix + USER_ROLE_PREFIX;
- this.userRoles = new UserRoleDataset(metadata.getUserRolesHash(), previousSettings.getCryptoSetting(),
- userRolePrefix, kvStorage, versioningKVStorage, readonly);
- }
-
- private LedgerSettings loadAndVerifySettings(HashDigest settingsHash) {
- if (settingsHash == null) {
- return null;
- }
- Bytes key = encodeSettingsKey(settingsHash);
- byte[] bytes = storage.get(key);
- HashFunction hashFunc = Crypto.getHashFunction(settingsHash.getAlgorithm());
- if (!hashFunc.verify(settingsHash, bytes)) {
- String errorMsg = "Verification of the hash for ledger setting failed! --[HASH=" + key + "]";
- LOGGER.error(errorMsg);
- throw new LedgerException(errorMsg);
- }
- return deserializeSettings(bytes);
- }
-
- private LedgerSettings deserializeSettings(byte[] bytes) {
- return BinaryProtocol.decode(bytes);
- }
-
- private byte[] serializeSetting(LedgerSettings setting) {
- return BinaryProtocol.encode(setting, LedgerSettings.class);
- }
-
- private LedgerMetadata_V2 loadAndVerifyMetadata(HashDigest adminAccountHash) {
- Bytes key = encodeMetadataKey(adminAccountHash);
- byte[] bytes = storage.get(key);
- HashFunction hashFunc = Crypto.getHashFunction(adminAccountHash.getAlgorithm());
- if (!hashFunc.verify(adminAccountHash, bytes)) {
- String errorMsg = "Verification of the hash for ledger metadata failed! --[HASH=" + key + "]";
- LOGGER.error(errorMsg);
- throw new LedgerException(errorMsg);
- }
- return deserializeMetadata(bytes);
- }
-
- private Bytes encodeSettingsKey(HashDigest settingsHash) {
- return settingPrefix.concat(settingsHash);
- }
-
- private Bytes encodeMetadataKey(HashDigest metadataHash) {
- // return LEDGER_META_PREFIX + metadataHash;
- // return metaPrefix + metadataHash;
- return metaPrefix.concat(metadataHash);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see com.jd.blockchain.ledger.core.LedgerAdministration#getMetadata()
- */
- @Override
- public LedgerMetadata_V2 getMetadata() {
- return metadata;
- }
-
-// /**
-// * 返回原来的账本配置;
-// *
-// *
-// * 此方法总是返回从上一个区块加载的账本配置,即时调用 {@link #setLedgerSetting(LedgerSettings)} 做出了新的更改;
-// *
-// * @return
-// */
-// public LedgerSettings getPreviousSetting() {
-// return previousSettings;
-// }
-
- /**
- * 返回当前设置的账本配置;
- *
- * @return
- */
-
- @Override
- public LedgerSettings getSettings() {
- return settings;
- }
-
- /**
- * 更新账本配置;
- *
- * @param ledgerSetting
- */
- public void setLedgerSetting(LedgerSettings ledgerSetting) {
- if (readonly) {
- throw new IllegalArgumentException("This merkle dataset is readonly!");
- }
- settings = ledgerSetting;
- updated = true;
- }
-
- @Override
- public long getParticipantCount() {
- return participants.getParticipantCount();
- }
-
- @Override
- public ParticipantNode[] getParticipants() {
- return participants.getParticipants();
- }
-
- @Override
- public ParticipantDataset getParticipantDataset() {
- return participants;
- }
-
- /**
- * 加入新的参与方; 如果指定的参与方已经存在,则引发 LedgerException 异常;
- *
- * @param participant
- */
- public void addParticipant(ParticipantNode participant) {
- participants.addConsensusParticipant(participant);
- }
-
-
- /**
- * 更新参与方的状态参数;
- *
- * @param participant
- */
- public void updateParticipant(ParticipantNode participant) {
- participants.updateConsensusParticipant(participant);
- }
-
- @Override
- public boolean isUpdated() {
- return updated || participants.isUpdated() || rolePrivileges.isUpdated() || userRoles.isUpdated();
- }
-
- @Override
- public void commit() {
- if (!isUpdated()) {
- return;
- }
- // 计算并更新参与方集合的根哈希;
- participants.commit();
- metadata.setParticipantsHash(participants.getRootHash());
-
- // 计算并更新角色权限集合的根哈希;
- rolePrivileges.commit();
- metadata.setRolePrivilegesHash(rolePrivileges.getRootHash());
-
- // 计算并更新用户角色授权集合的根哈希;
- userRoles.commit();
- metadata.setUserRolesHash(userRoles.getRootHash());
-
- // 当前区块上下文的密码参数设置的哈希函数;
- HashFunction hashFunc = Crypto.getHashFunction(previousSettings.getCryptoSetting().getHashAlgorithm());
-
- // 计算并更新参数配置的哈希;
- if (settings == null) {
- throw new LedgerException("Missing ledger settings!");
- }
- byte[] settingsBytes = serializeSetting(settings);
- HashDigest settingsHash = hashFunc.hash(settingsBytes);
- metadata.setSettingsHash(settingsHash);
- if (previousSettingHash == null || !previousSettingHash.equals(settingsHash)) {
- Bytes settingsKey = encodeSettingsKey(settingsHash);
- boolean nx = storage.set(settingsKey, settingsBytes, ExPolicy.NOT_EXISTING);
- if (!nx) {
- String base58MetadataHash = settingsHash.toBase58();
- // 有可能发生了并发写入冲突,不同的节点都向同一个存储服务器上写入数据;
- String errMsg = "Ledger metadata already exist! --[MetadataHash=" + base58MetadataHash + "]";
- LOGGER.warn(errMsg);
- throw new LedgerException(errMsg);
- }
- }
-
- // 基于之前的密码配置来计算元数据的哈希;
- byte[] metadataBytes = serializeMetadata(metadata);
-
- HashDigest metadataHash = hashFunc.hash(metadataBytes);
- if (adminDataHash == null || !adminDataHash.equals(metadataHash)) {
- // update modify;
- // String base58MetadataHash = metadataHash.toBase58();
- // String metadataKey = encodeMetadataKey(base58MetadataHash);
- Bytes metadataKey = encodeMetadataKey(metadataHash);
-
- boolean nx = storage.set(metadataKey, metadataBytes, ExPolicy.NOT_EXISTING);
- if (!nx) {
- String base58MetadataHash = metadataHash.toBase58();
- // 有可能发生了并发写入冲突,不同的节点都向同一个存储服务器上写入数据;
- String errMsg = "Ledger metadata already exist! --[MetadataHash=" + base58MetadataHash + "]";
- LOGGER.warn(errMsg);
- throw new LedgerException(errMsg);
- }
-
- adminDataHash = metadataHash;
- }
-
- updated = false;
- }
-
- private LedgerMetadata_V2 deserializeMetadata(byte[] bytes) {
- return BinaryProtocol.decode(bytes);
- }
-
- private byte[] serializeMetadata(LedgerMetadataInfo config) {
- return BinaryProtocol.encode(config, LedgerMetadata_V2.class);
- }
-
- @Override
- public void cancel() {
- if (!isUpdated()) {
- return;
- }
- participants.cancel();
- metadata =origMetadata == null ? new LedgerMetadataInfo() : new LedgerMetadataInfo(origMetadata);
- }
-
- public static class LedgerMetadataInfo implements LedgerMetadata_V2 {
-
- private byte[] seed;
-
-// private LedgerSetting setting;
-
- private HashDigest participantsHash;
-
- private HashDigest settingsHash;
-
- private HashDigest rolePrivilegesHash;
-
- private HashDigest userRolesHash;
-
- public LedgerMetadataInfo() {
- }
-
- public LedgerMetadataInfo(LedgerMetadata_V2 metadata) {
- this.seed = metadata.getSeed();
- this.participantsHash = metadata.getParticipantsHash();
- this.settingsHash = metadata.getSettingsHash();
- this.rolePrivilegesHash = metadata.getRolePrivilegesHash();
- this.userRolesHash = metadata.getUserRolesHash();
- }
-
- @Override
- public byte[] getSeed() {
- return seed;
- }
-
- @Override
- public HashDigest getSettingsHash() {
- return settingsHash;
- }
-
- @Override
- public HashDigest getParticipantsHash() {
- return participantsHash;
- }
-
- @Override
- public HashDigest getRolePrivilegesHash() {
- return rolePrivilegesHash;
- }
-
- @Override
- public HashDigest getUserRolesHash() {
- return userRolesHash;
- }
-
- public void setSeed(byte[] seed) {
- this.seed = seed;
- }
-
- public void setSettingsHash(HashDigest settingHash) {
- this.settingsHash = settingHash;
- }
-
- public void setParticipantsHash(HashDigest participantsHash) {
- this.participantsHash = participantsHash;
- }
-
- public void setRolePrivilegesHash(HashDigest rolePrivilegesHash) {
- this.rolePrivilegesHash = rolePrivilegesHash;
- }
-
- public void setUserRolesHash(HashDigest userRolesHash) {
- this.userRolesHash = userRolesHash;
- }
- }
-
+package com.jd.blockchain.ledger.core;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.jd.blockchain.binaryproto.BinaryProtocol;
+import com.jd.blockchain.binaryproto.DataContractRegistry;
+import com.jd.blockchain.crypto.Crypto;
+import com.jd.blockchain.crypto.HashDigest;
+import com.jd.blockchain.crypto.HashFunction;
+import com.jd.blockchain.ledger.LedgerAdminSettings;
+import com.jd.blockchain.ledger.LedgerException;
+import com.jd.blockchain.ledger.LedgerInitSetting;
+import com.jd.blockchain.ledger.LedgerMetadata;
+import com.jd.blockchain.ledger.LedgerMetadata_V2;
+import com.jd.blockchain.ledger.LedgerSettings;
+import com.jd.blockchain.ledger.ParticipantNode;
+import com.jd.blockchain.ledger.RolePrivilegeSettings;
+import com.jd.blockchain.ledger.UserAuthorizationSettings;
+import com.jd.blockchain.storage.service.ExPolicyKVStorage;
+import com.jd.blockchain.storage.service.ExPolicyKVStorage.ExPolicy;
+import com.jd.blockchain.storage.service.VersioningKVStorage;
+import com.jd.blockchain.utils.Bytes;
+import com.jd.blockchain.utils.Transactional;
+
+public class LedgerAdminDataset implements Transactional, LedgerAdminDataQuery, LedgerAdminSettings {
+
+ static {
+ DataContractRegistry.register(LedgerMetadata.class);
+ DataContractRegistry.register(LedgerMetadata_V2.class);
+ }
+
+ private static Logger LOGGER = LoggerFactory.getLogger(LedgerAdminDataset.class);
+
+ public static final String LEDGER_META_PREFIX = "MTA" + LedgerConsts.KEY_SEPERATOR;
+ public static final String LEDGER_PARTICIPANT_PREFIX = "PAR" + LedgerConsts.KEY_SEPERATOR;
+ public static final String LEDGER_SETTING_PREFIX = "SET" + LedgerConsts.KEY_SEPERATOR;
+ public static final String ROLE_PRIVILEGE_PREFIX = "RPV" + LedgerConsts.KEY_SEPERATOR;
+ public static final String USER_ROLE_PREFIX = "URO" + LedgerConsts.KEY_SEPERATOR;
+
+ private final Bytes metaPrefix;
+ private final Bytes settingPrefix;
+
+ private LedgerMetadata_V2 origMetadata;
+
+ private LedgerMetadataInfo metadata;
+
+ /**
+ * 原来的账本设置;
+ *
+ *
+ * 对 LedgerMetadata 修改的新配置不能立即生效,需要达成共识后,在下一次区块计算中才生效;
+ */
+ private LedgerSettings previousSettings;
+
+ private HashDigest previousSettingHash;
+
+ /**
+ * 账本的参与节点;
+ */
+ private ParticipantDataset participants;
+
+ /**
+ * “角色-权限”数据集;
+ */
+ private RolePrivilegeDataset rolePrivileges;
+
+ /**
+ * “用户-角色”数据集;
+ */
+ private UserRoleDataset userRoles;
+
+ /**
+ * 账本参数配置;
+ */
+ private LedgerSettings settings;
+
+ private ExPolicyKVStorage storage;
+
+ private HashDigest adminDataHash;
+
+ private boolean readonly;
+
+ private boolean updated;
+
+ public HashDigest getHash() {
+ return adminDataHash;
+ }
+
+ public boolean isReadonly() {
+ return readonly;
+ }
+
+ void setReadonly() {
+ this.readonly = true;
+ }
+
+ public LedgerSettings getPreviousSetting() {
+ return previousSettings;
+ }
+
+ @Override
+ public RolePrivilegeSettings getRolePrivileges() {
+ return rolePrivileges;
+ }
+
+ @Override
+ public UserAuthorizationSettings getAuthorizations() {
+ return userRoles;
+ }
+
+ @Override
+ public LedgerAdminSettings getAdminInfo() {
+ return this;
+ }
+
+ /**
+ * 初始化账本的管理账户;
+ *
+ *
+ *
+ * 只在新建账本时调用此方法;
+ *
+ * @param ledgerSeed
+ * @param settings
+ * @param partiList
+ * @param exPolicyStorage
+ * @param versioningStorage
+ */
+ public LedgerAdminDataset(LedgerInitSetting initSetting, String keyPrefix, ExPolicyKVStorage exPolicyStorage,
+ VersioningKVStorage versioningStorage) {
+ this.metaPrefix = Bytes.fromString(keyPrefix + LEDGER_META_PREFIX);
+ this.settingPrefix = Bytes.fromString(keyPrefix + LEDGER_SETTING_PREFIX);
+
+ ParticipantNode[] parties = initSetting.getConsensusParticipants();
+ if (parties.length == 0) {
+ throw new LedgerException("No participant!");
+ }
+
+ // 初始化元数据;
+ this.metadata = new LedgerMetadataInfo();
+ this.metadata.setSeed(initSetting.getLedgerSeed());
+ // 新配置;
+ this.settings = new LedgerConfiguration(initSetting.getConsensusProvider(), initSetting.getConsensusSettings(),
+ initSetting.getCryptoSetting());
+ this.previousSettings = new LedgerConfiguration(settings);
+ this.previousSettingHash = null;
+ this.adminDataHash = null;
+
+ // 基于原配置初始化参与者列表;
+ String partiPrefix = keyPrefix + LEDGER_PARTICIPANT_PREFIX;
+ this.participants = new ParticipantDataset(previousSettings.getCryptoSetting(), partiPrefix, exPolicyStorage,
+ versioningStorage);
+
+ for (ParticipantNode p : parties) {
+ this.participants.addConsensusParticipant(p);
+ }
+
+ String rolePrivilegePrefix = keyPrefix + ROLE_PRIVILEGE_PREFIX;
+ this.rolePrivileges = new RolePrivilegeDataset(this.settings.getCryptoSetting(), rolePrivilegePrefix,
+ exPolicyStorage, versioningStorage);
+
+ String userRolePrefix = keyPrefix + USER_ROLE_PREFIX;
+ this.userRoles = new UserRoleDataset(this.settings.getCryptoSetting(), userRolePrefix, exPolicyStorage,
+ versioningStorage);
+
+ // 初始化其它属性;
+ this.storage = exPolicyStorage;
+ this.readonly = false;
+ }
+
+ public LedgerAdminDataset(HashDigest adminAccountHash, String keyPrefix, ExPolicyKVStorage kvStorage,
+ VersioningKVStorage versioningKVStorage, boolean readonly) {
+ this.metaPrefix = Bytes.fromString(keyPrefix + LEDGER_META_PREFIX);
+ this.settingPrefix = Bytes.fromString(keyPrefix + LEDGER_SETTING_PREFIX);
+ this.storage = kvStorage;
+ this.readonly = readonly;
+ this.origMetadata = loadAndVerifyMetadata(adminAccountHash);
+ this.metadata = new LedgerMetadataInfo(origMetadata);
+ this.settings = loadAndVerifySettings(metadata.getSettingsHash());
+ // 复制记录一份配置作为上一个区块的原始配置,该实例仅供读取,不做修改,也不会回写到存储;
+ this.previousSettings = new LedgerConfiguration(settings);
+ this.previousSettingHash = metadata.getSettingsHash();
+ this.adminDataHash = adminAccountHash;
+
+ String partiPrefix = keyPrefix + LEDGER_PARTICIPANT_PREFIX;
+ this.participants = new ParticipantDataset(metadata.getParticipantsHash(), previousSettings.getCryptoSetting(),
+ partiPrefix, kvStorage, versioningKVStorage, readonly);
+
+ String rolePrivilegePrefix = keyPrefix + ROLE_PRIVILEGE_PREFIX;
+ this.rolePrivileges = new RolePrivilegeDataset(metadata.getRolePrivilegesHash(),
+ previousSettings.getCryptoSetting(), rolePrivilegePrefix, kvStorage, versioningKVStorage, readonly);
+
+ String userRolePrefix = keyPrefix + USER_ROLE_PREFIX;
+ this.userRoles = new UserRoleDataset(metadata.getUserRolesHash(), previousSettings.getCryptoSetting(),
+ userRolePrefix, kvStorage, versioningKVStorage, readonly);
+ }
+
+ private LedgerSettings loadAndVerifySettings(HashDigest settingsHash) {
+ if (settingsHash == null) {
+ return null;
+ }
+ Bytes key = encodeSettingsKey(settingsHash);
+ byte[] bytes = storage.get(key);
+ HashFunction hashFunc = Crypto.getHashFunction(settingsHash.getAlgorithm());
+ if (!hashFunc.verify(settingsHash, bytes)) {
+ String errorMsg = "Verification of the hash for ledger setting failed! --[HASH=" + key + "]";
+ LOGGER.error(errorMsg);
+ throw new LedgerException(errorMsg);
+ }
+ return deserializeSettings(bytes);
+ }
+
+ private LedgerSettings deserializeSettings(byte[] bytes) {
+ return BinaryProtocol.decode(bytes);
+ }
+
+ private byte[] serializeSetting(LedgerSettings setting) {
+ return BinaryProtocol.encode(setting, LedgerSettings.class);
+ }
+
+ private LedgerMetadata_V2 loadAndVerifyMetadata(HashDigest adminAccountHash) {
+ Bytes key = encodeMetadataKey(adminAccountHash);
+ byte[] bytes = storage.get(key);
+ HashFunction hashFunc = Crypto.getHashFunction(adminAccountHash.getAlgorithm());
+ if (!hashFunc.verify(adminAccountHash, bytes)) {
+ String errorMsg = "Verification of the hash for ledger metadata failed! --[HASH=" + key + "]";
+ LOGGER.error(errorMsg);
+ throw new LedgerException(errorMsg);
+ }
+ return deserializeMetadata(bytes);
+ }
+
+ private Bytes encodeSettingsKey(HashDigest settingsHash) {
+ return settingPrefix.concat(settingsHash);
+ }
+
+ private Bytes encodeMetadataKey(HashDigest metadataHash) {
+ // return LEDGER_META_PREFIX + metadataHash;
+ // return metaPrefix + metadataHash;
+ return metaPrefix.concat(metadataHash);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.jd.blockchain.ledger.core.LedgerAdministration#getMetadata()
+ */
+ @Override
+ public LedgerMetadata_V2 getMetadata() {
+ return metadata;
+ }
+
+// /**
+// * 返回原来的账本配置;
+// *
+// *
+// * 此方法总是返回从上一个区块加载的账本配置,即时调用 {@link #setLedgerSetting(LedgerSettings)} 做出了新的更改;
+// *
+// * @return
+// */
+// public LedgerSettings getPreviousSetting() {
+// return previousSettings;
+// }
+
+ /**
+ * 返回当前设置的账本配置;
+ *
+ * @return
+ */
+
+ @Override
+ public LedgerSettings getSettings() {
+ return settings;
+ }
+
+ /**
+ * 更新账本配置;
+ *
+ * @param ledgerSetting
+ */
+ public void setLedgerSetting(LedgerSettings ledgerSetting) {
+ if (readonly) {
+ throw new IllegalArgumentException("This merkle dataset is readonly!");
+ }
+ settings = ledgerSetting;
+ updated = true;
+ }
+
+ @Override
+ public long getParticipantCount() {
+ return participants.getParticipantCount();
+ }
+
+ @Override
+ public ParticipantNode[] getParticipants() {
+ return participants.getParticipants();
+ }
+
+ @Override
+ public ParticipantDataset getParticipantDataset() {
+ return participants;
+ }
+
+ /**
+ * 加入新的参与方; 如果指定的参与方已经存在,则引发 LedgerException 异常;
+ *
+ * @param participant
+ */
+ public void addParticipant(ParticipantNode participant) {
+ participants.addConsensusParticipant(participant);
+ }
+
+
+ /**
+ * 更新参与方的状态参数;
+ *
+ * @param participant
+ */
+ public void updateParticipant(ParticipantNode participant) {
+ participants.updateConsensusParticipant(participant);
+ }
+
+ @Override
+ public boolean isUpdated() {
+ return updated || participants.isUpdated() || rolePrivileges.isUpdated() || userRoles.isUpdated();
+ }
+
+ @Override
+ public void commit() {
+ if (!isUpdated()) {
+ return;
+ }
+ // 计算并更新参与方集合的根哈希;
+ participants.commit();
+ metadata.setParticipantsHash(participants.getRootHash());
+
+ // 计算并更新角色权限集合的根哈希;
+ rolePrivileges.commit();
+ metadata.setRolePrivilegesHash(rolePrivileges.getRootHash());
+
+ // 计算并更新用户角色授权集合的根哈希;
+ userRoles.commit();
+ metadata.setUserRolesHash(userRoles.getRootHash());
+
+ // 当前区块上下文的密码参数设置的哈希函数;
+ HashFunction hashFunc = Crypto.getHashFunction(previousSettings.getCryptoSetting().getHashAlgorithm());
+
+ // 计算并更新参数配置的哈希;
+ if (settings == null) {
+ throw new LedgerException("Missing ledger settings!");
+ }
+ byte[] settingsBytes = serializeSetting(settings);
+ HashDigest settingsHash = hashFunc.hash(settingsBytes);
+ metadata.setSettingsHash(settingsHash);
+ if (previousSettingHash == null || !previousSettingHash.equals(settingsHash)) {
+ Bytes settingsKey = encodeSettingsKey(settingsHash);
+ boolean nx = storage.set(settingsKey, settingsBytes, ExPolicy.NOT_EXISTING);
+ if (!nx) {
+ String base58MetadataHash = settingsHash.toBase58();
+ // 有可能发生了并发写入冲突,不同的节点都向同一个存储服务器上写入数据;
+ String errMsg = "Ledger metadata already exist! --[MetadataHash=" + base58MetadataHash + "]";
+ LOGGER.warn(errMsg);
+ throw new LedgerException(errMsg);
+ }
+ }
+
+ // 基于之前的密码配置来计算元数据的哈希;
+ byte[] metadataBytes = serializeMetadata(metadata);
+
+ HashDigest metadataHash = hashFunc.hash(metadataBytes);
+ if (adminDataHash == null || !adminDataHash.equals(metadataHash)) {
+ // update modify;
+ // String base58MetadataHash = metadataHash.toBase58();
+ // String metadataKey = encodeMetadataKey(base58MetadataHash);
+ Bytes metadataKey = encodeMetadataKey(metadataHash);
+
+ boolean nx = storage.set(metadataKey, metadataBytes, ExPolicy.NOT_EXISTING);
+ if (!nx) {
+ String base58MetadataHash = metadataHash.toBase58();
+ // 有可能发生了并发写入冲突,不同的节点都向同一个存储服务器上写入数据;
+ String errMsg = "Ledger metadata already exist! --[MetadataHash=" + base58MetadataHash + "]";
+ LOGGER.warn(errMsg);
+ throw new LedgerException(errMsg);
+ }
+
+ adminDataHash = metadataHash;
+ }
+
+ updated = false;
+ }
+
+ private LedgerMetadata_V2 deserializeMetadata(byte[] bytes) {
+ return BinaryProtocol.decode(bytes);
+ }
+
+ private byte[] serializeMetadata(LedgerMetadataInfo config) {
+ return BinaryProtocol.encode(config, LedgerMetadata_V2.class);
+ }
+
+ @Override
+ public void cancel() {
+ if (!isUpdated()) {
+ return;
+ }
+ participants.cancel();
+ metadata =origMetadata == null ? new LedgerMetadataInfo() : new LedgerMetadataInfo(origMetadata);
+ }
+
+ public static class LedgerMetadataInfo implements LedgerMetadata_V2 {
+
+ private byte[] seed;
+
+// private LedgerSetting setting;
+
+ private HashDigest participantsHash;
+
+ private HashDigest settingsHash;
+
+ private HashDigest rolePrivilegesHash;
+
+ private HashDigest userRolesHash;
+
+ public LedgerMetadataInfo() {
+ }
+
+ public LedgerMetadataInfo(LedgerMetadata_V2 metadata) {
+ this.seed = metadata.getSeed();
+ this.participantsHash = metadata.getParticipantsHash();
+ this.settingsHash = metadata.getSettingsHash();
+ this.rolePrivilegesHash = metadata.getRolePrivilegesHash();
+ this.userRolesHash = metadata.getUserRolesHash();
+ }
+
+ @Override
+ public byte[] getSeed() {
+ return seed;
+ }
+
+ @Override
+ public HashDigest getSettingsHash() {
+ return settingsHash;
+ }
+
+ @Override
+ public HashDigest getParticipantsHash() {
+ return participantsHash;
+ }
+
+ @Override
+ public HashDigest getRolePrivilegesHash() {
+ return rolePrivilegesHash;
+ }
+
+ @Override
+ public HashDigest getUserRolesHash() {
+ return userRolesHash;
+ }
+
+ public void setSeed(byte[] seed) {
+ this.seed = seed;
+ }
+
+ public void setSettingsHash(HashDigest settingHash) {
+ this.settingsHash = settingHash;
+ }
+
+ public void setParticipantsHash(HashDigest participantsHash) {
+ this.participantsHash = participantsHash;
+ }
+
+ public void setRolePrivilegesHash(HashDigest rolePrivilegesHash) {
+ this.rolePrivilegesHash = rolePrivilegesHash;
+ }
+
+ public void setUserRolesHash(HashDigest userRolesHash) {
+ this.userRolesHash = userRolesHash;
+ }
+ }
+
}
\ No newline at end of file
diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleAccountSet.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleAccountSet.java
index 8f46e235..ea0159fa 100644
--- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleAccountSet.java
+++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleAccountSet.java
@@ -1,411 +1,411 @@
-package com.jd.blockchain.ledger.core;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import com.jd.blockchain.binaryproto.DataContractRegistry;
-import com.jd.blockchain.crypto.AddressEncoding;
-import com.jd.blockchain.crypto.HashDigest;
-import com.jd.blockchain.crypto.PubKey;
-import com.jd.blockchain.ledger.BlockchainIdentity;
-import com.jd.blockchain.ledger.BlockchainIdentityData;
-import com.jd.blockchain.ledger.CryptoSetting;
-import com.jd.blockchain.ledger.LedgerException;
-import com.jd.blockchain.ledger.MerkleProof;
-import com.jd.blockchain.ledger.MerkleSnapshot;
-import com.jd.blockchain.ledger.TypedValue;
-import com.jd.blockchain.storage.service.ExPolicyKVStorage;
-import com.jd.blockchain.storage.service.VersioningKVStorage;
-import com.jd.blockchain.utils.Bytes;
-import com.jd.blockchain.utils.DataEntry;
-import com.jd.blockchain.utils.Transactional;
-
-public class MerkleAccountSet implements Transactional, MerkleProvable, AccountQuery {
-
- static {
- DataContractRegistry.register(MerkleSnapshot.class);
- DataContractRegistry.register(BlockchainIdentity.class);
- }
-
- private final Bytes keyPrefix;
-
- /**
- * 账户根哈希的数据集;
- */
- private MerkleDataSet merkleDataset;
-
- /**
- * The cache of latest version accounts, including accounts getting by querying
- * and by new regiestering ;
- *
- */
- // TODO:未考虑大数据量时,由于缺少过期策略,会导致内存溢出的问题;
- private Map latestAccountsCache = new HashMap<>();
-
- private ExPolicyKVStorage baseExStorage;
-
- private VersioningKVStorage baseVerStorage;
-
- private CryptoSetting cryptoSetting;
-
- private volatile boolean updated;
-
- private AccountAccessPolicy accessPolicy;
-
- public boolean isReadonly() {
- return merkleDataset.isReadonly();
- }
-
- void setReadonly() {
- merkleDataset.setReadonly();
- }
-
- public MerkleAccountSet(CryptoSetting cryptoSetting, Bytes keyPrefix, ExPolicyKVStorage exStorage,
- VersioningKVStorage verStorage, AccountAccessPolicy accessPolicy) {
- this(null, cryptoSetting, keyPrefix, exStorage, verStorage, false, accessPolicy);
- }
-
- public MerkleAccountSet(HashDigest rootHash, CryptoSetting cryptoSetting, Bytes keyPrefix,
- ExPolicyKVStorage exStorage, VersioningKVStorage verStorage, boolean readonly,
- AccountAccessPolicy accessPolicy) {
- this.keyPrefix = keyPrefix;
- this.cryptoSetting = cryptoSetting;
- this.baseExStorage = exStorage;
- this.baseVerStorage = verStorage;
- this.merkleDataset = new MerkleDataSet(rootHash, cryptoSetting, keyPrefix, this.baseExStorage,
- this.baseVerStorage, readonly);
-
- this.accessPolicy = accessPolicy;
- }
-
- @Override
- public HashDigest getRootHash() {
- return merkleDataset.getRootHash();
- }
-
- @Override
- public MerkleProof getProof(Bytes key) {
- return merkleDataset.getProof(key);
- }
-
- @Override
- public BlockchainIdentity[] getHeaders(int fromIndex, int count) {
- DataEntry[] results = merkleDataset.getLatestDataEntries(fromIndex, count);
-
- BlockchainIdentity[] ids = new BlockchainIdentity[results.length];
- for (int i = 0; i < results.length; i++) {
- InnerMerkleAccount account = createAccount(results[i].getKey(), new HashDigest(results[i].getValue()),
- results[i].getVersion(), true);
- ids[i] = account.getID();
- }
- return ids;
- }
-
- /**
- * 返回账户的总数量;
- *
- * @return
- */
- public long getTotal() {
- return merkleDataset.getDataCount();
- }
-
- @Override
- public CompositeAccount getAccount(String address) {
- return getAccount(Bytes.fromBase58(address));
- }
-
- /**
- * 返回最新版本的 Account;
- *
- * @param address
- * @return
- */
- @Override
- public CompositeAccount getAccount(Bytes address) {
- return this.getAccount(address, -1);
- }
-
- /**
- * 账户是否存在;
- *
- * 如果指定的账户已经注册(通过 {@link #register(String, PubKey)} 方法),但尚未提交(通过
- * {@link #commit()} 方法),此方法对该账户仍然返回 false;
- *
- * @param address
- * @return
- */
- public boolean contains(Bytes address) {
- InnerMerkleAccount acc = latestAccountsCache.get(address);
- if (acc != null) {
- // 无论是新注册未提交的,还是缓存已提交的账户实例,都认为是存在;
- return true;
- }
- long latestVersion = merkleDataset.getVersion(address);
- return latestVersion > -1;
- }
-
- /**
- * 返回指定账户的版本;
- * 如果账户已经注册,则返回该账户的最新版本,值大于等于 0;
- * 如果账户不存在,则返回 -1;
- * 如果账户已经注册(通过 {@link #register(String, PubKey)} 方法),但尚未提交(通过 {@link #commit()}
- * 方法),则返回 -1;
- *
- * @param address
- * @return
- */
- public long getVersion(Bytes address) {
- InnerMerkleAccount acc = latestAccountsCache.get(address);
- if (acc != null) {
- // 已注册尚未提交,也返回 -1;
- return acc.getVersion();
- }
-
- return merkleDataset.getVersion(address);
- }
-
- /**
- * 返回指定版本的 Account;
- *
- * 只有最新版本的账户才能可写的,其它都是只读;
- *
- * @param address 账户地址;
- * @param version 账户版本;如果指定为 -1,则返回最新版本;
- * @return
- */
- public CompositeAccount getAccount(Bytes address, long version) {
- version = version < 0 ? -1 : version;
- InnerMerkleAccount acc = latestAccountsCache.get(address);
- if (acc != null && version == -1) {
- return acc;
- } else if (acc != null && acc.getVersion() == version) {
- return acc;
- }
-
- long latestVersion = merkleDataset.getVersion(address);
- if (latestVersion < 0) {
- // Not exist;
- return null;
- }
- if (version > latestVersion) {
- return null;
- }
-
- // 如果是不存在的,或者刚刚新增未提交的账户,则前面一步查询到的 latestVersion 小于 0, 代码不会执行到此;
- if (acc != null && acc.getVersion() != latestVersion) {
- // 当执行到此处时,并且缓冲列表中缓存了最新的版本,
- // 如果当前缓存的最新账户的版本和刚刚从存储中检索得到的最新版本不一致,可能存在外部的并发更新,这超出了系统设计的逻辑;
-
- // TODO:如果是今后扩展至集群方案时,这种不一致的原因可能是由其它集群节点实例执行了更新,这种情况下,最好是放弃旧缓存,并重新加载和缓存最新版本;
- // by huanghaiquan at 2018-9-2 23:03:00;
- throw new IllegalStateException("The latest version in cache is not equals the latest version in storage! "
- + "Mybe some asynchronzing updating are performed out of current server.");
- }
-
- // Now, be sure that "acc == null", so get account from storage;
- // Set readonly for the old version account;
- boolean readonly = (version > -1 && version < latestVersion) || isReadonly();
-
- long qVersion = version == -1 ? latestVersion : version;
- // load account from storage;
- acc = loadAccount(address, readonly, qVersion);
- if (acc == null) {
- return null;
- }
- if (!readonly) {
- // cache the latest version witch enable reading and writing;
- // readonly version of account not necessary to be cached;
- latestAccountsCache.put(address, acc);
- }
- return acc;
- }
-
- public CompositeAccount register(Bytes address, PubKey pubKey) {
- return register(new BlockchainIdentityData(address, pubKey));
- }
-
- /**
- * 注册一个新账户;
- *
- * 如果账户已经存在,则会引发 {@link LedgerException} 异常;
- *
- * 如果指定的地址和公钥不匹配,则会引发 {@link LedgerException} 异常;
- *
- * @param address 区块链地址;
- * @param pubKey 公钥;
- * @return 注册成功的账户对象;
- */
- public CompositeAccount register(BlockchainIdentity accountId) {
- if (isReadonly()) {
- throw new IllegalArgumentException("This AccountSet is readonly!");
- }
-
- Bytes address = accountId.getAddress();
- PubKey pubKey = accountId.getPubKey();
- verifyAddressEncoding(address, pubKey);
-
- InnerMerkleAccount cachedAcc = latestAccountsCache.get(address);
- if (cachedAcc != null) {
- if (cachedAcc.getVersion() < 0) {
- // 同一个新账户已经注册,但尚未提交,所以重复注册不会引起任何变化;
- return cachedAcc;
- }
- // 相同的账户已经存在;
- throw new LedgerException("The registering account already exist!");
- }
- long version = merkleDataset.getVersion(address);
- if (version >= 0) {
- throw new LedgerException("The registering account already exist!");
- }
-
- if (!accessPolicy.checkRegistering(address, pubKey)) {
- throw new LedgerException("Account Registering was rejected for the access policy!");
- }
-
- Bytes prefix = keyPrefix.concat(address);
- InnerMerkleAccount acc = createInstance(accountId, cryptoSetting, prefix);
- latestAccountsCache.put(address, acc);
- updated = true;
-
- return acc;
- }
-
- private void verifyAddressEncoding(Bytes address, PubKey pubKey) {
- Bytes chAddress = AddressEncoding.generateAddress(pubKey);
- if (!chAddress.equals(address)) {
- throw new LedgerException("The registering Address mismatch the specified PubKey!");
- }
- }
-
- private InnerMerkleAccount createInstance(BlockchainIdentity header, CryptoSetting cryptoSetting, Bytes keyPrefix) {
- return new InnerMerkleAccount(header, cryptoSetting, keyPrefix, baseExStorage, baseVerStorage);
- }
-
- /**
- * 加载指定版本的账户;
- *
- * @param address 账户地址;
- * @param readonly 是否只读;
- * @param version 账户的版本;大于等于 0 ;
- * @return
- */
- private InnerMerkleAccount loadAccount(Bytes address, boolean readonly, long version) {
- byte[] rootHashBytes = merkleDataset.getValue(address, version);
- if (rootHashBytes == null) {
- return null;
- }
- HashDigest rootHash = new HashDigest(rootHashBytes);
-
- return createAccount(address, rootHash, version, readonly);
- }
-
- private InnerMerkleAccount createAccount(Bytes address, HashDigest rootHash, long version, boolean readonly) {
- // prefix;
- Bytes prefix = keyPrefix.concat(address);
-
- return new InnerMerkleAccount(address, version, rootHash, cryptoSetting, prefix, baseExStorage, baseVerStorage,
- readonly);
- }
-
- // TODO:优化:区块链身份(地址+公钥)与其Merkle树根哈希分开独立存储;
- // 不必作为一个整块,避免状态数据写入时频繁重写公钥,尤其某些算法的公钥可能很大;
-
- /**
- * 保存账户的根哈希,返回账户的新版本;
- *
- * @param account
- * @return
- */
- private long saveAccount(InnerMerkleAccount account) {
- // 提交更改,更新哈希;
- account.commit();
-
- return account.getVersion();
- }
-
- @Override
- public boolean isUpdated() {
- return updated;
- }
-
- @Override
- public void commit() {
- if (!updated) {
- return;
- }
- try {
- for (InnerMerkleAccount acc : latestAccountsCache.values()) {
- // updated or new created;
- if (acc.isUpdated() || acc.getVersion() < 0) {
- saveAccount(acc);
- }
- }
- merkleDataset.commit();
- } finally {
- updated = false;
- latestAccountsCache.clear();
- }
- }
-
- @Override
- public void cancel() {
- if (!updated) {
- return;
- }
- Bytes[] addresses = new Bytes[latestAccountsCache.size()];
- latestAccountsCache.keySet().toArray(addresses);
- for (Bytes address : addresses) {
- InnerMerkleAccount acc = latestAccountsCache.remove(address);
- // cancel;
- if (acc.isUpdated()) {
- acc.cancel();
- }
- }
- updated = false;
- }
-
- /**
- * 内部实现的账户,监听和同步账户数据的变更;
- *
- * @author huanghaiquan
- *
- */
- private class InnerMerkleAccount extends MerkleAccount {
-
- private long version;
-
- public InnerMerkleAccount(BlockchainIdentity accountID, CryptoSetting cryptoSetting, Bytes keyPrefix,
- ExPolicyKVStorage exStorage, VersioningKVStorage verStorage) {
- super(accountID, cryptoSetting, keyPrefix, exStorage, verStorage);
- this.version = -1;
- }
-
- public InnerMerkleAccount(Bytes address, long version, HashDigest dataRootHash, CryptoSetting cryptoSetting,
- Bytes keyPrefix, ExPolicyKVStorage exStorage, VersioningKVStorage verStorage, boolean readonly) {
- super(address, dataRootHash, cryptoSetting, keyPrefix, exStorage, verStorage, readonly);
- this.version = version;
- }
-
- @Override
- protected void onUpdated(String key, TypedValue value, long expectedVersion, long newVersion) {
- updated = true;
- }
-
- @Override
- protected void onCommited(HashDigest previousRootHash, HashDigest newRootHash) {
- long newVersion = merkleDataset.setValue(this.getAddress(), newRootHash.toBytes(), version);
- if (newVersion < 0) {
- // Update fail;
- throw new LedgerException("Account updating fail! --[Address=" + this.getAddress() + "]");
- }
- this.version = newVersion;
- }
-
- public long getVersion() {
- return version;
- }
-
- }
-
+package com.jd.blockchain.ledger.core;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import com.jd.blockchain.binaryproto.DataContractRegistry;
+import com.jd.blockchain.crypto.AddressEncoding;
+import com.jd.blockchain.crypto.HashDigest;
+import com.jd.blockchain.crypto.PubKey;
+import com.jd.blockchain.ledger.BlockchainIdentity;
+import com.jd.blockchain.ledger.BlockchainIdentityData;
+import com.jd.blockchain.ledger.CryptoSetting;
+import com.jd.blockchain.ledger.LedgerException;
+import com.jd.blockchain.ledger.MerkleProof;
+import com.jd.blockchain.ledger.MerkleSnapshot;
+import com.jd.blockchain.ledger.TypedValue;
+import com.jd.blockchain.storage.service.ExPolicyKVStorage;
+import com.jd.blockchain.storage.service.VersioningKVStorage;
+import com.jd.blockchain.utils.Bytes;
+import com.jd.blockchain.utils.DataEntry;
+import com.jd.blockchain.utils.Transactional;
+
+public class MerkleAccountSet implements Transactional, MerkleProvable, AccountQuery {
+
+ static {
+ DataContractRegistry.register(MerkleSnapshot.class);
+ DataContractRegistry.register(BlockchainIdentity.class);
+ }
+
+ private final Bytes keyPrefix;
+
+ /**
+ * 账户根哈希的数据集;
+ */
+ private MerkleDataSet merkleDataset;
+
+ /**
+ * The cache of latest version accounts, including accounts getting by querying
+ * and by new regiestering ;
+ *
+ */
+ // TODO:未考虑大数据量时,由于缺少过期策略,会导致内存溢出的问题;
+ private Map latestAccountsCache = new HashMap<>();
+
+ private ExPolicyKVStorage baseExStorage;
+
+ private VersioningKVStorage baseVerStorage;
+
+ private CryptoSetting cryptoSetting;
+
+ private volatile boolean updated;
+
+ private AccountAccessPolicy accessPolicy;
+
+ public boolean isReadonly() {
+ return merkleDataset.isReadonly();
+ }
+
+ void setReadonly() {
+ merkleDataset.setReadonly();
+ }
+
+ public MerkleAccountSet(CryptoSetting cryptoSetting, Bytes keyPrefix, ExPolicyKVStorage exStorage,
+ VersioningKVStorage verStorage, AccountAccessPolicy accessPolicy) {
+ this(null, cryptoSetting, keyPrefix, exStorage, verStorage, false, accessPolicy);
+ }
+
+ public MerkleAccountSet(HashDigest rootHash, CryptoSetting cryptoSetting, Bytes keyPrefix,
+ ExPolicyKVStorage exStorage, VersioningKVStorage verStorage, boolean readonly,
+ AccountAccessPolicy accessPolicy) {
+ this.keyPrefix = keyPrefix;
+ this.cryptoSetting = cryptoSetting;
+ this.baseExStorage = exStorage;
+ this.baseVerStorage = verStorage;
+ this.merkleDataset = new MerkleDataSet(rootHash, cryptoSetting, keyPrefix, this.baseExStorage,
+ this.baseVerStorage, readonly);
+
+ this.accessPolicy = accessPolicy;
+ }
+
+ @Override
+ public HashDigest getRootHash() {
+ return merkleDataset.getRootHash();
+ }
+
+ @Override
+ public MerkleProof getProof(Bytes key) {
+ return merkleDataset.getProof(key);
+ }
+
+ @Override
+ public BlockchainIdentity[] getHeaders(int fromIndex, int count) {
+ DataEntry[] results = merkleDataset.getLatestDataEntries(fromIndex, count);
+
+ BlockchainIdentity[] ids = new BlockchainIdentity[results.length];
+ for (int i = 0; i < results.length; i++) {
+ InnerMerkleAccount account = createAccount(results[i].getKey(), new HashDigest(results[i].getValue()),
+ results[i].getVersion(), true);
+ ids[i] = account.getID();
+ }
+ return ids;
+ }
+
+ /**
+ * 返回账户的总数量;
+ *
+ * @return
+ */
+ public long getTotal() {
+ return merkleDataset.getDataCount();
+ }
+
+ @Override
+ public CompositeAccount getAccount(String address) {
+ return getAccount(Bytes.fromBase58(address));
+ }
+
+ /**
+ * 返回最新版本的 Account;
+ *
+ * @param address
+ * @return
+ */
+ @Override
+ public CompositeAccount getAccount(Bytes address) {
+ return this.getAccount(address, -1);
+ }
+
+ /**
+ * 账户是否存在;
+ *
+ * 如果指定的账户已经注册(通过 {@link #register(String, PubKey)} 方法),但尚未提交(通过
+ * {@link #commit()} 方法),此方法对该账户仍然返回 false;
+ *
+ * @param address
+ * @return
+ */
+ public boolean contains(Bytes address) {
+ InnerMerkleAccount acc = latestAccountsCache.get(address);
+ if (acc != null) {
+ // 无论是新注册未提交的,还是缓存已提交的账户实例,都认为是存在;
+ return true;
+ }
+ long latestVersion = merkleDataset.getVersion(address);
+ return latestVersion > -1;
+ }
+
+ /**
+ * 返回指定账户的版本;
+ * 如果账户已经注册,则返回该账户的最新版本,值大于等于 0;
+ * 如果账户不存在,则返回 -1;
+ * 如果账户已经注册(通过 {@link #register(String, PubKey)} 方法),但尚未提交(通过 {@link #commit()}
+ * 方法),则返回 -1;
+ *
+ * @param address
+ * @return
+ */
+ public long getVersion(Bytes address) {
+ InnerMerkleAccount acc = latestAccountsCache.get(address);
+ if (acc != null) {
+ // 已注册尚未提交,也返回 -1;
+ return acc.getVersion();
+ }
+
+ return merkleDataset.getVersion(address);
+ }
+
+ /**
+ * 返回指定版本的 Account;
+ *
+ * 只有最新版本的账户才能可写的,其它都是只读;
+ *
+ * @param address 账户地址;
+ * @param version 账户版本;如果指定为 -1,则返回最新版本;
+ * @return
+ */
+ public CompositeAccount getAccount(Bytes address, long version) {
+ version = version < 0 ? -1 : version;
+ InnerMerkleAccount acc = latestAccountsCache.get(address);
+ if (acc != null && version == -1) {
+ return acc;
+ } else if (acc != null && acc.getVersion() == version) {
+ return acc;
+ }
+
+ long latestVersion = merkleDataset.getVersion(address);
+ if (latestVersion < 0) {
+ // Not exist;
+ return null;
+ }
+ if (version > latestVersion) {
+ return null;
+ }
+
+ // 如果是不存在的,或者刚刚新增未提交的账户,则前面一步查询到的 latestVersion 小于 0, 代码不会执行到此;
+ if (acc != null && acc.getVersion() != latestVersion) {
+ // 当执行到此处时,并且缓冲列表中缓存了最新的版本,
+ // 如果当前缓存的最新账户的版本和刚刚从存储中检索得到的最新版本不一致,可能存在外部的并发更新,这超出了系统设计的逻辑;
+
+ // TODO:如果是今后扩展至集群方案时,这种不一致的原因可能是由其它集群节点实例执行了更新,这种情况下,最好是放弃旧缓存,并重新加载和缓存最新版本;
+ // by huanghaiquan at 2018-9-2 23:03:00;
+ throw new IllegalStateException("The latest version in cache is not equals the latest version in storage! "
+ + "Mybe some asynchronzing updating are performed out of current server.");
+ }
+
+ // Now, be sure that "acc == null", so get account from storage;
+ // Set readonly for the old version account;
+ boolean readonly = (version > -1 && version < latestVersion) || isReadonly();
+
+ long qVersion = version == -1 ? latestVersion : version;
+ // load account from storage;
+ acc = loadAccount(address, readonly, qVersion);
+ if (acc == null) {
+ return null;
+ }
+ if (!readonly) {
+ // cache the latest version witch enable reading and writing;
+ // readonly version of account not necessary to be cached;
+ latestAccountsCache.put(address, acc);
+ }
+ return acc;
+ }
+
+ public CompositeAccount register(Bytes address, PubKey pubKey) {
+ return register(new BlockchainIdentityData(address, pubKey));
+ }
+
+ /**
+ * 注册一个新账户;
+ *
+ * 如果账户已经存在,则会引发 {@link LedgerException} 异常;
+ *
+ * 如果指定的地址和公钥不匹配,则会引发 {@link LedgerException} 异常;
+ *
+ * @param address 区块链地址;
+ * @param pubKey 公钥;
+ * @return 注册成功的账户对象;
+ */
+ public CompositeAccount register(BlockchainIdentity accountId) {
+ if (isReadonly()) {
+ throw new IllegalArgumentException("This AccountSet is readonly!");
+ }
+
+ Bytes address = accountId.getAddress();
+ PubKey pubKey = accountId.getPubKey();
+ verifyAddressEncoding(address, pubKey);
+
+ InnerMerkleAccount cachedAcc = latestAccountsCache.get(address);
+ if (cachedAcc != null) {
+ if (cachedAcc.getVersion() < 0) {
+ // 同一个新账户已经注册,但尚未提交,所以重复注册不会引起任何变化;
+ return cachedAcc;
+ }
+ // 相同的账户已经存在;
+ throw new LedgerException("The registering account already exist!");
+ }
+ long version = merkleDataset.getVersion(address);
+ if (version >= 0) {
+ throw new LedgerException("The registering account already exist!");
+ }
+
+ if (!accessPolicy.checkRegistering(address, pubKey)) {
+ throw new LedgerException("Account Registering was rejected for the access policy!");
+ }
+
+ Bytes prefix = keyPrefix.concat(address);
+ InnerMerkleAccount acc = createInstance(accountId, cryptoSetting, prefix);
+ latestAccountsCache.put(address, acc);
+ updated = true;
+
+ return acc;
+ }
+
+ private void verifyAddressEncoding(Bytes address, PubKey pubKey) {
+ Bytes chAddress = AddressEncoding.generateAddress(pubKey);
+ if (!chAddress.equals(address)) {
+ throw new LedgerException("The registering Address mismatch the specified PubKey!");
+ }
+ }
+
+ private InnerMerkleAccount createInstance(BlockchainIdentity header, CryptoSetting cryptoSetting, Bytes keyPrefix) {
+ return new InnerMerkleAccount(header, cryptoSetting, keyPrefix, baseExStorage, baseVerStorage);
+ }
+
+ /**
+ * 加载指定版本的账户;
+ *
+ * @param address 账户地址;
+ * @param readonly 是否只读;
+ * @param version 账户的版本;大于等于 0 ;
+ * @return
+ */
+ private InnerMerkleAccount loadAccount(Bytes address, boolean readonly, long version) {
+ byte[] rootHashBytes = merkleDataset.getValue(address, version);
+ if (rootHashBytes == null) {
+ return null;
+ }
+ HashDigest rootHash = new HashDigest(rootHashBytes);
+
+ return createAccount(address, rootHash, version, readonly);
+ }
+
+ private InnerMerkleAccount createAccount(Bytes address, HashDigest rootHash, long version, boolean readonly) {
+ // prefix;
+ Bytes prefix = keyPrefix.concat(address);
+
+ return new InnerMerkleAccount(address, version, rootHash, cryptoSetting, prefix, baseExStorage, baseVerStorage,
+ readonly);
+ }
+
+ // TODO:优化:区块链身份(地址+公钥)与其Merkle树根哈希分开独立存储;
+ // 不必作为一个整块,避免状态数据写入时频繁重写公钥,尤其某些算法的公钥可能很大;
+
+ /**
+ * 保存账户的根哈希,返回账户的新版本;
+ *
+ * @param account
+ * @return
+ */
+ private long saveAccount(InnerMerkleAccount account) {
+ // 提交更改,更新哈希;
+ account.commit();
+
+ return account.getVersion();
+ }
+
+ @Override
+ public boolean isUpdated() {
+ return updated;
+ }
+
+ @Override
+ public void commit() {
+ if (!updated) {
+ return;
+ }
+ try {
+ for (InnerMerkleAccount acc : latestAccountsCache.values()) {
+ // updated or new created;
+ if (acc.isUpdated() || acc.getVersion() < 0) {
+ saveAccount(acc);
+ }
+ }
+ merkleDataset.commit();
+ } finally {
+ updated = false;
+ latestAccountsCache.clear();
+ }
+ }
+
+ @Override
+ public void cancel() {
+ if (!updated) {
+ return;
+ }
+ Bytes[] addresses = new Bytes[latestAccountsCache.size()];
+ latestAccountsCache.keySet().toArray(addresses);
+ for (Bytes address : addresses) {
+ InnerMerkleAccount acc = latestAccountsCache.remove(address);
+ // cancel;
+ if (acc.isUpdated()) {
+ acc.cancel();
+ }
+ }
+ updated = false;
+ }
+
+ /**
+ * 内部实现的账户,监听和同步账户数据的变更;
+ *
+ * @author huanghaiquan
+ *
+ */
+ private class InnerMerkleAccount extends MerkleAccount {
+
+ private long version;
+
+ public InnerMerkleAccount(BlockchainIdentity accountID, CryptoSetting cryptoSetting, Bytes keyPrefix,
+ ExPolicyKVStorage exStorage, VersioningKVStorage verStorage) {
+ super(accountID, cryptoSetting, keyPrefix, exStorage, verStorage);
+ this.version = -1;
+ }
+
+ public InnerMerkleAccount(Bytes address, long version, HashDigest dataRootHash, CryptoSetting cryptoSetting,
+ Bytes keyPrefix, ExPolicyKVStorage exStorage, VersioningKVStorage verStorage, boolean readonly) {
+ super(address, dataRootHash, cryptoSetting, keyPrefix, exStorage, verStorage, readonly);
+ this.version = version;
+ }
+
+ @Override
+ protected void onUpdated(String key, TypedValue value, long expectedVersion, long newVersion) {
+ updated = true;
+ }
+
+ @Override
+ protected void onCommited(HashDigest previousRootHash, HashDigest newRootHash) {
+ long newVersion = merkleDataset.setValue(this.getAddress(), newRootHash.toBytes(), version);
+ if (newVersion < 0) {
+ // Update fail;
+ throw new LedgerException("Account updating fail! --[Address=" + this.getAddress() + "]");
+ }
+ this.version = newVersion;
+ }
+
+ public long getVersion() {
+ return version;
+ }
+
+ }
+
}
\ No newline at end of file
diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleDataSet.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleDataSet.java
index 80217efe..4b546404 100644
--- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleDataSet.java
+++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleDataSet.java
@@ -1,740 +1,740 @@
-package com.jd.blockchain.ledger.core;
-
-import com.jd.blockchain.crypto.HashDigest;
-import com.jd.blockchain.ledger.CryptoSetting;
-import com.jd.blockchain.ledger.LedgerException;
-import com.jd.blockchain.ledger.MerkleDataNode;
-import com.jd.blockchain.ledger.MerkleProof;
-import com.jd.blockchain.storage.service.ExPolicyKVStorage;
-import com.jd.blockchain.storage.service.ExPolicyKVStorage.ExPolicy;
-import com.jd.blockchain.storage.service.VersioningKVStorage;
-import com.jd.blockchain.storage.service.utils.BufferedKVStorage;
-import com.jd.blockchain.storage.service.utils.VersioningKVData;
-import com.jd.blockchain.utils.ArrayUtils;
-import com.jd.blockchain.utils.Bytes;
-import com.jd.blockchain.utils.DataEntry;
-import com.jd.blockchain.utils.DataIterator;
-import com.jd.blockchain.utils.Dataset;
-import com.jd.blockchain.utils.Transactional;
-import com.jd.blockchain.utils.io.BytesUtils;
-
-/**
- * 对新的数据项按顺序递增进行编号的 Merkle 数据集;
- *
- * 注:此实现不是线程安全的;
- *
- * @author huanghaiquan
- *
- */
-public class MerkleDataSet implements Transactional, MerkleProvable, Dataset {
-
- /**
- * 4 MB MaxSize of value;
- */
- public static final int MAX_SIZE_OF_VALUE = 4 * 1024 * 1024;
-
- public static final Bytes SN_PREFIX = Bytes.fromString("SN" + LedgerConsts.KEY_SEPERATOR);
- public static final Bytes DATA_PREFIX = Bytes.fromString("KV" + LedgerConsts.KEY_SEPERATOR);
- public static final Bytes MERKLE_TREE_PREFIX = Bytes.fromString("MKL" + LedgerConsts.KEY_SEPERATOR);
-
- private final Bytes snKeyPrefix;
- private final Bytes dataKeyPrefix;
- private final Bytes merkleKeyPrefix;
-
- @SuppressWarnings("unchecked")
- private static final DataEntry[] EMPTY_ENTRIES = new DataEntry[0];
-
- private BufferedKVStorage bufferedStorage;
-
- private VersioningKVStorage valueStorage;
-
- private ExPolicyKVStorage snStorage;
-
- private MerkleTree merkleTree;
-
- private SNGenerator snGenerator;
-
- private boolean readonly;
-
- /*
- * (non-Javadoc)
- *
- * @see com.jd.blockchain.ledger.core.MerkleProvable#getRootHash()
- */
- @Override
- public HashDigest getRootHash() {
- return merkleTree.getRootHash();
- }
-
- /**
- * 创建一个新的 MerkleDataSet;
- *
- * @param setting 密码设置;
- * @param exPolicyStorage 默克尔树的存储;
- * @param versioningStorage 数据的存储;
- */
- public MerkleDataSet(CryptoSetting setting, String keyPrefix, ExPolicyKVStorage exPolicyStorage,
- VersioningKVStorage versioningStorage) {
- this(setting, Bytes.fromString(keyPrefix), exPolicyStorage, versioningStorage);
- }
-
- /**
- * 创建一个新的 MerkleDataSet;
- *
- * @param setting 密码设置;
- * @param exPolicyStorage 默克尔树的存储;
- * @param versioningStorage 数据的存储;
- */
- public MerkleDataSet(CryptoSetting setting, Bytes keyPrefix, ExPolicyKVStorage exPolicyStorage,
- VersioningKVStorage versioningStorage) {
- // 缓冲对KV的写入;
- this.bufferedStorage = new BufferedKVStorage(exPolicyStorage, versioningStorage, false);
-
- // 把存储数据值、SN、Merkle节点的 key 分别加入独立的前缀,避免针对 key 的注入攻击;
- // this.valueStorage = PrefixAppender.prefix(DATA_PREFIX, (VersioningKVStorage)
- // bufferedStorage);
- // this.snStorage = PrefixAppender.prefix(SN_PREFIX, (ExPolicyKVStorage)
- // bufferedStorage);
- snKeyPrefix = keyPrefix.concat(SN_PREFIX);
- dataKeyPrefix = keyPrefix.concat(DATA_PREFIX);
- this.valueStorage = bufferedStorage;
- this.snStorage = bufferedStorage;
-
- // MerkleTree 本身是可缓冲的;
- // ExPolicyKVStorage merkleTreeStorage =
- // PrefixAppender.prefix(MERKLE_TREE_PREFIX, exPolicyStorage);
- merkleKeyPrefix = keyPrefix.concat(MERKLE_TREE_PREFIX);
- ExPolicyKVStorage merkleTreeStorage = exPolicyStorage;
- this.merkleTree = new MerkleTree(setting, merkleKeyPrefix, merkleTreeStorage);
- this.snGenerator = new MerkleSequenceSNGenerator(merkleTree);
- }
-
- /**
- * 从指定的 Merkle 根构建的 MerkleDataSet;
- *
- * @param dataStorage
- * @param defaultMerkleHashAlgorithm
- * @param verifyMerkleHashOnLoad
- * @param merkleTreeStorage
- * @param snGenerator
- */
- public MerkleDataSet(HashDigest merkleRootHash, CryptoSetting setting, String keyPrefix,
- ExPolicyKVStorage exPolicyStorage, VersioningKVStorage versioningStorage, boolean readonly) {
- this(merkleRootHash, setting, Bytes.fromString(keyPrefix), exPolicyStorage, versioningStorage, readonly);
- }
-
- /**
- * 从指定的 Merkle 根构建的 MerkleDataSet;
- *
- * @param dataStorage
- * @param defaultMerkleHashAlgorithm
- * @param verifyMerkleHashOnLoad
- * @param merkleTreeStorage
- * @param snGenerator
- */
- public MerkleDataSet(HashDigest merkleRootHash, CryptoSetting setting, Bytes keyPrefix,
- ExPolicyKVStorage exPolicyStorage, VersioningKVStorage versioningStorage, boolean readonly) {
- // 缓冲对KV的写入;
- this.bufferedStorage = new BufferedKVStorage(exPolicyStorage, versioningStorage, false);
-
- // 把存储数据值、SN、Merkle节点的 key 分别加入独立的前缀,避免针对 key 的注入攻击;
-// snKeyPrefix = Bytes.fromString(keyPrefix + SN_PREFIX);
-// dataKeyPrefix = Bytes.fromString(keyPrefix + DATA_PREFIX);
- snKeyPrefix = keyPrefix.concat(SN_PREFIX);
- dataKeyPrefix = keyPrefix.concat(DATA_PREFIX);
- this.valueStorage = bufferedStorage;
- this.snStorage = bufferedStorage;
-
- // MerkleTree 本身是可缓冲的;
- merkleKeyPrefix = keyPrefix.concat(MERKLE_TREE_PREFIX);
- ExPolicyKVStorage merkleTreeStorage = exPolicyStorage;
- this.merkleTree = new MerkleTree(merkleRootHash, setting, merkleKeyPrefix, merkleTreeStorage, readonly);
-
- this.snGenerator = new MerkleSequenceSNGenerator(merkleTree);
- this.readonly = readonly;
- }
-
- public boolean isReadonly() {
- return readonly;
- }
-
- void setReadonly() {
- this.readonly = true;
- }
-
- @Override
- public long getDataCount() {
- return merkleTree.getDataCount();
- }
-
- /**
- * 返回理论上允许的最大数据索引;
- *
- * @return
- */
- public long getMaxIndex() {
- return merkleTree.getMaxSn();
- }
-
- public byte[][] getLatestValues(long fromIndex, int count) {
- if (count > LedgerConsts.MAX_LIST_COUNT) {
- throw new IllegalArgumentException("Count exceed the upper limit[" + LedgerConsts.MAX_LIST_COUNT + "]!");
- }
- if (fromIndex < 0 || (fromIndex + count) > merkleTree.getDataCount()) {
- throw new IllegalArgumentException("Index out of bound!");
- }
- byte[][] values = new byte[count][];
- for (int i = 0; i < count; i++) {
- MerkleDataNode dataNode = merkleTree.getData(fromIndex + i);
- Bytes dataKey = encodeDataKey(dataNode.getKey());
- values[i] = valueStorage.get(dataKey, dataNode.getVersion());
- }
- return values;
- }
-
- public DataEntry[] getLatestDataEntries(long fromIndex, int count) {
- if (count > LedgerConsts.MAX_LIST_COUNT) {
- throw new IllegalArgumentException("Count exceed the upper limit[" + LedgerConsts.MAX_LIST_COUNT + "]!");
- }
- if (fromIndex < 0 || (fromIndex + count) > merkleTree.getDataCount()) {
- throw new IllegalArgumentException("Index out of bound!");
- }
- if (count == 0) {
- return EMPTY_ENTRIES;
- }
- @SuppressWarnings("unchecked")
- DataEntry[] values = new DataEntry[count];
- byte[] bytesValue;
- for (int i = 0; i < count; i++) {
- MerkleDataNode dataNode = merkleTree.getData(fromIndex + i);
- Bytes dataKey = encodeDataKey(dataNode.getKey());
- bytesValue = valueStorage.get(dataKey, dataNode.getVersion());
- values[i] = new VersioningKVData(dataNode.getKey(), dataNode.getVersion(), bytesValue);
- }
- return values;
- }
-
- public DataEntry getLatestDataEntry(long index) {
- if (index < 0 || index + 1 > merkleTree.getDataCount()) {
- throw new IllegalArgumentException("Index out of bound!");
- }
- byte[] bytesValue;
- MerkleDataNode dataNode = merkleTree.getData(index);
- Bytes dataKey = encodeDataKey(dataNode.getKey());
- bytesValue = valueStorage.get(dataKey, dataNode.getVersion());
- DataEntry entry = new VersioningKVData(dataNode.getKey(), dataNode.getVersion(),
- bytesValue);
- return entry;
- }
-
- /**
- * get the data at the specific index;
- *
- * @param fromIndex
- * @return
- */
- public byte[] getValuesAtIndex(int fromIndex) {
- MerkleDataNode dataNode = merkleTree.getData(fromIndex);
- Bytes dataKey = encodeDataKey(dataNode.getKey());
- return valueStorage.get(dataKey, dataNode.getVersion());
- }
-
- /**
- * get the key at the specific index;
- *
- * @param fromIndex
- * @return
- */
- public String getKeyAtIndex(int fromIndex) {
- MerkleDataNode dataNode = merkleTree.getData(fromIndex);
- // TODO: 未去掉前缀;
- return dataNode.getKey().toUTF8String();
- }
-
-// /**
-// * Create or update the value associated the specified key if the version
-// * checking is passed.
-// *
-// * The value of the key will be updated only if it's latest version equals the
-// * specified version argument.
-// * If the key doesn't exist, it will be created when the version arg was -1.
-// *
-// * If updating is performed, the version of the key increase by 1.
-// * If creating is performed, the version of the key initialize by 0.
-// *
-// * @param key The key of data;
-// * @param value The value of data;
-// * @param version The expected latest version of the key.
-// * @return The new version of the key.
-// * If the key is new created success, then return 0;
-// * If the key is updated success, then return the new version;
-// * If this operation fail by version checking or other reason, then
-// * return -1;
-// */
-// @Override
-// public long setValue(String key, byte[] value, long version) {
-// return setValue(Bytes.fromString(key), value, version);
-// }
-
- /**
- * Create or update the value associated the specified key if the version
- * checking is passed.
- *
- * The value of the key will be updated only if it's latest version equals the
- * specified version argument.
- * If the key doesn't exist, it will be created when the version arg was -1.
- *
- * If updating is performed, the version of the key increase by 1.
- * If creating is performed, the version of the key initialize by 0.
- *
- * @param key The key of data;
- * @param value The value of data;
- * @param version The expected latest version of the key.
- * @return The new version of the key.
- * If the key is new created success, then return 0;
- * If the key is updated success, then return the new version;
- * If this operation fail by version checking or other reason, then
- * return -1;
- */
- @Override
- public long setValue(Bytes key, byte[] value, long version) {
- if (readonly) {
- throw new IllegalArgumentException("This merkle dataset is readonly!");
- }
- if (value.length > MAX_SIZE_OF_VALUE) {
- throw new IllegalArgumentException(
- "The size of value is great than the max size[" + MAX_SIZE_OF_VALUE + "]!");
- }
- Bytes dataKey = encodeDataKey(key);
- long latestVersion = valueStorage.getVersion(dataKey);
- if (version != latestVersion) {
- return -1;
- }
-
- // set into versioning kv storage before adding to merkle tree, in order to
- // check version confliction first;
- long sn;
- long newVersion;
- if (version < 0) {
- // creating ;
- sn = snGenerator.generate(key);
- newVersion = valueStorage.set(dataKey, value, -1);
- if (newVersion < 0) {
- return -1;
- }
- byte[] snBytes = BytesUtils.toBytes(sn);
- Bytes snKey = encodeSNKey(key);
- boolean nx = snStorage.set(snKey, snBytes, ExPolicy.NOT_EXISTING);
- if (!nx) {
- throw new LedgerException("SN already exist! --[KEY=" + key + "]");
- }
- } else {
- // updating;
-
- // TODO: 未在当前实例的层面,实现对输入键-值的缓冲,而直接写入了存储,而 MerkleTree 在未调用 commit
- // 之前是缓冲的,这使得在存储层面的数据会不一致,而未来需要优化;
- newVersion = valueStorage.set(dataKey, value, version);
- if (newVersion < 0) {
- return -1;
- }
-
- sn = getSN(key);
- }
-
- // update merkle tree;
- merkleTree.setData(sn, key, newVersion, value);
- // TODO: 未在当前实例的层面,实现对输入键-值的缓冲,而直接写入了存储,而 MerkleTree 在未调用 commit
- // 之前是缓冲的,这使得在存储层面的数据会不一致,而未来需要优化;
-
- return newVersion;
- }
-
- private Bytes encodeSNKey(Bytes key) {
- return new Bytes(snKeyPrefix, key);
- }
-
- private Bytes encodeDataKey(Bytes key) {
- return new Bytes(dataKeyPrefix, key);
- }
-
- /**
- * 返回指定 key 对应的序号,如果不存在,则返回 -1;
- *
- * @param key
- * @return
- */
- private long getSN(Bytes key) {
- // SN-KEY index entry has never changed;
- Bytes snKey = encodeSNKey(key);
- byte[] snBytes = snStorage.get(snKey);
- if (snBytes == null) {
- // throw new IllegalStateException("Cann't found SN of key[" + key + "] from
- // data storage!");
- return -1;
- }
- return BytesUtils.toLong(snBytes);
- }
-
- /**
- * 返回默克尔树中记录的指定键的版本,在由默克尔树表示的数据集的快照中,这是指定键的最新版本,
- * 但该版本有可能小于实际存储的最新版本(由于后续追加的新修改被之后生成的快照维护);
- *
- * @param key
- * @return 返回指定的键的版本;如果不存在,则返回 -1;
- */
- private long getMerkleVersion(Bytes key) {
- long sn = getSN(key);
- if (sn < 0) {
- return -1;
- }
- MerkleDataNode mdn = merkleTree.getData(sn);
- if (mdn == null) {
- return -1;
- }
- return mdn.getVersion();
- }
-
-// /**
-// * Return the specified version's value;
-// *
-// * If the key with the specified version doesn't exist, then return null;
-// * If the version is specified to -1, then return the latest version's value;
-// *
-// * @param key
-// * @param version
-// */
-// @Override
-// public byte[] getValue(String key, long version) {
-// return getValue(Bytes.fromString(key), version);
-// }
-
- /**
- * Return the specified version's value;
- *
- * If the key with the specified version doesn't exist, then return null;
- * If the version is specified to -1, then return the latest version's value;
- *
- * @param key
- * @param version
- */
- @Override
- public byte[] getValue(Bytes key, long version) {
- long latestVersion = getMerkleVersion(key);
- if (latestVersion < 0 || version > latestVersion) {
- // key not exist, or the specified version is out of the latest version indexed
- // by the current merkletree;
- return null;
- }
- version = version < 0 ? latestVersion : version;
- Bytes dataKey = encodeDataKey(key);
- return valueStorage.get(dataKey, version);
- }
-
-// /**
-// * Return the latest version's value;
-// *
-// * @param key
-// * @return return null if not exist;
-// */
-// @Override
-// public byte[] getValue(String key) {
-// return getValue(Bytes.fromString(key));
-// }
-
- /**
- * Return the latest version's value;
- *
- * @param key
- * @return return null if not exist;
- */
- @Override
- public byte[] getValue(Bytes key) {
- long latestVersion = getMerkleVersion(key);
- if (latestVersion < 0) {
- return null;
- }
- Bytes dataKey = encodeDataKey(key);
- return valueStorage.get(dataKey, latestVersion);
- }
-
-// /**
-// * Return the latest version entry associated the specified key; If the key
-// * doesn't exist, then return -1;
-// *
-// * @param key
-// * @return
-// */
-// @Override
-// public long getVersion(String key) {
-// return getMerkleVersion(Bytes.fromString(key));
-// }
-
- /**
- * Return the latest version entry associated the specified key; If the key
- * doesn't exist, then return -1;
- *
- * @param key
- * @return
- */
- @Override
- public long getVersion(Bytes key) {
- return getMerkleVersion(key);
- }
-
-// @Override
-// public VersioningKVEntry getDataEntry(String key) {
-// return getDataEntry(key, -1);
-// }
-
- /**
- *
- * @param key
- * @return Null if the key doesn't exist!
- */
- @Override
- public DataEntry getDataEntry(Bytes key) {
- return getDataEntry(key, -1);
- }
-
-// @Override
-// public VersioningKVEntry getDataEntry(String key, long version) {
-// Bytes keyBytes = Bytes.fromString(key);
-// long latestVersion = getMerkleVersion(keyBytes);
-// if (latestVersion < 0 || version > latestVersion) {
-// // key not exist, or the specified version is out of the latest version indexed
-// // by the current merkletree;
-// return null;
-// }
-// version = version < 0 ? latestVersion : version;
-// Bytes dataKey = encodeDataKey(keyBytes);
-// byte[] value = valueStorage.get(dataKey, version);
-// if (value == null) {
-// return null;
-// }
-// return new VersioningKVData(key, version, value);
-// }
-
- @Override
- public DataEntry getDataEntry(Bytes key, long version) {
- long latestVersion = getMerkleVersion(key);
- if (latestVersion < 0 || version > latestVersion) {
- // key not exist, or the specified version is out of the latest version indexed
- // by the current merkletree;
- return null;
- }
- version = version < 0 ? latestVersion : version;
- Bytes dataKey = encodeDataKey(key);
- byte[] value = valueStorage.get(dataKey, version);
- if (value == null) {
- return null;
- }
- return new VersioningKVData(key, version, value);
- }
-
- @Override
- public DataIterator iterator() {
- return new AscDataInterator(getDataCount());
- }
-
- @Override
- public DataIterator iteratorDesc() {
- return new DescDataInterator(getDataCount());
- }
-
- public MerkleDataEntry getMerkleEntry(Bytes key, long version) {
- DataEntry dataEntry = getDataEntry(key, version);
- if (dataEntry == null) {
- return null;
- }
- MerkleProof proof = getProof(key);
- return new MerkleDataEntryWrapper(dataEntry, proof);
- }
-
- public MerkleDataEntry getMerkleEntry(Bytes key) {
- DataEntry dataEntry = getDataEntry(key);
- if (dataEntry == null) {
- return null;
- }
- MerkleProof proof = getProof(key);
- return new MerkleDataEntryWrapper(dataEntry, proof);
- }
-
- public MerkleProof getProof(String key) {
- return getProof(Bytes.fromString(key));
- }
-
- /*
- * (non-Javadoc)
- *
- * @see com.jd.blockchain.ledger.core.MerkleProvable#getProof(java.lang.String)
- */
- @Override
- public MerkleProof getProof(Bytes key) {
- long sn = getSN(key);
- if (sn < 0) {
- return null;
- }
- return merkleTree.getProof(sn);
- }
-
- /**
- * A wrapper for {@link DataEntry} and {@link MerkleProof};
- *
- * @author huanghaiquan
- *
- */
- private static class MerkleDataEntryWrapper implements MerkleDataEntry {
-
- private DataEntry data;
- private MerkleProof proof;
-
- public MerkleDataEntryWrapper(DataEntry data, MerkleProof proof) {
- this.data = data;
- this.proof = proof;
- }
-
- @Override
- public DataEntry getData() {
- return data;
- }
-
- @Override
- public MerkleProof getProof() {
- return proof;
- }
-
- }
-
- @Override
- public boolean isUpdated() {
- return bufferedStorage.isUpdated() || merkleTree.isUpdated();
- }
-
- @Override
- public void commit() {
- bufferedStorage.commit();
- merkleTree.commit();
- }
-
- @Override
- public void cancel() {
- bufferedStorage.cancel();
- merkleTree.cancel();
- snGenerator = new MerkleSequenceSNGenerator(merkleTree);
- }
-
- // ----------------------------------------------------------
-
- private class AscDataInterator implements DataIterator {
-
- private final long total;
-
- private long cursor = 0;
-
- public AscDataInterator(long total) {
- this.total = total;
- }
-
- @Override
- public void skip(long count) {
- cursor = nextCursor(count);
- }
-
- private long nextCursor(long skippingCount) {
- long c = cursor + skippingCount;
- return c > total ? total : c;
- }
-
- @Override
- public DataEntry next() {
- if (hasNext()) {
- DataEntry entry = getLatestDataEntry(cursor);
- cursor = nextCursor(1);
- return entry;
- }
- return null;
- }
-
- @Override
- public DataEntry[] next(int count) {
- if (hasNext()) {
- long from = cursor;
- long nextCursor = nextCursor(count);
- long c = nextCursor - cursor;
- if (c > LedgerConsts.MAX_LIST_COUNT) {
- throw new IllegalArgumentException(
- "Count exceed the upper limit[" + LedgerConsts.MAX_LIST_COUNT + "]!");
- }
- DataEntry[] entries = getLatestDataEntries(from, (int) c);
- cursor = nextCursor;
- return entries;
- }
- return EMPTY_ENTRIES;
- }
-
- @Override
- public boolean hasNext() {
- return cursor < total;
- }
-
- }
-
- private class DescDataInterator implements DataIterator {
-
- private final long total;
-
- private long cursor;
-
- public DescDataInterator(long total) {
- this.total = total;
- this.cursor = total - 1;
- }
-
- @Override
- public void skip(long count) {
- cursor = nextCursor(count);
- }
-
- private long nextCursor(long skippingCount) {
- long c = cursor - skippingCount;
- return c < 0 ? -1 : c;
- }
-
- @Override
- public DataEntry next() {
- if (hasNext()) {
- DataEntry entry = getLatestDataEntry(cursor);
- cursor = nextCursor(1);
- return entry;
- }
- return null;
- }
-
- @Override
- public DataEntry[] next(int count) {
- if (hasNext()) {
- long nextCursor = nextCursor(count);
- long from = nextCursor + 1;
- long c = cursor - nextCursor;
- if (c > LedgerConsts.MAX_LIST_COUNT) {
- throw new IllegalArgumentException(
- "Count exceed the upper limit[" + LedgerConsts.MAX_LIST_COUNT + "]!");
- }
- DataEntry[] entries = getLatestDataEntries(from, (int) c);
- // reverse;
- ArrayUtils.reverse(entries);
-
- cursor = nextCursor;
- return entries;
- }
- return EMPTY_ENTRIES;
- }
-
- @Override
- public boolean hasNext() {
- return cursor < total;
- }
-
- }
-
+package com.jd.blockchain.ledger.core;
+
+import com.jd.blockchain.crypto.HashDigest;
+import com.jd.blockchain.ledger.CryptoSetting;
+import com.jd.blockchain.ledger.LedgerException;
+import com.jd.blockchain.ledger.MerkleDataNode;
+import com.jd.blockchain.ledger.MerkleProof;
+import com.jd.blockchain.storage.service.ExPolicyKVStorage;
+import com.jd.blockchain.storage.service.ExPolicyKVStorage.ExPolicy;
+import com.jd.blockchain.storage.service.VersioningKVStorage;
+import com.jd.blockchain.storage.service.utils.BufferedKVStorage;
+import com.jd.blockchain.storage.service.utils.VersioningKVData;
+import com.jd.blockchain.utils.ArrayUtils;
+import com.jd.blockchain.utils.Bytes;
+import com.jd.blockchain.utils.DataEntry;
+import com.jd.blockchain.utils.DataIterator;
+import com.jd.blockchain.utils.Dataset;
+import com.jd.blockchain.utils.Transactional;
+import com.jd.blockchain.utils.io.BytesUtils;
+
+/**
+ * 对新的数据项按顺序递增进行编号的 Merkle 数据集;
+ *
+ * 注:此实现不是线程安全的;
+ *
+ * @author huanghaiquan
+ *
+ */
+public class MerkleDataSet implements Transactional, MerkleProvable, Dataset {
+
+ /**
+ * 4 MB MaxSize of value;
+ */
+ public static final int MAX_SIZE_OF_VALUE = 4 * 1024 * 1024;
+
+ public static final Bytes SN_PREFIX = Bytes.fromString("SN" + LedgerConsts.KEY_SEPERATOR);
+ public static final Bytes DATA_PREFIX = Bytes.fromString("KV" + LedgerConsts.KEY_SEPERATOR);
+ public static final Bytes MERKLE_TREE_PREFIX = Bytes.fromString("MKL" + LedgerConsts.KEY_SEPERATOR);
+
+ private final Bytes snKeyPrefix;
+ private final Bytes dataKeyPrefix;
+ private final Bytes merkleKeyPrefix;
+
+ @SuppressWarnings("unchecked")
+ private static final DataEntry[] EMPTY_ENTRIES = new DataEntry[0];
+
+ private BufferedKVStorage bufferedStorage;
+
+ private VersioningKVStorage valueStorage;
+
+ private ExPolicyKVStorage snStorage;
+
+ private MerkleTree merkleTree;
+
+ private SNGenerator snGenerator;
+
+ private boolean readonly;
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.jd.blockchain.ledger.core.MerkleProvable#getRootHash()
+ */
+ @Override
+ public HashDigest getRootHash() {
+ return merkleTree.getRootHash();
+ }
+
+ /**
+ * 创建一个新的 MerkleDataSet;
+ *
+ * @param setting 密码设置;
+ * @param exPolicyStorage 默克尔树的存储;
+ * @param versioningStorage 数据的存储;
+ */
+ public MerkleDataSet(CryptoSetting setting, String keyPrefix, ExPolicyKVStorage exPolicyStorage,
+ VersioningKVStorage versioningStorage) {
+ this(setting, Bytes.fromString(keyPrefix), exPolicyStorage, versioningStorage);
+ }
+
+ /**
+ * 创建一个新的 MerkleDataSet;
+ *
+ * @param setting 密码设置;
+ * @param exPolicyStorage 默克尔树的存储;
+ * @param versioningStorage 数据的存储;
+ */
+ public MerkleDataSet(CryptoSetting setting, Bytes keyPrefix, ExPolicyKVStorage exPolicyStorage,
+ VersioningKVStorage versioningStorage) {
+ // 缓冲对KV的写入;
+ this.bufferedStorage = new BufferedKVStorage(exPolicyStorage, versioningStorage, false);
+
+ // 把存储数据值、SN、Merkle节点的 key 分别加入独立的前缀,避免针对 key 的注入攻击;
+ // this.valueStorage = PrefixAppender.prefix(DATA_PREFIX, (VersioningKVStorage)
+ // bufferedStorage);
+ // this.snStorage = PrefixAppender.prefix(SN_PREFIX, (ExPolicyKVStorage)
+ // bufferedStorage);
+ snKeyPrefix = keyPrefix.concat(SN_PREFIX);
+ dataKeyPrefix = keyPrefix.concat(DATA_PREFIX);
+ this.valueStorage = bufferedStorage;
+ this.snStorage = bufferedStorage;
+
+ // MerkleTree 本身是可缓冲的;
+ // ExPolicyKVStorage merkleTreeStorage =
+ // PrefixAppender.prefix(MERKLE_TREE_PREFIX, exPolicyStorage);
+ merkleKeyPrefix = keyPrefix.concat(MERKLE_TREE_PREFIX);
+ ExPolicyKVStorage merkleTreeStorage = exPolicyStorage;
+ this.merkleTree = new MerkleTree(setting, merkleKeyPrefix, merkleTreeStorage);
+ this.snGenerator = new MerkleSequenceSNGenerator(merkleTree);
+ }
+
+ /**
+ * 从指定的 Merkle 根构建的 MerkleDataSet;
+ *
+ * @param dataStorage
+ * @param defaultMerkleHashAlgorithm
+ * @param verifyMerkleHashOnLoad
+ * @param merkleTreeStorage
+ * @param snGenerator
+ */
+ public MerkleDataSet(HashDigest merkleRootHash, CryptoSetting setting, String keyPrefix,
+ ExPolicyKVStorage exPolicyStorage, VersioningKVStorage versioningStorage, boolean readonly) {
+ this(merkleRootHash, setting, Bytes.fromString(keyPrefix), exPolicyStorage, versioningStorage, readonly);
+ }
+
+ /**
+ * 从指定的 Merkle 根构建的 MerkleDataSet;
+ *
+ * @param dataStorage
+ * @param defaultMerkleHashAlgorithm
+ * @param verifyMerkleHashOnLoad
+ * @param merkleTreeStorage
+ * @param snGenerator
+ */
+ public MerkleDataSet(HashDigest merkleRootHash, CryptoSetting setting, Bytes keyPrefix,
+ ExPolicyKVStorage exPolicyStorage, VersioningKVStorage versioningStorage, boolean readonly) {
+ // 缓冲对KV的写入;
+ this.bufferedStorage = new BufferedKVStorage(exPolicyStorage, versioningStorage, false);
+
+ // 把存储数据值、SN、Merkle节点的 key 分别加入独立的前缀,避免针对 key 的注入攻击;
+// snKeyPrefix = Bytes.fromString(keyPrefix + SN_PREFIX);
+// dataKeyPrefix = Bytes.fromString(keyPrefix + DATA_PREFIX);
+ snKeyPrefix = keyPrefix.concat(SN_PREFIX);
+ dataKeyPrefix = keyPrefix.concat(DATA_PREFIX);
+ this.valueStorage = bufferedStorage;
+ this.snStorage = bufferedStorage;
+
+ // MerkleTree 本身是可缓冲的;
+ merkleKeyPrefix = keyPrefix.concat(MERKLE_TREE_PREFIX);
+ ExPolicyKVStorage merkleTreeStorage = exPolicyStorage;
+ this.merkleTree = new MerkleTree(merkleRootHash, setting, merkleKeyPrefix, merkleTreeStorage, readonly);
+
+ this.snGenerator = new MerkleSequenceSNGenerator(merkleTree);
+ this.readonly = readonly;
+ }
+
+ public boolean isReadonly() {
+ return readonly;
+ }
+
+ void setReadonly() {
+ this.readonly = true;
+ }
+
+ @Override
+ public long getDataCount() {
+ return merkleTree.getDataCount();
+ }
+
+ /**
+ * 返回理论上允许的最大数据索引;
+ *
+ * @return
+ */
+ public long getMaxIndex() {
+ return merkleTree.getMaxSn();
+ }
+
+ public byte[][] getLatestValues(long fromIndex, int count) {
+ if (count > LedgerConsts.MAX_LIST_COUNT) {
+ throw new IllegalArgumentException("Count exceed the upper limit[" + LedgerConsts.MAX_LIST_COUNT + "]!");
+ }
+ if (fromIndex < 0 || (fromIndex + count) > merkleTree.getDataCount()) {
+ throw new IllegalArgumentException("Index out of bound!");
+ }
+ byte[][] values = new byte[count][];
+ for (int i = 0; i < count; i++) {
+ MerkleDataNode dataNode = merkleTree.getData(fromIndex + i);
+ Bytes dataKey = encodeDataKey(dataNode.getKey());
+ values[i] = valueStorage.get(dataKey, dataNode.getVersion());
+ }
+ return values;
+ }
+
+ public DataEntry[] getLatestDataEntries(long fromIndex, int count) {
+ if (count > LedgerConsts.MAX_LIST_COUNT) {
+ throw new IllegalArgumentException("Count exceed the upper limit[" + LedgerConsts.MAX_LIST_COUNT + "]!");
+ }
+ if (fromIndex < 0 || (fromIndex + count) > merkleTree.getDataCount()) {
+ throw new IllegalArgumentException("Index out of bound!");
+ }
+ if (count == 0) {
+ return EMPTY_ENTRIES;
+ }
+ @SuppressWarnings("unchecked")
+ DataEntry[] values = new DataEntry[count];
+ byte[] bytesValue;
+ for (int i = 0; i < count; i++) {
+ MerkleDataNode dataNode = merkleTree.getData(fromIndex + i);
+ Bytes dataKey = encodeDataKey(dataNode.getKey());
+ bytesValue = valueStorage.get(dataKey, dataNode.getVersion());
+ values[i] = new VersioningKVData(dataNode.getKey(), dataNode.getVersion(), bytesValue);
+ }
+ return values;
+ }
+
+ public DataEntry getLatestDataEntry(long index) {
+ if (index < 0 || index + 1 > merkleTree.getDataCount()) {
+ throw new IllegalArgumentException("Index out of bound!");
+ }
+ byte[] bytesValue;
+ MerkleDataNode dataNode = merkleTree.getData(index);
+ Bytes dataKey = encodeDataKey(dataNode.getKey());
+ bytesValue = valueStorage.get(dataKey, dataNode.getVersion());
+ DataEntry entry = new VersioningKVData(dataNode.getKey(), dataNode.getVersion(),
+ bytesValue);
+ return entry;
+ }
+
+ /**
+ * get the data at the specific index;
+ *
+ * @param fromIndex
+ * @return
+ */
+ public byte[] getValuesAtIndex(int fromIndex) {
+ MerkleDataNode dataNode = merkleTree.getData(fromIndex);
+ Bytes dataKey = encodeDataKey(dataNode.getKey());
+ return valueStorage.get(dataKey, dataNode.getVersion());
+ }
+
+ /**
+ * get the key at the specific index;
+ *
+ * @param fromIndex
+ * @return
+ */
+ public String getKeyAtIndex(int fromIndex) {
+ MerkleDataNode dataNode = merkleTree.getData(fromIndex);
+ // TODO: 未去掉前缀;
+ return dataNode.getKey().toUTF8String();
+ }
+
+// /**
+// * Create or update the value associated the specified key if the version
+// * checking is passed.
+// *
+// * The value of the key will be updated only if it's latest version equals the
+// * specified version argument.
+// * If the key doesn't exist, it will be created when the version arg was -1.
+// *
+// * If updating is performed, the version of the key increase by 1.
+// * If creating is performed, the version of the key initialize by 0.
+// *
+// * @param key The key of data;
+// * @param value The value of data;
+// * @param version The expected latest version of the key.
+// * @return The new version of the key.
+// * If the key is new created success, then return 0;
+// * If the key is updated success, then return the new version;
+// * If this operation fail by version checking or other reason, then
+// * return -1;
+// */
+// @Override
+// public long setValue(String key, byte[] value, long version) {
+// return setValue(Bytes.fromString(key), value, version);
+// }
+
+ /**
+ * Create or update the value associated the specified key if the version
+ * checking is passed.
+ *
+ * The value of the key will be updated only if it's latest version equals the
+ * specified version argument.
+ * If the key doesn't exist, it will be created when the version arg was -1.
+ *
+ * If updating is performed, the version of the key increase by 1.
+ * If creating is performed, the version of the key initialize by 0.
+ *
+ * @param key The key of data;
+ * @param value The value of data;
+ * @param version The expected latest version of the key.
+ * @return The new version of the key.
+ * If the key is new created success, then return 0;
+ * If the key is updated success, then return the new version;
+ * If this operation fail by version checking or other reason, then
+ * return -1;
+ */
+ @Override
+ public long setValue(Bytes key, byte[] value, long version) {
+ if (readonly) {
+ throw new IllegalArgumentException("This merkle dataset is readonly!");
+ }
+ if (value.length > MAX_SIZE_OF_VALUE) {
+ throw new IllegalArgumentException(
+ "The size of value is great than the max size[" + MAX_SIZE_OF_VALUE + "]!");
+ }
+ Bytes dataKey = encodeDataKey(key);
+ long latestVersion = valueStorage.getVersion(dataKey);
+ if (version != latestVersion) {
+ return -1;
+ }
+
+ // set into versioning kv storage before adding to merkle tree, in order to
+ // check version confliction first;
+ long sn;
+ long newVersion;
+ if (version < 0) {
+ // creating ;
+ sn = snGenerator.generate(key);
+ newVersion = valueStorage.set(dataKey, value, -1);
+ if (newVersion < 0) {
+ return -1;
+ }
+ byte[] snBytes = BytesUtils.toBytes(sn);
+ Bytes snKey = encodeSNKey(key);
+ boolean nx = snStorage.set(snKey, snBytes, ExPolicy.NOT_EXISTING);
+ if (!nx) {
+ throw new LedgerException("SN already exist! --[KEY=" + key + "]");
+ }
+ } else {
+ // updating;
+
+ // TODO: 未在当前实例的层面,实现对输入键-值的缓冲,而直接写入了存储,而 MerkleTree 在未调用 commit
+ // 之前是缓冲的,这使得在存储层面的数据会不一致,而未来需要优化;
+ newVersion = valueStorage.set(dataKey, value, version);
+ if (newVersion < 0) {
+ return -1;
+ }
+
+ sn = getSN(key);
+ }
+
+ // update merkle tree;
+ merkleTree.setData(sn, key, newVersion, value);
+ // TODO: 未在当前实例的层面,实现对输入键-值的缓冲,而直接写入了存储,而 MerkleTree 在未调用 commit
+ // 之前是缓冲的,这使得在存储层面的数据会不一致,而未来需要优化;
+
+ return newVersion;
+ }
+
+ private Bytes encodeSNKey(Bytes key) {
+ return new Bytes(snKeyPrefix, key);
+ }
+
+ private Bytes encodeDataKey(Bytes key) {
+ return new Bytes(dataKeyPrefix, key);
+ }
+
+ /**
+ * 返回指定 key 对应的序号,如果不存在,则返回 -1;
+ *
+ * @param key
+ * @return
+ */
+ private long getSN(Bytes key) {
+ // SN-KEY index entry has never changed;
+ Bytes snKey = encodeSNKey(key);
+ byte[] snBytes = snStorage.get(snKey);
+ if (snBytes == null) {
+ // throw new IllegalStateException("Cann't found SN of key[" + key + "] from
+ // data storage!");
+ return -1;
+ }
+ return BytesUtils.toLong(snBytes);
+ }
+
+ /**
+ * 返回默克尔树中记录的指定键的版本,在由默克尔树表示的数据集的快照中,这是指定键的最新版本,
+ * 但该版本有可能小于实际存储的最新版本(由于后续追加的新修改被之后生成的快照维护);
+ *
+ * @param key
+ * @return 返回指定的键的版本;如果不存在,则返回 -1;
+ */
+ private long getMerkleVersion(Bytes key) {
+ long sn = getSN(key);
+ if (sn < 0) {
+ return -1;
+ }
+ MerkleDataNode mdn = merkleTree.getData(sn);
+ if (mdn == null) {
+ return -1;
+ }
+ return mdn.getVersion();
+ }
+
+// /**
+// * Return the specified version's value;
+// *
+// * If the key with the specified version doesn't exist, then return null;
+// * If the version is specified to -1, then return the latest version's value;
+// *
+// * @param key
+// * @param version
+// */
+// @Override
+// public byte[] getValue(String key, long version) {
+// return getValue(Bytes.fromString(key), version);
+// }
+
+ /**
+ * Return the specified version's value;
+ *
+ * If the key with the specified version doesn't exist, then return null;
+ * If the version is specified to -1, then return the latest version's value;
+ *
+ * @param key
+ * @param version
+ */
+ @Override
+ public byte[] getValue(Bytes key, long version) {
+ long latestVersion = getMerkleVersion(key);
+ if (latestVersion < 0 || version > latestVersion) {
+ // key not exist, or the specified version is out of the latest version indexed
+ // by the current merkletree;
+ return null;
+ }
+ version = version < 0 ? latestVersion : version;
+ Bytes dataKey = encodeDataKey(key);
+ return valueStorage.get(dataKey, version);
+ }
+
+// /**
+// * Return the latest version's value;
+// *
+// * @param key
+// * @return return null if not exist;
+// */
+// @Override
+// public byte[] getValue(String key) {
+// return getValue(Bytes.fromString(key));
+// }
+
+ /**
+ * Return the latest version's value;
+ *
+ * @param key
+ * @return return null if not exist;
+ */
+ @Override
+ public byte[] getValue(Bytes key) {
+ long latestVersion = getMerkleVersion(key);
+ if (latestVersion < 0) {
+ return null;
+ }
+ Bytes dataKey = encodeDataKey(key);
+ return valueStorage.get(dataKey, latestVersion);
+ }
+
+// /**
+// * Return the latest version entry associated the specified key; If the key
+// * doesn't exist, then return -1;
+// *
+// * @param key
+// * @return
+// */
+// @Override
+// public long getVersion(String key) {
+// return getMerkleVersion(Bytes.fromString(key));
+// }
+
+ /**
+ * Return the latest version entry associated the specified key; If the key
+ * doesn't exist, then return -1;
+ *
+ * @param key
+ * @return
+ */
+ @Override
+ public long getVersion(Bytes key) {
+ return getMerkleVersion(key);
+ }
+
+// @Override
+// public VersioningKVEntry getDataEntry(String key) {
+// return getDataEntry(key, -1);
+// }
+
+ /**
+ *
+ * @param key
+ * @return Null if the key doesn't exist!
+ */
+ @Override
+ public DataEntry getDataEntry(Bytes key) {
+ return getDataEntry(key, -1);
+ }
+
+// @Override
+// public VersioningKVEntry getDataEntry(String key, long version) {
+// Bytes keyBytes = Bytes.fromString(key);
+// long latestVersion = getMerkleVersion(keyBytes);
+// if (latestVersion < 0 || version > latestVersion) {
+// // key not exist, or the specified version is out of the latest version indexed
+// // by the current merkletree;
+// return null;
+// }
+// version = version < 0 ? latestVersion : version;
+// Bytes dataKey = encodeDataKey(keyBytes);
+// byte[] value = valueStorage.get(dataKey, version);
+// if (value == null) {
+// return null;
+// }
+// return new VersioningKVData(key, version, value);
+// }
+
+ @Override
+ public DataEntry getDataEntry(Bytes key, long version) {
+ long latestVersion = getMerkleVersion(key);
+ if (latestVersion < 0 || version > latestVersion) {
+ // key not exist, or the specified version is out of the latest version indexed
+ // by the current merkletree;
+ return null;
+ }
+ version = version < 0 ? latestVersion : version;
+ Bytes dataKey = encodeDataKey(key);
+ byte[] value = valueStorage.get(dataKey, version);
+ if (value == null) {
+ return null;
+ }
+ return new VersioningKVData(key, version, value);
+ }
+
+ @Override
+ public DataIterator iterator() {
+ return new AscDataInterator(getDataCount());
+ }
+
+ @Override
+ public DataIterator iteratorDesc() {
+ return new DescDataInterator(getDataCount());
+ }
+
+ public MerkleDataEntry getMerkleEntry(Bytes key, long version) {
+ DataEntry dataEntry = getDataEntry(key, version);
+ if (dataEntry == null) {
+ return null;
+ }
+ MerkleProof proof = getProof(key);
+ return new MerkleDataEntryWrapper(dataEntry, proof);
+ }
+
+ public MerkleDataEntry getMerkleEntry(Bytes key) {
+ DataEntry dataEntry = getDataEntry(key);
+ if (dataEntry == null) {
+ return null;
+ }
+ MerkleProof proof = getProof(key);
+ return new MerkleDataEntryWrapper(dataEntry, proof);
+ }
+
+ public MerkleProof getProof(String key) {
+ return getProof(Bytes.fromString(key));
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.jd.blockchain.ledger.core.MerkleProvable#getProof(java.lang.String)
+ */
+ @Override
+ public MerkleProof getProof(Bytes key) {
+ long sn = getSN(key);
+ if (sn < 0) {
+ return null;
+ }
+ return merkleTree.getProof(sn);
+ }
+
+ /**
+ * A wrapper for {@link DataEntry} and {@link MerkleProof};
+ *
+ * @author huanghaiquan
+ *
+ */
+ private static class MerkleDataEntryWrapper implements MerkleDataEntry {
+
+ private DataEntry data;
+ private MerkleProof proof;
+
+ public MerkleDataEntryWrapper(DataEntry data, MerkleProof proof) {
+ this.data = data;
+ this.proof = proof;
+ }
+
+ @Override
+ public DataEntry getData() {
+ return data;
+ }
+
+ @Override
+ public MerkleProof getProof() {
+ return proof;
+ }
+
+ }
+
+ @Override
+ public boolean isUpdated() {
+ return bufferedStorage.isUpdated() || merkleTree.isUpdated();
+ }
+
+ @Override
+ public void commit() {
+ bufferedStorage.commit();
+ merkleTree.commit();
+ }
+
+ @Override
+ public void cancel() {
+ bufferedStorage.cancel();
+ merkleTree.cancel();
+ snGenerator = new MerkleSequenceSNGenerator(merkleTree);
+ }
+
+ // ----------------------------------------------------------
+
+ private class AscDataInterator implements DataIterator {
+
+ private final long total;
+
+ private long cursor = 0;
+
+ public AscDataInterator(long total) {
+ this.total = total;
+ }
+
+ @Override
+ public void skip(long count) {
+ cursor = nextCursor(count);
+ }
+
+ private long nextCursor(long skippingCount) {
+ long c = cursor + skippingCount;
+ return c > total ? total : c;
+ }
+
+ @Override
+ public DataEntry next() {
+ if (hasNext()) {
+ DataEntry entry = getLatestDataEntry(cursor);
+ cursor = nextCursor(1);
+ return entry;
+ }
+ return null;
+ }
+
+ @Override
+ public DataEntry[] next(int count) {
+ if (hasNext()) {
+ long from = cursor;
+ long nextCursor = nextCursor(count);
+ long c = nextCursor - cursor;
+ if (c > LedgerConsts.MAX_LIST_COUNT) {
+ throw new IllegalArgumentException(
+ "Count exceed the upper limit[" + LedgerConsts.MAX_LIST_COUNT + "]!");
+ }
+ DataEntry[] entries = getLatestDataEntries(from, (int) c);
+ cursor = nextCursor;
+ return entries;
+ }
+ return EMPTY_ENTRIES;
+ }
+
+ @Override
+ public boolean hasNext() {
+ return cursor < total;
+ }
+
+ }
+
+ private class DescDataInterator implements DataIterator {
+
+ private final long total;
+
+ private long cursor;
+
+ public DescDataInterator(long total) {
+ this.total = total;
+ this.cursor = total - 1;
+ }
+
+ @Override
+ public void skip(long count) {
+ cursor = nextCursor(count);
+ }
+
+ private long nextCursor(long skippingCount) {
+ long c = cursor - skippingCount;
+ return c < 0 ? -1 : c;
+ }
+
+ @Override
+ public DataEntry next() {
+ if (hasNext()) {
+ DataEntry entry = getLatestDataEntry(cursor);
+ cursor = nextCursor(1);
+ return entry;
+ }
+ return null;
+ }
+
+ @Override
+ public DataEntry[] next(int count) {
+ if (hasNext()) {
+ long nextCursor = nextCursor(count);
+ long from = nextCursor + 1;
+ long c = cursor - nextCursor;
+ if (c > LedgerConsts.MAX_LIST_COUNT) {
+ throw new IllegalArgumentException(
+ "Count exceed the upper limit[" + LedgerConsts.MAX_LIST_COUNT + "]!");
+ }
+ DataEntry[] entries = getLatestDataEntries(from, (int) c);
+ // reverse;
+ ArrayUtils.reverse(entries);
+
+ cursor = nextCursor;
+ return entries;
+ }
+ return EMPTY_ENTRIES;
+ }
+
+ @Override
+ public boolean hasNext() {
+ return cursor < total;
+ }
+
+ }
+
}
\ No newline at end of file
diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/Node.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/Node.java
index fd8df0cd..d9db7e70 100644
--- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/Node.java
+++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/Node.java
@@ -1,11 +1,11 @@
-package com.jd.blockchain.ledger.core;
-
-
-public class Node {
-
- public Node(){
-
- }
-
-
+package com.jd.blockchain.ledger.core;
+
+
+public class Node {
+
+ public Node(){
+
+ }
+
+
}
\ No newline at end of file
diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ParticipantCertData.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ParticipantCertData.java
index c9212bb2..ff03355d 100644
--- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ParticipantCertData.java
+++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ParticipantCertData.java
@@ -1,73 +1,73 @@
-package com.jd.blockchain.ledger.core;
-
-import com.jd.blockchain.crypto.PubKey;
-import com.jd.blockchain.ledger.ParticipantNode;
-import com.jd.blockchain.utils.Bytes;
-import com.jd.blockchain.ledger.ParticipantNodeState;
-
-/**
- * 参与方证书数据对象;
- *
- * @author huanghaiquan
- *
- */
-public class ParticipantCertData implements ParticipantNode {
-
- private int id;
- private Bytes address;
- private String name;
- private PubKey pubKey;
- private ParticipantNodeState participantNodeState;
-
- public ParticipantCertData() {
- }
-
- public ParticipantCertData(ParticipantNode participantNode) {
- this.id = participantNode.getId();
- this.address = participantNode.getAddress();
- this.name = participantNode.getName();
- this.pubKey = participantNode.getPubKey();
- this.participantNodeState = participantNode.getParticipantNodeState();
- }
-
- public ParticipantCertData(Bytes address, String name, PubKey pubKey, ParticipantNodeState participantNodeState) {
- this.address = address;
- this.name = name;
- this.pubKey = pubKey;
- this.participantNodeState = participantNodeState;
- }
-
- @Override
- public Bytes getAddress() {
- return address;
- }
-
- @Override
- public String getName() {
- return name;
- }
-
- @Override
- public PubKey getPubKey() {
- return pubKey;
- }
-
- @Override
- public int getId() {
- return id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
-
- @Override
- public ParticipantNodeState getParticipantNodeState() {
- return participantNodeState;
- }
-
- public void setParticipantNodeState(ParticipantNodeState participantNodeState) {
- this.participantNodeState = participantNodeState;
- }
-
+package com.jd.blockchain.ledger.core;
+
+import com.jd.blockchain.crypto.PubKey;
+import com.jd.blockchain.ledger.ParticipantNode;
+import com.jd.blockchain.utils.Bytes;
+import com.jd.blockchain.ledger.ParticipantNodeState;
+
+/**
+ * 参与方证书数据对象;
+ *
+ * @author huanghaiquan
+ *
+ */
+public class ParticipantCertData implements ParticipantNode {
+
+ private int id;
+ private Bytes address;
+ private String name;
+ private PubKey pubKey;
+ private ParticipantNodeState participantNodeState;
+
+ public ParticipantCertData() {
+ }
+
+ public ParticipantCertData(ParticipantNode participantNode) {
+ this.id = participantNode.getId();
+ this.address = participantNode.getAddress();
+ this.name = participantNode.getName();
+ this.pubKey = participantNode.getPubKey();
+ this.participantNodeState = participantNode.getParticipantNodeState();
+ }
+
+ public ParticipantCertData(Bytes address, String name, PubKey pubKey, ParticipantNodeState participantNodeState) {
+ this.address = address;
+ this.name = name;
+ this.pubKey = pubKey;
+ this.participantNodeState = participantNodeState;
+ }
+
+ @Override
+ public Bytes getAddress() {
+ return address;
+ }
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public PubKey getPubKey() {
+ return pubKey;
+ }
+
+ @Override
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ @Override
+ public ParticipantNodeState getParticipantNodeState() {
+ return participantNodeState;
+ }
+
+ public void setParticipantNodeState(ParticipantNodeState participantNodeState) {
+ this.participantNodeState = participantNodeState;
+ }
+
}
\ No newline at end of file
diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/Peer.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/Peer.java
index 2ef46c99..19a4dcbc 100644
--- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/Peer.java
+++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/Peer.java
@@ -1,22 +1,22 @@
-package com.jd.blockchain.ledger.core;
-
-import com.jd.blockchain.ledger.ParticipantNode;
-
-/**
- * @author hhq
- * @version 1.0
- * @created 14-6��-2018 12:13:33
- */
-public class Peer extends Node {
-
- public ParticipantNode m_Participant;
-
- public Peer(){
-
- }
-
- public void finalize() throws Throwable {
- super.finalize();
- }
-
+package com.jd.blockchain.ledger.core;
+
+import com.jd.blockchain.ledger.ParticipantNode;
+
+/**
+ * @author hhq
+ * @version 1.0
+ * @created 14-6��-2018 12:13:33
+ */
+public class Peer extends Node {
+
+ public ParticipantNode m_Participant;
+
+ public Peer(){
+
+ }
+
+ public void finalize() throws Throwable {
+ super.finalize();
+ }
+
}
\ No newline at end of file
diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserAccount.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserAccount.java
index 87696e86..08d7c248 100644
--- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserAccount.java
+++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserAccount.java
@@ -1,85 +1,85 @@
-package com.jd.blockchain.ledger.core;
-
-import com.jd.blockchain.crypto.PubKey;
-import com.jd.blockchain.ledger.BytesValue;
-import com.jd.blockchain.ledger.LedgerException;
-import com.jd.blockchain.ledger.TypedValue;
-import com.jd.blockchain.ledger.UserInfo;
-import com.jd.blockchain.utils.Bytes;
-
-/**
- * 用户账户;
- *
- * @author huanghaiquan
- *
- */
-public class UserAccount extends AccountDecorator implements UserInfo { // implements UserInfo {
-
- private static final String USER_INFO_PREFIX = "PROP" + LedgerConsts.KEY_SEPERATOR;
-
- private static final String DATA_PUB_KEY = "DATA-PUBKEY";
-
- public UserAccount(CompositeAccount baseAccount) {
- super(baseAccount);
- }
-
- private PubKey dataPubKey;
-
-
- @Override
- public Bytes getAddress() {
- return getID().getAddress();
- }
-
- @Override
- public PubKey getPubKey() {
- return getID().getPubKey();
- }
-
- @Override
- public PubKey getDataPubKey() {
- if (dataPubKey == null) {
- BytesValue pkBytes = getHeaders().getValue(DATA_PUB_KEY);
- if (pkBytes == null) {
- return null;
- }
- dataPubKey = new PubKey(pkBytes.getBytes().toBytes());
- }
- return dataPubKey;
- }
-
- public void setDataPubKey(PubKey pubKey) {
- long version = getHeaders().getVersion(DATA_PUB_KEY);
- setDataPubKey(pubKey, version);
- }
-
- public void setDataPubKey(PubKey pubKey, long version) {
- TypedValue value = TypedValue.fromPubKey(dataPubKey);
- long newVersion = getHeaders().setValue(DATA_PUB_KEY, value, version);
- if (newVersion > -1) {
- dataPubKey = pubKey;
- } else {
- throw new LedgerException("Data public key was updated failed!");
- }
- }
-
- public long setProperty(String key, String value, long version) {
- return getHeaders().setValue(encodePropertyKey(key), TypedValue.fromText(value), version);
- }
-
- public String getProperty(String key) {
- BytesValue value = getHeaders().getValue(encodePropertyKey(key));
- return value == null ? null : value.getBytes().toUTF8String();
- }
-
- public String getProperty(String key, long version) {
- BytesValue value = getHeaders().getValue(encodePropertyKey(key), version);
- return value == null ? null : value.getBytes().toUTF8String();
- }
-
- private String encodePropertyKey(String key) {
- return USER_INFO_PREFIX+key;
- }
-
-
+package com.jd.blockchain.ledger.core;
+
+import com.jd.blockchain.crypto.PubKey;
+import com.jd.blockchain.ledger.BytesValue;
+import com.jd.blockchain.ledger.LedgerException;
+import com.jd.blockchain.ledger.TypedValue;
+import com.jd.blockchain.ledger.UserInfo;
+import com.jd.blockchain.utils.Bytes;
+
+/**
+ * 用户账户;
+ *
+ * @author huanghaiquan
+ *
+ */
+public class UserAccount extends AccountDecorator implements UserInfo { // implements UserInfo {
+
+ private static final String USER_INFO_PREFIX = "PROP" + LedgerConsts.KEY_SEPERATOR;
+
+ private static final String DATA_PUB_KEY = "DATA-PUBKEY";
+
+ public UserAccount(CompositeAccount baseAccount) {
+ super(baseAccount);
+ }
+
+ private PubKey dataPubKey;
+
+
+ @Override
+ public Bytes getAddress() {
+ return getID().getAddress();
+ }
+
+ @Override
+ public PubKey getPubKey() {
+ return getID().getPubKey();
+ }
+
+ @Override
+ public PubKey getDataPubKey() {
+ if (dataPubKey == null) {
+ BytesValue pkBytes = getHeaders().getValue(DATA_PUB_KEY);
+ if (pkBytes == null) {
+ return null;
+ }
+ dataPubKey = new PubKey(pkBytes.getBytes().toBytes());
+ }
+ return dataPubKey;
+ }
+
+ public void setDataPubKey(PubKey pubKey) {
+ long version = getHeaders().getVersion(DATA_PUB_KEY);
+ setDataPubKey(pubKey, version);
+ }
+
+ public void setDataPubKey(PubKey pubKey, long version) {
+ TypedValue value = TypedValue.fromPubKey(dataPubKey);
+ long newVersion = getHeaders().setValue(DATA_PUB_KEY, value, version);
+ if (newVersion > -1) {
+ dataPubKey = pubKey;
+ } else {
+ throw new LedgerException("Data public key was updated failed!");
+ }
+ }
+
+ public long setProperty(String key, String value, long version) {
+ return getHeaders().setValue(encodePropertyKey(key), TypedValue.fromText(value), version);
+ }
+
+ public String getProperty(String key) {
+ BytesValue value = getHeaders().getValue(encodePropertyKey(key));
+ return value == null ? null : value.getBytes().toUTF8String();
+ }
+
+ public String getProperty(String key, long version) {
+ BytesValue value = getHeaders().getValue(encodePropertyKey(key), version);
+ return value == null ? null : value.getBytes().toUTF8String();
+ }
+
+ private String encodePropertyKey(String key) {
+ return USER_INFO_PREFIX+key;
+ }
+
+
}
\ No newline at end of file
diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserAccountSet.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserAccountSet.java
index bc71711d..25256480 100644
--- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserAccountSet.java
+++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserAccountSet.java
@@ -1,121 +1,121 @@
-package com.jd.blockchain.ledger.core;
-
-import com.jd.blockchain.crypto.HashDigest;
-import com.jd.blockchain.crypto.PubKey;
-import com.jd.blockchain.ledger.BlockchainIdentity;
-import com.jd.blockchain.ledger.CryptoSetting;
-import com.jd.blockchain.ledger.LedgerException;
-import com.jd.blockchain.ledger.MerkleProof;
-import com.jd.blockchain.storage.service.ExPolicyKVStorage;
-import com.jd.blockchain.storage.service.VersioningKVStorage;
-import com.jd.blockchain.utils.Bytes;
-import com.jd.blockchain.utils.Transactional;
-
-/**
- * @author huanghaiquan
- *
- */
-public class UserAccountSet implements Transactional, UserAccountQuery {
-
- private MerkleAccountSet accountSet;
-
- public UserAccountSet(CryptoSetting cryptoSetting, String keyPrefix, ExPolicyKVStorage simpleStorage,
- VersioningKVStorage versioningStorage, AccountAccessPolicy accessPolicy) {
- accountSet = new MerkleAccountSet(cryptoSetting, Bytes.fromString(keyPrefix), simpleStorage, versioningStorage,
- accessPolicy);
- }
-
- public UserAccountSet(HashDigest dataRootHash, CryptoSetting cryptoSetting, String keyPrefix,
- ExPolicyKVStorage exStorage, VersioningKVStorage verStorage, boolean readonly,
- AccountAccessPolicy accessPolicy) {
- accountSet = new MerkleAccountSet(dataRootHash, cryptoSetting, Bytes.fromString(keyPrefix), exStorage,
- verStorage, readonly, accessPolicy);
- }
-
- @Override
- public BlockchainIdentity[] getHeaders(int fromIndex, int count) {
- return accountSet.getHeaders(fromIndex, count);
- }
-
- /**
- * 返回用户总数;
- *
- * @return
- */
- @Override
- public long getTotal() {
- return accountSet.getTotal();
- }
-
- public boolean isReadonly() {
- return accountSet.isReadonly();
- }
-
- void setReadonly() {
- accountSet.setReadonly();
- }
-
- @Override
- public HashDigest getRootHash() {
- return accountSet.getRootHash();
- }
-
- @Override
- public MerkleProof getProof(Bytes key) {
- return accountSet.getProof(key);
- }
-
- @Override
- public UserAccount getAccount(String address) {
- return getAccount(Bytes.fromBase58(address));
- }
-
- @Override
- public UserAccount getAccount(Bytes address) {
- CompositeAccount baseAccount = accountSet.getAccount(address);
- return new UserAccount(baseAccount);
- }
-
- @Override
- public boolean contains(Bytes address) {
- return accountSet.contains(address);
- }
-
- @Override
- public UserAccount getAccount(Bytes address, long version) {
- CompositeAccount baseAccount = accountSet.getAccount(address, version);
- return new UserAccount(baseAccount);
- }
-
- /**
- * 注册一个新用户;
- *
- * 如果用户已经存在,则会引发 {@link LedgerException} 异常;
- *
- * 如果指定的地址和公钥不匹配,则会引发 {@link LedgerException} 异常;
- *
- * @param address 区块链地址;
- * @param pubKey 公钥;
- * @return 注册成功的用户对象;
- */
- public UserAccount register(Bytes address, PubKey pubKey) {
- CompositeAccount baseAccount = accountSet.register(address, pubKey);
- return new UserAccount(baseAccount);
- }
-
- @Override
- public boolean isUpdated() {
- return accountSet.isUpdated();
- }
-
- @Override
- public void commit() {
- accountSet.commit();
- }
-
- @Override
- public void cancel() {
- accountSet.cancel();
- }
-
+package com.jd.blockchain.ledger.core;
+
+import com.jd.blockchain.crypto.HashDigest;
+import com.jd.blockchain.crypto.PubKey;
+import com.jd.blockchain.ledger.BlockchainIdentity;
+import com.jd.blockchain.ledger.CryptoSetting;
+import com.jd.blockchain.ledger.LedgerException;
+import com.jd.blockchain.ledger.MerkleProof;
+import com.jd.blockchain.storage.service.ExPolicyKVStorage;
+import com.jd.blockchain.storage.service.VersioningKVStorage;
+import com.jd.blockchain.utils.Bytes;
+import com.jd.blockchain.utils.Transactional;
+
+/**
+ * @author huanghaiquan
+ *
+ */
+public class UserAccountSet implements Transactional, UserAccountQuery {
+
+ private MerkleAccountSet accountSet;
+
+ public UserAccountSet(CryptoSetting cryptoSetting, String keyPrefix, ExPolicyKVStorage simpleStorage,
+ VersioningKVStorage versioningStorage, AccountAccessPolicy accessPolicy) {
+ accountSet = new MerkleAccountSet(cryptoSetting, Bytes.fromString(keyPrefix), simpleStorage, versioningStorage,
+ accessPolicy);
+ }
+
+ public UserAccountSet(HashDigest dataRootHash, CryptoSetting cryptoSetting, String keyPrefix,
+ ExPolicyKVStorage exStorage, VersioningKVStorage verStorage, boolean readonly,
+ AccountAccessPolicy accessPolicy) {
+ accountSet = new MerkleAccountSet(dataRootHash, cryptoSetting, Bytes.fromString(keyPrefix), exStorage,
+ verStorage, readonly, accessPolicy);
+ }
+
+ @Override
+ public BlockchainIdentity[] getHeaders(int fromIndex, int count) {
+ return accountSet.getHeaders(fromIndex, count);
+ }
+
+ /**
+ * 返回用户总数;
+ *
+ * @return
+ */
+ @Override
+ public long getTotal() {
+ return accountSet.getTotal();
+ }
+
+ public boolean isReadonly() {
+ return accountSet.isReadonly();
+ }
+
+ void setReadonly() {
+ accountSet.setReadonly();
+ }
+
+ @Override
+ public HashDigest getRootHash() {
+ return accountSet.getRootHash();
+ }
+
+ @Override
+ public MerkleProof getProof(Bytes key) {
+ return accountSet.getProof(key);
+ }
+
+ @Override
+ public UserAccount getAccount(String address) {
+ return getAccount(Bytes.fromBase58(address));
+ }
+
+ @Override
+ public UserAccount getAccount(Bytes address) {
+ CompositeAccount baseAccount = accountSet.getAccount(address);
+ return new UserAccount(baseAccount);
+ }
+
+ @Override
+ public boolean contains(Bytes address) {
+ return accountSet.contains(address);
+ }
+
+ @Override
+ public UserAccount getAccount(Bytes address, long version) {
+ CompositeAccount baseAccount = accountSet.getAccount(address, version);
+ return new UserAccount(baseAccount);
+ }
+
+ /**
+ * 注册一个新用户;
+ *
+ * 如果用户已经存在,则会引发 {@link LedgerException} 异常;
+ *
+ * 如果指定的地址和公钥不匹配,则会引发 {@link LedgerException} 异常;
+ *
+ * @param address 区块链地址;
+ * @param pubKey 公钥;
+ * @return 注册成功的用户对象;
+ */
+ public UserAccount register(Bytes address, PubKey pubKey) {
+ CompositeAccount baseAccount = accountSet.register(address, pubKey);
+ return new UserAccount(baseAccount);
+ }
+
+ @Override
+ public boolean isUpdated() {
+ return accountSet.isUpdated();
+ }
+
+ @Override
+ public void commit() {
+ accountSet.commit();
+ }
+
+ @Override
+ public void cancel() {
+ accountSet.cancel();
+ }
+
}
\ No newline at end of file
diff --git a/source/ledger/ledger-model/pom.xml b/source/ledger/ledger-model/pom.xml
index 90b5a759..0a5a09eb 100644
--- a/source/ledger/ledger-model/pom.xml
+++ b/source/ledger/ledger-model/pom.xml
@@ -1,43 +1,43 @@
-
- 4.0.0
-
-
- com.jd.blockchain
- ledger
- 1.1.2.RELEASE
-
- ledger-model
-
-
-
-
- com.jd.blockchain
- utils-common
- ${project.version}
-
-
- com.jd.blockchain
- utils-web
- ${project.version}
-
-
-
- com.jd.blockchain
- binary-proto
- ${project.version}
-
-
- com.jd.blockchain
- crypto-framework
- ${project.version}
-
-
- com.jd.blockchain
- crypto-classic
- ${project.version}
-
-
-
+
+ 4.0.0
+
+
+ com.jd.blockchain
+ ledger
+ 1.1.2.RELEASE
+
+ ledger-model
+
+
+
+
+ com.jd.blockchain
+ utils-common
+ ${project.version}
+
+
+ com.jd.blockchain
+ utils-web
+ ${project.version}
+
+
+
+ com.jd.blockchain
+ binary-proto
+ ${project.version}
+
+
+ com.jd.blockchain
+ crypto-framework
+ ${project.version}
+
+
+ com.jd.blockchain
+ crypto-classic
+ ${project.version}
+
+
+
\ No newline at end of file
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/Contract.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/Contract.java
index e1b7ea4e..490c5782 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/Contract.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/Contract.java
@@ -1,14 +1,14 @@
-package com.jd.blockchain.contract;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-@Target({ ElementType.TYPE })
-@Retention(RetentionPolicy.RUNTIME)
-public @interface Contract {
-
- String name() default "";
-
-}
+package com.jd.blockchain.contract;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Target({ ElementType.TYPE })
+@Retention(RetentionPolicy.RUNTIME)
+public @interface Contract {
+
+ String name() default "";
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/ContractEvent.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/ContractEvent.java
index 6249945e..b6467b4f 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/ContractEvent.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/ContractEvent.java
@@ -1,14 +1,14 @@
-package com.jd.blockchain.contract;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-@Target({ ElementType.METHOD })
-@Retention(RetentionPolicy.RUNTIME)
-public @interface ContractEvent {
-
- String name() default "";
-
-}
+package com.jd.blockchain.contract;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Target({ ElementType.METHOD })
+@Retention(RetentionPolicy.RUNTIME)
+public @interface ContractEvent {
+
+ String name() default "";
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/EventHandle.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/EventHandle.java
index ac193ab9..37b419a2 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/EventHandle.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/contract/EventHandle.java
@@ -1,15 +1,15 @@
-package com.jd.blockchain.contract;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-
-@Target({ ElementType.METHOD })
-@Retention(RetentionPolicy.RUNTIME)
-public @interface EventHandle {
-
-
-
-}
+package com.jd.blockchain.contract;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+
+@Target({ ElementType.METHOD })
+@Retention(RetentionPolicy.RUNTIME)
+public @interface EventHandle {
+
+
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockRollbackException.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockRollbackException.java
index c64f9e42..8eb6c2ee 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockRollbackException.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockRollbackException.java
@@ -1,33 +1,33 @@
-package com.jd.blockchain.ledger;
-
-public class BlockRollbackException extends LedgerException {
-
- private static final long serialVersionUID = 3583192000738807503L;
-
- private TransactionState state;
-
- public BlockRollbackException(String message) {
- this(TransactionState.SYSTEM_ERROR, message);
- }
-
- public BlockRollbackException(TransactionState state, String message) {
- super(message);
- assert TransactionState.SUCCESS != state;
- this.state = state;
- }
-
- public BlockRollbackException(String message, Throwable cause) {
- this(TransactionState.SYSTEM_ERROR, message, cause);
- }
-
- public BlockRollbackException(TransactionState state, String message, Throwable cause) {
- super(message, cause);
- assert TransactionState.SUCCESS != state;
- this.state = state;
- }
-
- public TransactionState getState() {
- return state;
- }
-
-}
+package com.jd.blockchain.ledger;
+
+public class BlockRollbackException extends LedgerException {
+
+ private static final long serialVersionUID = 3583192000738807503L;
+
+ private TransactionState state;
+
+ public BlockRollbackException(String message) {
+ this(TransactionState.SYSTEM_ERROR, message);
+ }
+
+ public BlockRollbackException(TransactionState state, String message) {
+ super(message);
+ assert TransactionState.SUCCESS != state;
+ this.state = state;
+ }
+
+ public BlockRollbackException(String message, Throwable cause) {
+ this(TransactionState.SYSTEM_ERROR, message, cause);
+ }
+
+ public BlockRollbackException(TransactionState state, String message, Throwable cause) {
+ super(message, cause);
+ assert TransactionState.SUCCESS != state;
+ this.state = state;
+ }
+
+ public TransactionState getState() {
+ return state;
+ }
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainEventType.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainEventType.java
index aa7449a0..5e05c545 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainEventType.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainEventType.java
@@ -1,83 +1,83 @@
-package com.jd.blockchain.ledger;
-
-/**
- * 区块链事件类型;
- *
- * 每一种事件类型都包含一个事件码;
- *
- * 在一次事件消息中,可以包含多种事件,而且事件之间具有嵌套关系;
- *
- * 例如:
- *
- * 一个区块生成事件 {@link #BLOCK_GENERATED} 含了交易提交事件
- * {@link #TRANSACTION_COMMITED};
- *
- * 交易提交事件 {@link #TRANSACTION_COMMITED} 必然包含账户更新事件 {@link #ACCOUNT_UPDATED};
- *
- * 更进一步,账户更新事件 {@link #ACCOUNT_UPDATED} 也必然包含了权限更新事件
- * {@link #PRIVILEGE_UPDATED}、负载数据更新事件 {@link #PAYLOAD_UPDATED}
- * 、合约脚本更新事件{@link #SCRIPT_UPDATED} 、合约脚本执行事件{@link #SCRIPT_INVOKED} 这4种事件中的一种或者多种事件;
- *
- * 这种嵌套关系,表现在事件的编码中是子事件码的比特位中包含了上级事件码;
- *
- * @author huanghaiquan
- *
- */
-public enum BlockchainEventType {
-
- /**
- * 生成新区块;
- *
- * 事件码:1 (0x01)
- *
- */
- BLOCK_GENERATED(1),
-
- /**
- * 成功提交新交易;
- *
- * 事件码:3 (0x03)
- */
- TRANSACTION_COMMITED(3),
-
- /**
- * 账户的版本已更新;
- *
- * 事件码:259 (0x103)
- */
- ACCOUNT_UPDATED(259),
-
- /**
- * 账户权限已被更新;
- *
- * 事件码:65795 (0x10103)
- */
- PRIVILEGE_UPDATED(65795),
-
- /**
- * 账户负载数据已被更新;
- *
- * 事件码:131331 (0x20103)
- */
- PAYLOAD_UPDATED(131331),
-
- /**
- * 合约脚本已被更新;
- *
- * 事件码:262403 (0x40103)
- */
- SCRIPT_UPDATED(262403),
-
- /**
- * 合约脚本已被调用;
- *
- * 事件码:524547 (0x80103)
- */
- SCRIPT_INVOKED(524547);
-
- public final int CODE;
-
- private BlockchainEventType(int code) {
- this.CODE = code;
- }
-}
+package com.jd.blockchain.ledger;
+
+/**
+ * 区块链事件类型;
+ *
+ * 每一种事件类型都包含一个事件码;
+ *
+ * 在一次事件消息中,可以包含多种事件,而且事件之间具有嵌套关系;
+ *
+ * 例如:
+ *
+ * 一个区块生成事件 {@link #BLOCK_GENERATED} 含了交易提交事件
+ * {@link #TRANSACTION_COMMITED};
+ *
+ * 交易提交事件 {@link #TRANSACTION_COMMITED} 必然包含账户更新事件 {@link #ACCOUNT_UPDATED};
+ *
+ * 更进一步,账户更新事件 {@link #ACCOUNT_UPDATED} 也必然包含了权限更新事件
+ * {@link #PRIVILEGE_UPDATED}、负载数据更新事件 {@link #PAYLOAD_UPDATED}
+ * 、合约脚本更新事件{@link #SCRIPT_UPDATED} 、合约脚本执行事件{@link #SCRIPT_INVOKED} 这4种事件中的一种或者多种事件;
+ *
+ * 这种嵌套关系,表现在事件的编码中是子事件码的比特位中包含了上级事件码;
+ *
+ * @author huanghaiquan
+ *
+ */
+public enum BlockchainEventType {
+
+ /**
+ * 生成新区块;
+ *
+ * 事件码:1 (0x01)
+ *
+ */
+ BLOCK_GENERATED(1),
+
+ /**
+ * 成功提交新交易;
+ *
+ * 事件码:3 (0x03)
+ */
+ TRANSACTION_COMMITED(3),
+
+ /**
+ * 账户的版本已更新;
+ *
+ * 事件码:259 (0x103)
+ */
+ ACCOUNT_UPDATED(259),
+
+ /**
+ * 账户权限已被更新;
+ *
+ * 事件码:65795 (0x10103)
+ */
+ PRIVILEGE_UPDATED(65795),
+
+ /**
+ * 账户负载数据已被更新;
+ *
+ * 事件码:131331 (0x20103)
+ */
+ PAYLOAD_UPDATED(131331),
+
+ /**
+ * 合约脚本已被更新;
+ *
+ * 事件码:262403 (0x40103)
+ */
+ SCRIPT_UPDATED(262403),
+
+ /**
+ * 合约脚本已被调用;
+ *
+ * 事件码:524547 (0x80103)
+ */
+ SCRIPT_INVOKED(524547);
+
+ public final int CODE;
+
+ private BlockchainEventType(int code) {
+ this.CODE = code;
+ }
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainIdentityData.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainIdentityData.java
index 19e3522a..50a1d996 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainIdentityData.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainIdentityData.java
@@ -1,216 +1,216 @@
-package com.jd.blockchain.ledger;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.Externalizable;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-import com.jd.blockchain.crypto.AddressEncoding;
-import com.jd.blockchain.crypto.CryptoAlgorithm;
-import com.jd.blockchain.crypto.PubKey;
-import com.jd.blockchain.utils.Bytes;
-import com.jd.blockchain.utils.io.ByteArray;
-import com.jd.blockchain.utils.io.BytesEncoding;
-import com.jd.blockchain.utils.io.BytesReader;
-import com.jd.blockchain.utils.io.BytesUtils;
-import com.jd.blockchain.utils.io.BytesWriter;
-import com.jd.blockchain.utils.io.RuntimeIOException;
-
-/**
- * 区块链身份;
- *
- * @author huanghaiquan
- *
- */
-public class BlockchainIdentityData implements BytesWriter, BytesReader, Externalizable, BlockchainIdentity {
-
- private Bytes address;
-
- private PubKey pubKey;
-
- private BlockchainIdentityData() {
- }
-
- public BlockchainIdentityData(PubKey pubKey) {
- this.pubKey = pubKey;
- this.address = AddressEncoding.generateAddress(pubKey);
- }
-
- public BlockchainIdentityData(CryptoAlgorithm algorithm, ByteArray pubKeyBytes) {
- this.pubKey = new PubKey(algorithm, pubKeyBytes.bytes());
- this.address = AddressEncoding.generateAddress(pubKey);
- }
-
- public BlockchainIdentityData(Bytes address, PubKey pubKey) {
- if (!verifyAddress(address, pubKey)) {
- throw new IllegalArgumentException("Blockchain address is mismatch with the pub-key!");
- }
- this.address = address;
- this.pubKey = pubKey;
- }
-
- public static boolean verifyAddress(Bytes address, PubKey pubKey) {
- Bytes addr = AddressEncoding.generateAddress(pubKey);
- return addr.equals(address);
- }
-
- @Override
- public void resolvFrom(InputStream in) throws IOException {
- Bytes addr = AddressEncoding.readAddress(in);
- byte[] value = BytesEncoding.readInShort(in);
- PubKey pk = new PubKey(value);
- this.address = addr;
- this.pubKey = pk;
- }
-
- @Override
- public void writeTo(OutputStream out) throws IOException {
- AddressEncoding.writeAddress(address, out);
- BytesEncoding.writeInShort(pubKey.toBytes(), out);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see com.jd.blockchain.ledger.BlockchainIdentity#getAddress()
- */
- @Override
- public Bytes getAddress() {
- return address;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see com.jd.blockchain.ledger.BlockchainIdentity#getPubKey()
- */
- @Override
- public PubKey getPubKey() {
- return pubKey;
- }
-
- public static BlockchainIdentity resolveFrom(ByteArray bytes) {
- try {
- BlockchainIdentityData id = new BlockchainIdentityData();
- id.resolvFrom(bytes.asInputStream());
- return id;
- } catch (IOException e) {
- throw new RuntimeIOException(e.getMessage(), e);
- }
- }
-
- public static ByteArray toBytes(List identities) {
- try {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- BytesUtils.writeInt(identities.size(), out);
- for (BlockchainIdentityData identity : identities) {
- identity.writeTo(out);
- }
-
- return ByteArray.wrap(out.toByteArray());
- } catch (IOException e) {
- throw new RuntimeIOException(e.getMessage(), e);
- }
- }
-
- public static List resolveIdentitiesFrom(ByteArray bytes) {
- try {
- InputStream in = bytes.asInputStream();
- int identitiesLen = BytesUtils.readInt(in);
- List identities = new ArrayList<>();
- for (int i = 0; i < identitiesLen; i++) {
- BlockchainIdentityData id = new BlockchainIdentityData();
- id.resolvFrom(in);
-
- identities.add(id);
- }
-
- return identities;
- } catch (IOException e) {
- throw new RuntimeIOException(e.getMessage(), e);
- }
- }
-
- public ByteArray toBytes() {
- try {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- writeTo(out);
- return ByteArray.wrap(out.toByteArray());
- } catch (IOException e) {
- throw new RuntimeIOException(e.getMessage(), e);
- }
- }
-
- @Override
- public int hashCode() {
- return address.hashCode();
- }
-
- @Override
- public boolean equals(Object other) {
- if (this == other) {
- return true;
- }
- if (!(other instanceof BlockchainIdentityData)) {
- return false;
- }
-
- BlockchainIdentity identity = (BlockchainIdentity) other;
-
- if (!getAddress().equals(identity.getAddress())) {
- return false;
- }
- return pubKey.equals(identity.getPubKey());
- }
-
- /**
- * The object implements the writeExternal method to save its contents by
- * calling the methods of DataOutput for its primitive values or calling the
- * writeObject method of ObjectOutput for objects, strings, and arrays.
- *
- * @param out
- * the stream to write the object to
- * @throws IOException
- * Includes any I/O exceptions that may occur
- * @serialData Overriding methods should use this tag to describe the data
- * layout of this Externalizable object. List the sequence of
- * element types and, if possible, relate the element to a
- * public/protected field and/or method of this Externalizable
- * class.
- */
- @Override
- public void writeExternal(ObjectOutput out) throws IOException {
- ByteArrayOutputStream os = new ByteArrayOutputStream();
- writeTo(os);
- byte[] bts = os.toByteArray();
- out.writeInt(bts.length);
- out.write(bts);
- }
-
- /**
- * The object implements the readExternal method to restore its contents by
- * calling the methods of DataInput for primitive types and readObject for
- * objects, strings and arrays. The readExternal method must read the values in
- * the same sequence and with the same types as were written by writeExternal.
- *
- * @param in
- * the stream to read data from in order to restore the object
- * @throws IOException
- * if I/O errors occur
- * @throws ClassNotFoundException
- * If the class for an object being restored cannot be found.
- */
- @Override
- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
- int len = in.readInt();
- byte[] bts = new byte[len];
- in.readFully(bts);
- this.resolvFrom(new ByteArrayInputStream(bts));
- }
-}
+package com.jd.blockchain.ledger;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import com.jd.blockchain.crypto.AddressEncoding;
+import com.jd.blockchain.crypto.CryptoAlgorithm;
+import com.jd.blockchain.crypto.PubKey;
+import com.jd.blockchain.utils.Bytes;
+import com.jd.blockchain.utils.io.ByteArray;
+import com.jd.blockchain.utils.io.BytesEncoding;
+import com.jd.blockchain.utils.io.BytesReader;
+import com.jd.blockchain.utils.io.BytesUtils;
+import com.jd.blockchain.utils.io.BytesWriter;
+import com.jd.blockchain.utils.io.RuntimeIOException;
+
+/**
+ * 区块链身份;
+ *
+ * @author huanghaiquan
+ *
+ */
+public class BlockchainIdentityData implements BytesWriter, BytesReader, Externalizable, BlockchainIdentity {
+
+ private Bytes address;
+
+ private PubKey pubKey;
+
+ private BlockchainIdentityData() {
+ }
+
+ public BlockchainIdentityData(PubKey pubKey) {
+ this.pubKey = pubKey;
+ this.address = AddressEncoding.generateAddress(pubKey);
+ }
+
+ public BlockchainIdentityData(CryptoAlgorithm algorithm, ByteArray pubKeyBytes) {
+ this.pubKey = new PubKey(algorithm, pubKeyBytes.bytes());
+ this.address = AddressEncoding.generateAddress(pubKey);
+ }
+
+ public BlockchainIdentityData(Bytes address, PubKey pubKey) {
+ if (!verifyAddress(address, pubKey)) {
+ throw new IllegalArgumentException("Blockchain address is mismatch with the pub-key!");
+ }
+ this.address = address;
+ this.pubKey = pubKey;
+ }
+
+ public static boolean verifyAddress(Bytes address, PubKey pubKey) {
+ Bytes addr = AddressEncoding.generateAddress(pubKey);
+ return addr.equals(address);
+ }
+
+ @Override
+ public void resolvFrom(InputStream in) throws IOException {
+ Bytes addr = AddressEncoding.readAddress(in);
+ byte[] value = BytesEncoding.readInShort(in);
+ PubKey pk = new PubKey(value);
+ this.address = addr;
+ this.pubKey = pk;
+ }
+
+ @Override
+ public void writeTo(OutputStream out) throws IOException {
+ AddressEncoding.writeAddress(address, out);
+ BytesEncoding.writeInShort(pubKey.toBytes(), out);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.jd.blockchain.ledger.BlockchainIdentity#getAddress()
+ */
+ @Override
+ public Bytes getAddress() {
+ return address;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see com.jd.blockchain.ledger.BlockchainIdentity#getPubKey()
+ */
+ @Override
+ public PubKey getPubKey() {
+ return pubKey;
+ }
+
+ public static BlockchainIdentity resolveFrom(ByteArray bytes) {
+ try {
+ BlockchainIdentityData id = new BlockchainIdentityData();
+ id.resolvFrom(bytes.asInputStream());
+ return id;
+ } catch (IOException e) {
+ throw new RuntimeIOException(e.getMessage(), e);
+ }
+ }
+
+ public static ByteArray toBytes(List identities) {
+ try {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ BytesUtils.writeInt(identities.size(), out);
+ for (BlockchainIdentityData identity : identities) {
+ identity.writeTo(out);
+ }
+
+ return ByteArray.wrap(out.toByteArray());
+ } catch (IOException e) {
+ throw new RuntimeIOException(e.getMessage(), e);
+ }
+ }
+
+ public static List resolveIdentitiesFrom(ByteArray bytes) {
+ try {
+ InputStream in = bytes.asInputStream();
+ int identitiesLen = BytesUtils.readInt(in);
+ List identities = new ArrayList<>();
+ for (int i = 0; i < identitiesLen; i++) {
+ BlockchainIdentityData id = new BlockchainIdentityData();
+ id.resolvFrom(in);
+
+ identities.add(id);
+ }
+
+ return identities;
+ } catch (IOException e) {
+ throw new RuntimeIOException(e.getMessage(), e);
+ }
+ }
+
+ public ByteArray toBytes() {
+ try {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ writeTo(out);
+ return ByteArray.wrap(out.toByteArray());
+ } catch (IOException e) {
+ throw new RuntimeIOException(e.getMessage(), e);
+ }
+ }
+
+ @Override
+ public int hashCode() {
+ return address.hashCode();
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (this == other) {
+ return true;
+ }
+ if (!(other instanceof BlockchainIdentityData)) {
+ return false;
+ }
+
+ BlockchainIdentity identity = (BlockchainIdentity) other;
+
+ if (!getAddress().equals(identity.getAddress())) {
+ return false;
+ }
+ return pubKey.equals(identity.getPubKey());
+ }
+
+ /**
+ * The object implements the writeExternal method to save its contents by
+ * calling the methods of DataOutput for its primitive values or calling the
+ * writeObject method of ObjectOutput for objects, strings, and arrays.
+ *
+ * @param out
+ * the stream to write the object to
+ * @throws IOException
+ * Includes any I/O exceptions that may occur
+ * @serialData Overriding methods should use this tag to describe the data
+ * layout of this Externalizable object. List the sequence of
+ * element types and, if possible, relate the element to a
+ * public/protected field and/or method of this Externalizable
+ * class.
+ */
+ @Override
+ public void writeExternal(ObjectOutput out) throws IOException {
+ ByteArrayOutputStream os = new ByteArrayOutputStream();
+ writeTo(os);
+ byte[] bts = os.toByteArray();
+ out.writeInt(bts.length);
+ out.write(bts);
+ }
+
+ /**
+ * The object implements the readExternal method to restore its contents by
+ * calling the methods of DataInput for primitive types and readObject for
+ * objects, strings and arrays. The readExternal method must read the values in
+ * the same sequence and with the same types as were written by writeExternal.
+ *
+ * @param in
+ * the stream to read data from in order to restore the object
+ * @throws IOException
+ * if I/O errors occur
+ * @throws ClassNotFoundException
+ * If the class for an object being restored cannot be found.
+ */
+ @Override
+ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
+ int len = in.readInt();
+ byte[] bts = new byte[len];
+ in.readFully(bts);
+ this.resolvFrom(new ByteArrayInputStream(bts));
+ }
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainKeyGenerator.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainKeyGenerator.java
index 6d751f87..0c1ce1aa 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainKeyGenerator.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainKeyGenerator.java
@@ -1,40 +1,40 @@
-package com.jd.blockchain.ledger;
-
-import com.jd.blockchain.crypto.CryptoAlgorithm;
-import com.jd.blockchain.crypto.AsymmetricKeypair;
-import com.jd.blockchain.crypto.Crypto;
-import com.jd.blockchain.crypto.SignatureFunction;
-
-/**
- * 区块链密钥生成器;
- *
- * @author huanghaiquan
- *
- */
-public class BlockchainKeyGenerator {
-
- public static final String DEFAULT_ALGORITHM = "ED25519";
-
- private BlockchainKeyGenerator() {
- }
-
- public static BlockchainKeyGenerator getInstance() {
- return new BlockchainKeyGenerator();
- }
-
- public BlockchainKeypair generate() {
- return generate(DEFAULT_ALGORITHM);
- }
-
- public BlockchainKeypair generate(String algorithmName) {
- CryptoAlgorithm algorithm = Crypto.getAlgorithm(algorithmName);
- return generate(algorithm);
- }
-
- public BlockchainKeypair generate(CryptoAlgorithm signatureAlgorithm) {
- SignatureFunction signFunc = Crypto.getSignatureFunction(signatureAlgorithm);
- AsymmetricKeypair cryptoKeyPair = signFunc.generateKeypair();
- return new BlockchainKeypair(cryptoKeyPair.getPubKey(), cryptoKeyPair.getPrivKey());
- }
-
-}
+package com.jd.blockchain.ledger;
+
+import com.jd.blockchain.crypto.CryptoAlgorithm;
+import com.jd.blockchain.crypto.AsymmetricKeypair;
+import com.jd.blockchain.crypto.Crypto;
+import com.jd.blockchain.crypto.SignatureFunction;
+
+/**
+ * 区块链密钥生成器;
+ *
+ * @author huanghaiquan
+ *
+ */
+public class BlockchainKeyGenerator {
+
+ public static final String DEFAULT_ALGORITHM = "ED25519";
+
+ private BlockchainKeyGenerator() {
+ }
+
+ public static BlockchainKeyGenerator getInstance() {
+ return new BlockchainKeyGenerator();
+ }
+
+ public BlockchainKeypair generate() {
+ return generate(DEFAULT_ALGORITHM);
+ }
+
+ public BlockchainKeypair generate(String algorithmName) {
+ CryptoAlgorithm algorithm = Crypto.getAlgorithm(algorithmName);
+ return generate(algorithm);
+ }
+
+ public BlockchainKeypair generate(CryptoAlgorithm signatureAlgorithm) {
+ SignatureFunction signFunc = Crypto.getSignatureFunction(signatureAlgorithm);
+ AsymmetricKeypair cryptoKeyPair = signFunc.generateKeypair();
+ return new BlockchainKeypair(cryptoKeyPair.getPubKey(), cryptoKeyPair.getPrivKey());
+ }
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainKeypair.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainKeypair.java
index 00001591..269c9eba 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainKeypair.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/BlockchainKeypair.java
@@ -1,46 +1,46 @@
-package com.jd.blockchain.ledger;
-
-import com.jd.blockchain.crypto.AsymmetricKeypair;
-import com.jd.blockchain.crypto.PrivKey;
-import com.jd.blockchain.crypto.PubKey;
-import com.jd.blockchain.utils.Bytes;
-
-/**
- * 区块链密钥对;
- *
- * @author huanghaiquan
- *
- */
-public class BlockchainKeypair extends AsymmetricKeypair {
-
- private BlockchainIdentity id;
-
-// public BlockchainKeyPair(CryptoAlgorithm algorithm, ByteArray pubKeyBytes, ByteArray privKeyBytes) {
-// this.id = new BlockchainIdentity(algorithm, pubKeyBytes);
-// privKey = new PrivKey(algorithm, privKeyBytes.bytes());
-// }
-
- public BlockchainKeypair(String address, PubKey pubKey, PrivKey privKey) {
- super(pubKey, privKey);
- if (pubKey.getAlgorithm() != privKey.getAlgorithm()) {
- throw new IllegalArgumentException("The PublicKey's algorithm is different from the PrivateKey's!");
- }
- this.id = new BlockchainIdentityData(Bytes.fromBase58(address), pubKey);
- }
-
- public BlockchainKeypair(PubKey pubKey, PrivKey privKey) {
- super(pubKey, privKey);
- if (pubKey.getAlgorithm() != privKey.getAlgorithm()) {
- throw new IllegalArgumentException("The PublicKey's algorithm is different from the PrivateKey's!");
- }
- this.id = new BlockchainIdentityData(pubKey);
- }
-
- public Bytes getAddress() {
- return id.getAddress();
- }
-
- public BlockchainIdentity getIdentity() {
- return id;
- }
-}
+package com.jd.blockchain.ledger;
+
+import com.jd.blockchain.crypto.AsymmetricKeypair;
+import com.jd.blockchain.crypto.PrivKey;
+import com.jd.blockchain.crypto.PubKey;
+import com.jd.blockchain.utils.Bytes;
+
+/**
+ * 区块链密钥对;
+ *
+ * @author huanghaiquan
+ *
+ */
+public class BlockchainKeypair extends AsymmetricKeypair {
+
+ private BlockchainIdentity id;
+
+// public BlockchainKeyPair(CryptoAlgorithm algorithm, ByteArray pubKeyBytes, ByteArray privKeyBytes) {
+// this.id = new BlockchainIdentity(algorithm, pubKeyBytes);
+// privKey = new PrivKey(algorithm, privKeyBytes.bytes());
+// }
+
+ public BlockchainKeypair(String address, PubKey pubKey, PrivKey privKey) {
+ super(pubKey, privKey);
+ if (pubKey.getAlgorithm() != privKey.getAlgorithm()) {
+ throw new IllegalArgumentException("The PublicKey's algorithm is different from the PrivateKey's!");
+ }
+ this.id = new BlockchainIdentityData(Bytes.fromBase58(address), pubKey);
+ }
+
+ public BlockchainKeypair(PubKey pubKey, PrivKey privKey) {
+ super(pubKey, privKey);
+ if (pubKey.getAlgorithm() != privKey.getAlgorithm()) {
+ throw new IllegalArgumentException("The PublicKey's algorithm is different from the PrivateKey's!");
+ }
+ this.id = new BlockchainIdentityData(pubKey);
+ }
+
+ public Bytes getAddress() {
+ return id.getAddress();
+ }
+
+ public BlockchainIdentity getIdentity() {
+ return id;
+ }
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/CodeDeployOperation.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/CodeDeployOperation.java
index 2816b952..1e902c21 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/CodeDeployOperation.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/CodeDeployOperation.java
@@ -1,23 +1,23 @@
-//package com.jd.blockchain.ledger;
-//
-//import com.jd.blockchain.ledger.data.AccountUpdateOperationBuilder;
-//
-///**
-// * 合约代码部署操作;
-// *
-// * @author huanghaiquan
-// *
-// */
-//public interface CodeDeployOperation extends AccountUpdateOperationBuilder {
-//
-// /**
-// * 修改脚本;
-// *
-// * @param code
-// * 合约代码;
-// * @param codeVersion
-// * 预期的当前的代码的版本;如果指定为 -1,则不进行版本检查;
-// */
-// void set(BlockchainIdentity id, String code, long codeVersion);
-//
-//}
+//package com.jd.blockchain.ledger;
+//
+//import com.jd.blockchain.ledger.data.AccountUpdateOperationBuilder;
+//
+///**
+// * 合约代码部署操作;
+// *
+// * @author huanghaiquan
+// *
+// */
+//public interface CodeDeployOperation extends AccountUpdateOperationBuilder {
+//
+// /**
+// * 修改脚本;
+// *
+// * @param code
+// * 合约代码;
+// * @param codeVersion
+// * 预期的当前的代码的版本;如果指定为 -1,则不进行版本检查;
+// */
+// void set(BlockchainIdentity id, String code, long codeVersion);
+//
+//}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ContractCodeDeployOperation.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ContractCodeDeployOperation.java
index 48190979..bc27beef 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ContractCodeDeployOperation.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ContractCodeDeployOperation.java
@@ -1,31 +1,31 @@
-package com.jd.blockchain.ledger;
-
-import com.jd.blockchain.binaryproto.DataContract;
-import com.jd.blockchain.binaryproto.DataField;
-import com.jd.blockchain.binaryproto.PrimitiveType;
-import com.jd.blockchain.consts.DataCodes;
-
-@DataContract(code= DataCodes.TX_OP_CONTRACT_DEPLOY)
-public interface ContractCodeDeployOperation extends Operation {
-
- @DataField(order=2, refContract = true)
- BlockchainIdentity getContractID();
-
- @DataField(order=3, primitiveType=PrimitiveType.BYTES)
- byte[] getChainCode();
-
-
- /**
- * 地址签名;
- *
- *
- * 这是合约账户身份 ({@link #getContractID()}) 使用对应的私钥对地址做出的签名;
- *
- * 在注册时将校验此签名与账户地址、公钥是否相匹配,以此保证只有私钥的持有者才能注册相应的合约账户,确保合约账户的唯一性;
- *
- * @return
- */
- @DataField(order=4, refContract = true)
- DigitalSignature getAddressSignature();
-
-}
+package com.jd.blockchain.ledger;
+
+import com.jd.blockchain.binaryproto.DataContract;
+import com.jd.blockchain.binaryproto.DataField;
+import com.jd.blockchain.binaryproto.PrimitiveType;
+import com.jd.blockchain.consts.DataCodes;
+
+@DataContract(code= DataCodes.TX_OP_CONTRACT_DEPLOY)
+public interface ContractCodeDeployOperation extends Operation {
+
+ @DataField(order=2, refContract = true)
+ BlockchainIdentity getContractID();
+
+ @DataField(order=3, primitiveType=PrimitiveType.BYTES)
+ byte[] getChainCode();
+
+
+ /**
+ * 地址签名;
+ *
+ *
+ * 这是合约账户身份 ({@link #getContractID()}) 使用对应的私钥对地址做出的签名;
+ *
+ * 在注册时将校验此签名与账户地址、公钥是否相匹配,以此保证只有私钥的持有者才能注册相应的合约账户,确保合约账户的唯一性;
+ *
+ * @return
+ */
+ @DataField(order=4, refContract = true)
+ DigitalSignature getAddressSignature();
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataAccountKVSetOperation.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataAccountKVSetOperation.java
index c83cea9a..8c5d115b 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataAccountKVSetOperation.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataAccountKVSetOperation.java
@@ -1,32 +1,32 @@
-package com.jd.blockchain.ledger;
-
-import com.jd.blockchain.binaryproto.DataContract;
-import com.jd.blockchain.binaryproto.DataField;
-import com.jd.blockchain.binaryproto.PrimitiveType;
-import com.jd.blockchain.consts.DataCodes;
-import com.jd.blockchain.utils.Bytes;
-
-@DataContract(code= DataCodes.TX_OP_DATA_ACC_SET)
-public interface DataAccountKVSetOperation extends Operation {
-
- @DataField(order=2, primitiveType=PrimitiveType.BYTES)
- Bytes getAccountAddress();
-
- @DataField(order=3, list=true, refContract=true)
- KVWriteEntry[] getWriteSet();
-
-
- @DataContract(code=DataCodes.TX_OP_DATA_ACC_SET_KV)
- public static interface KVWriteEntry{
-
- @DataField(order=1, primitiveType=PrimitiveType.TEXT)
- String getKey();
-
- @DataField(order=2, refContract = true)
- BytesValue getValue();
-
- @DataField(order=3, primitiveType=PrimitiveType.INT64)
- long getExpectedVersion();
- }
-
-}
+package com.jd.blockchain.ledger;
+
+import com.jd.blockchain.binaryproto.DataContract;
+import com.jd.blockchain.binaryproto.DataField;
+import com.jd.blockchain.binaryproto.PrimitiveType;
+import com.jd.blockchain.consts.DataCodes;
+import com.jd.blockchain.utils.Bytes;
+
+@DataContract(code= DataCodes.TX_OP_DATA_ACC_SET)
+public interface DataAccountKVSetOperation extends Operation {
+
+ @DataField(order=2, primitiveType=PrimitiveType.BYTES)
+ Bytes getAccountAddress();
+
+ @DataField(order=3, list=true, refContract=true)
+ KVWriteEntry[] getWriteSet();
+
+
+ @DataContract(code=DataCodes.TX_OP_DATA_ACC_SET_KV)
+ public static interface KVWriteEntry{
+
+ @DataField(order=1, primitiveType=PrimitiveType.TEXT)
+ String getKey();
+
+ @DataField(order=2, refContract = true)
+ BytesValue getValue();
+
+ @DataField(order=3, primitiveType=PrimitiveType.INT64)
+ long getExpectedVersion();
+ }
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataAccountRegisterOperation.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataAccountRegisterOperation.java
index f75621f7..a923494c 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataAccountRegisterOperation.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataAccountRegisterOperation.java
@@ -1,26 +1,26 @@
-package com.jd.blockchain.ledger;
-
-import com.jd.blockchain.binaryproto.DataContract;
-import com.jd.blockchain.binaryproto.DataField;
-import com.jd.blockchain.consts.DataCodes;
-
-@DataContract(code= DataCodes.TX_OP_DATA_ACC_REG)
-public interface DataAccountRegisterOperation extends Operation {
-
- @DataField(order=1, refContract = true)
- BlockchainIdentity getAccountID();
-
- /**
- * 地址签名;
- *
- *
- * 这是账户身份 ({@link #getAccountID()}) 使用对应的私钥对地址做出的签名;
- *
- * 在注册时将校验此签名与账户地址、公钥是否相匹配,以此保证只有私钥的持有者才能注册数据账户,确保数据账户的唯一性;
- *
- * @return
- */
- @DataField(order=2, refContract = true)
- DigitalSignature getAddressSignature();
-
-}
+package com.jd.blockchain.ledger;
+
+import com.jd.blockchain.binaryproto.DataContract;
+import com.jd.blockchain.binaryproto.DataField;
+import com.jd.blockchain.consts.DataCodes;
+
+@DataContract(code= DataCodes.TX_OP_DATA_ACC_REG)
+public interface DataAccountRegisterOperation extends Operation {
+
+ @DataField(order=1, refContract = true)
+ BlockchainIdentity getAccountID();
+
+ /**
+ * 地址签名;
+ *
+ *
+ * 这是账户身份 ({@link #getAccountID()}) 使用对应的私钥对地址做出的签名;
+ *
+ * 在注册时将校验此签名与账户地址、公钥是否相匹配,以此保证只有私钥的持有者才能注册数据账户,确保数据账户的唯一性;
+ *
+ * @return
+ */
+ @DataField(order=2, refContract = true)
+ DigitalSignature getAddressSignature();
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataType.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataType.java
index 6395bcc2..2d5cda55 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataType.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataType.java
@@ -1,185 +1,185 @@
-package com.jd.blockchain.ledger;
-
-import com.jd.blockchain.binaryproto.BaseType;
-import com.jd.blockchain.binaryproto.EnumContract;
-import com.jd.blockchain.binaryproto.EnumField;
-import com.jd.blockchain.binaryproto.PrimitiveType;
-import com.jd.blockchain.consts.DataCodes;
-
-/**
- * 键值操作的数据类型;
- *
- * @author huanghaiquan
- *
- */
-@EnumContract(code = DataCodes.ENUM_TYPE_BYTES_VALUE_TYPE)
-public enum DataType {
-
- /**
- * 空;
- */
- NIL(PrimitiveType.NIL.CODE),
-
- /**
- * 布尔型;
- */
- BOOLEAN(PrimitiveType.BOOLEAN.CODE),
-
- /**
- * 数值型:
- */
-
- INT8(PrimitiveType.INT8.CODE),
-
- INT16(PrimitiveType.INT16.CODE),
-
- INT32(PrimitiveType.INT32.CODE),
-
- INT64(PrimitiveType.INT64.CODE),
-
- /**
- * 文本数据;
- */
- TEXT(PrimitiveType.TEXT.CODE),
-
- /**
- * 二进制数据;
- */
- BYTES(PrimitiveType.BYTES.CODE),
-
- /**
- * 时间戳;
- */
- TIMESTAMP((byte) (BaseType.INTEGER | 0x08)),
-
- /**
- * 文本数据;
- */
- JSON((byte) (BaseType.TEXT | 0x01)),
-
- /**
- * 文本数据;
- */
- XML((byte) (BaseType.TEXT | 0x02)),
-
- /**
- * 大整数;
- */
- BIG_INT((byte) (BaseType.BYTES | 0x01)),
-
- /**
- * 图片;
- */
- IMG((byte) (BaseType.BYTES | 0x02)),
-
- /**
- * 视频;
- */
- VIDEO((byte) (BaseType.BYTES | 0x03)),
-
- /**
- * 位置坐标;
- */
- LOCATION((byte) (BaseType.BYTES | 0x04)),
-
- /**
- * 公钥;
- */
- PUB_KEY((byte) (BaseType.BYTES | 0x05)),
-
- /**
- * 签名摘要;
- */
- SIGNATURE_DIGEST((byte) (BaseType.BYTES | 0x06)),
-
- /**
- * 哈希摘要;
- */
- HASH_DIGEST((byte) (BaseType.BYTES | 0x07)),
-
- /**
- * 加密数据;
- */
- ENCRYPTED_DATA((byte) (BaseType.BYTES | 0x08)),
-
- /**
- * DataContract 数据;
- */
- DATA_CONTRACT((byte) (BaseType.EXT | 0x01));
-
-
-
- public static final boolean BOOLEAN_DEFAULT_VALUE = false;
-
- public static final byte INT8_DEFAULT_VALUE = 0;
-
- public static final short INT16_DEFAULT_VALUE = 0;
-
- public static final int INT32_DEFAULT_VALUE = 0;
-
- public static final long INT64_DEFAULT_VALUE = 0;
-
-
-
- @EnumField(type = PrimitiveType.INT8)
- public final byte CODE;
-
- private DataType(byte code) {
- this.CODE = code;
- }
-
- /**
- * 是否表示“文本类型”或“文本衍生类型”;
- *
- * @return
- */
- public boolean isText() {
- return BaseType.TEXT == (BaseType.TEXT & CODE);
- }
-
- /**
- * 是否表示“字节类型”或“字节衍生类型”;
- *
- * @return
- */
- public boolean isBytes() {
- return BaseType.BYTES == (BaseType.BYTES & CODE);
- }
-
- /**
- * 是否表示“整数类型”或“整数衍生类型”;
- *
- * @return
- */
- public boolean isInteger() {
- return BaseType.INTEGER == (BaseType.INTEGER & CODE);
- }
-
- /**
- * 是否表示“布尔类型”;
- *
- * @return
- */
- public boolean isBoolean() {
- return BaseType.BOOLEAN == (BaseType.BOOLEAN & CODE);
- }
-
- /**
- * 是否表示“扩展类型”;
- *
- * @return
- */
- public boolean isExt() {
- return BaseType.EXT == (BaseType.EXT & CODE);
- }
-
- public static DataType valueOf(byte code) {
- for (DataType dataType : DataType.values()) {
- if (dataType.CODE == code) {
- return dataType;
- }
- }
- throw new IllegalArgumentException("Code [" + code + "] not supported by BytesValueType enum!");
- }
-
-}
+package com.jd.blockchain.ledger;
+
+import com.jd.blockchain.binaryproto.BaseType;
+import com.jd.blockchain.binaryproto.EnumContract;
+import com.jd.blockchain.binaryproto.EnumField;
+import com.jd.blockchain.binaryproto.PrimitiveType;
+import com.jd.blockchain.consts.DataCodes;
+
+/**
+ * 键值操作的数据类型;
+ *
+ * @author huanghaiquan
+ *
+ */
+@EnumContract(code = DataCodes.ENUM_TYPE_BYTES_VALUE_TYPE)
+public enum DataType {
+
+ /**
+ * 空;
+ */
+ NIL(PrimitiveType.NIL.CODE),
+
+ /**
+ * 布尔型;
+ */
+ BOOLEAN(PrimitiveType.BOOLEAN.CODE),
+
+ /**
+ * 数值型:
+ */
+
+ INT8(PrimitiveType.INT8.CODE),
+
+ INT16(PrimitiveType.INT16.CODE),
+
+ INT32(PrimitiveType.INT32.CODE),
+
+ INT64(PrimitiveType.INT64.CODE),
+
+ /**
+ * 文本数据;
+ */
+ TEXT(PrimitiveType.TEXT.CODE),
+
+ /**
+ * 二进制数据;
+ */
+ BYTES(PrimitiveType.BYTES.CODE),
+
+ /**
+ * 时间戳;
+ */
+ TIMESTAMP((byte) (BaseType.INTEGER | 0x08)),
+
+ /**
+ * 文本数据;
+ */
+ JSON((byte) (BaseType.TEXT | 0x01)),
+
+ /**
+ * 文本数据;
+ */
+ XML((byte) (BaseType.TEXT | 0x02)),
+
+ /**
+ * 大整数;
+ */
+ BIG_INT((byte) (BaseType.BYTES | 0x01)),
+
+ /**
+ * 图片;
+ */
+ IMG((byte) (BaseType.BYTES | 0x02)),
+
+ /**
+ * 视频;
+ */
+ VIDEO((byte) (BaseType.BYTES | 0x03)),
+
+ /**
+ * 位置坐标;
+ */
+ LOCATION((byte) (BaseType.BYTES | 0x04)),
+
+ /**
+ * 公钥;
+ */
+ PUB_KEY((byte) (BaseType.BYTES | 0x05)),
+
+ /**
+ * 签名摘要;
+ */
+ SIGNATURE_DIGEST((byte) (BaseType.BYTES | 0x06)),
+
+ /**
+ * 哈希摘要;
+ */
+ HASH_DIGEST((byte) (BaseType.BYTES | 0x07)),
+
+ /**
+ * 加密数据;
+ */
+ ENCRYPTED_DATA((byte) (BaseType.BYTES | 0x08)),
+
+ /**
+ * DataContract 数据;
+ */
+ DATA_CONTRACT((byte) (BaseType.EXT | 0x01));
+
+
+
+ public static final boolean BOOLEAN_DEFAULT_VALUE = false;
+
+ public static final byte INT8_DEFAULT_VALUE = 0;
+
+ public static final short INT16_DEFAULT_VALUE = 0;
+
+ public static final int INT32_DEFAULT_VALUE = 0;
+
+ public static final long INT64_DEFAULT_VALUE = 0;
+
+
+
+ @EnumField(type = PrimitiveType.INT8)
+ public final byte CODE;
+
+ private DataType(byte code) {
+ this.CODE = code;
+ }
+
+ /**
+ * 是否表示“文本类型”或“文本衍生类型”;
+ *
+ * @return
+ */
+ public boolean isText() {
+ return BaseType.TEXT == (BaseType.TEXT & CODE);
+ }
+
+ /**
+ * 是否表示“字节类型”或“字节衍生类型”;
+ *
+ * @return
+ */
+ public boolean isBytes() {
+ return BaseType.BYTES == (BaseType.BYTES & CODE);
+ }
+
+ /**
+ * 是否表示“整数类型”或“整数衍生类型”;
+ *
+ * @return
+ */
+ public boolean isInteger() {
+ return BaseType.INTEGER == (BaseType.INTEGER & CODE);
+ }
+
+ /**
+ * 是否表示“布尔类型”;
+ *
+ * @return
+ */
+ public boolean isBoolean() {
+ return BaseType.BOOLEAN == (BaseType.BOOLEAN & CODE);
+ }
+
+ /**
+ * 是否表示“扩展类型”;
+ *
+ * @return
+ */
+ public boolean isExt() {
+ return BaseType.EXT == (BaseType.EXT & CODE);
+ }
+
+ public static DataType valueOf(byte code) {
+ for (DataType dataType : DataType.values()) {
+ if (dataType.CODE == code) {
+ return dataType;
+ }
+ }
+ throw new IllegalArgumentException("Code [" + code + "] not supported by BytesValueType enum!");
+ }
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataVersionConflictException.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataVersionConflictException.java
index 9831c0cc..29042200 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataVersionConflictException.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DataVersionConflictException.java
@@ -1,27 +1,27 @@
-package com.jd.blockchain.ledger;
-
-public class DataVersionConflictException extends LedgerException {
-
- private static final long serialVersionUID = 3583192000738807503L;
-
- private TransactionState state;
-
- public DataVersionConflictException() {
- this(TransactionState.DATA_VERSION_CONFLICT, null);
- }
-
- public DataVersionConflictException(String message) {
- this(TransactionState.DATA_VERSION_CONFLICT, message);
- }
-
- private DataVersionConflictException(TransactionState state, String message) {
- super(message);
- assert TransactionState.SUCCESS != state;
- this.state = state;
- }
-
- public TransactionState getState() {
- return state;
- }
-
-}
+package com.jd.blockchain.ledger;
+
+public class DataVersionConflictException extends LedgerException {
+
+ private static final long serialVersionUID = 3583192000738807503L;
+
+ private TransactionState state;
+
+ public DataVersionConflictException() {
+ this(TransactionState.DATA_VERSION_CONFLICT, null);
+ }
+
+ public DataVersionConflictException(String message) {
+ this(TransactionState.DATA_VERSION_CONFLICT, message);
+ }
+
+ private DataVersionConflictException(TransactionState state, String message) {
+ super(message);
+ assert TransactionState.SUCCESS != state;
+ this.state = state;
+ }
+
+ public TransactionState getState() {
+ return state;
+ }
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DigitalSignature.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DigitalSignature.java
index f5acef07..4616f7ee 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DigitalSignature.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/DigitalSignature.java
@@ -1,15 +1,15 @@
-package com.jd.blockchain.ledger;
-
-import com.jd.blockchain.binaryproto.DataContract;
-import com.jd.blockchain.consts.DataCodes;
-
-/**
- * 数字签名;
- *
- * @author huanghaiquan
- *
- */
-@DataContract(code= DataCodes.DIGITALSIGNATURE)
-public interface DigitalSignature extends DigitalSignatureBody {
-
-}
+package com.jd.blockchain.ledger;
+
+import com.jd.blockchain.binaryproto.DataContract;
+import com.jd.blockchain.consts.DataCodes;
+
+/**
+ * 数字签名;
+ *
+ * @author huanghaiquan
+ *
+ */
+@DataContract(code= DataCodes.DIGITALSIGNATURE)
+public interface DigitalSignature extends DigitalSignatureBody {
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/EndpointRequest.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/EndpointRequest.java
index 00253b85..391ac609 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/EndpointRequest.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/EndpointRequest.java
@@ -1,30 +1,30 @@
-package com.jd.blockchain.ledger;
-
-import com.jd.blockchain.binaryproto.DataContract;
-import com.jd.blockchain.binaryproto.DataField;
-import com.jd.blockchain.binaryproto.PrimitiveType;
-import com.jd.blockchain.consts.DataCodes;
-import com.jd.blockchain.crypto.HashDigest;
-
-@DataContract(code= DataCodes.REQUEST_ENDPOINT)
-public interface EndpointRequest {
-
- @DataField(order=1, primitiveType = PrimitiveType.BYTES)
- HashDigest getHash();
- /**
- * 交易内容;
- *
- * @return
- */
- @DataField(order=2, refContract=true)
- TransactionContent getTransactionContent();
-
- /**
- * 终端用户的签名列表;
- *
- * @return
- */
- @DataField(order=3, list=true, refContract=true)
- DigitalSignature[] getEndpointSignatures();
-
-}
+package com.jd.blockchain.ledger;
+
+import com.jd.blockchain.binaryproto.DataContract;
+import com.jd.blockchain.binaryproto.DataField;
+import com.jd.blockchain.binaryproto.PrimitiveType;
+import com.jd.blockchain.consts.DataCodes;
+import com.jd.blockchain.crypto.HashDigest;
+
+@DataContract(code= DataCodes.REQUEST_ENDPOINT)
+public interface EndpointRequest {
+
+ @DataField(order=1, primitiveType = PrimitiveType.BYTES)
+ HashDigest getHash();
+ /**
+ * 交易内容;
+ *
+ * @return
+ */
+ @DataField(order=2, refContract=true)
+ TransactionContent getTransactionContent();
+
+ /**
+ * 终端用户的签名列表;
+ *
+ * @return
+ */
+ @DataField(order=3, list=true, refContract=true)
+ DigitalSignature[] getEndpointSignatures();
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/HashAlgorithm.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/HashAlgorithm.java
index 03953c21..61674095 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/HashAlgorithm.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/HashAlgorithm.java
@@ -1,46 +1,46 @@
-//package com.jd.blockchain.ledger;
-//
-///**
-// * Hash 算法的代码常量;
-// *
-// * @author zhaoming9
-// *
-// */
-//public enum HashAlgorithm {
-//
-// RIPE160((byte) 1),
-//
-// SHA256((byte) 2),
-//
-// SM3((byte) 4);
-//
-// public final byte CODE;
-//
-// private HashAlgorithm(byte algorithm) {
-// CODE = algorithm;
-// }
-//
-// public byte getAlgorithm() {
-// return CODE;
-// }
-//
-// public static HashAlgorithm valueOf(byte algorithm) {
-// for (HashAlgorithm hashAlgorithm : HashAlgorithm.values()) {
-// if (hashAlgorithm.CODE == algorithm) {
-// return hashAlgorithm;
-// }
-// }
-// throw new IllegalArgumentException("Unsupported hash algorithm [" + algorithm + "]!");
-// }
-//
-// public static void checkHashAlgorithm(HashAlgorithm algorithm) {
-// switch (algorithm) {
-// case RIPE160:
-// break;
-// case SHA256:
-// break;
-// default:
-// throw new IllegalArgumentException("Unsupported hash algorithm [" + algorithm + "]!");
-// }
-// }
-//}
+//package com.jd.blockchain.ledger;
+//
+///**
+// * Hash 算法的代码常量;
+// *
+// * @author zhaoming9
+// *
+// */
+//public enum HashAlgorithm {
+//
+// RIPE160((byte) 1),
+//
+// SHA256((byte) 2),
+//
+// SM3((byte) 4);
+//
+// public final byte CODE;
+//
+// private HashAlgorithm(byte algorithm) {
+// CODE = algorithm;
+// }
+//
+// public byte getAlgorithm() {
+// return CODE;
+// }
+//
+// public static HashAlgorithm valueOf(byte algorithm) {
+// for (HashAlgorithm hashAlgorithm : HashAlgorithm.values()) {
+// if (hashAlgorithm.CODE == algorithm) {
+// return hashAlgorithm;
+// }
+// }
+// throw new IllegalArgumentException("Unsupported hash algorithm [" + algorithm + "]!");
+// }
+//
+// public static void checkHashAlgorithm(HashAlgorithm algorithm) {
+// switch (algorithm) {
+// case RIPE160:
+// break;
+// case SHA256:
+// break;
+// default:
+// throw new IllegalArgumentException("Unsupported hash algorithm [" + algorithm + "]!");
+// }
+// }
+//}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/HashObject.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/HashObject.java
index ccba57aa..d5deae10 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/HashObject.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/HashObject.java
@@ -1,37 +1,37 @@
-package com.jd.blockchain.ledger;
-
-import com.jd.blockchain.binaryproto.DataContract;
-import com.jd.blockchain.consts.DataCodes;
-import com.jd.blockchain.crypto.HashDigest;
-
-/**
- * HashObject 表示以“哈希值”作为唯一标识的对象;
- *
- * @author huanghaiquan
- *
- */
-@DataContract(code= DataCodes.HASH_OBJECT)
-public interface HashObject {
-
- /**
- * 哈希值;
- *
- * @return
- */
- //no need annotation
- HashDigest getHash();
-
- // /**
- // * 哈希算法;
- // *
- // * @return
- // */
- // HashAlgorithm getHashAlgorithm();
-
- // /**
- // * 进行哈希运算的数据;
- // * @return
- // */
- // ByteArray getHashData();
-
-}
+package com.jd.blockchain.ledger;
+
+import com.jd.blockchain.binaryproto.DataContract;
+import com.jd.blockchain.consts.DataCodes;
+import com.jd.blockchain.crypto.HashDigest;
+
+/**
+ * HashObject 表示以“哈希值”作为唯一标识的对象;
+ *
+ * @author huanghaiquan
+ *
+ */
+@DataContract(code= DataCodes.HASH_OBJECT)
+public interface HashObject {
+
+ /**
+ * 哈希值;
+ *
+ * @return
+ */
+ //no need annotation
+ HashDigest getHash();
+
+ // /**
+ // * 哈希算法;
+ // *
+ // * @return
+ // */
+ // HashAlgorithm getHashAlgorithm();
+
+ // /**
+ // * 进行哈希运算的数据;
+ // * @return
+ // */
+ // ByteArray getHashData();
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Ledger.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Ledger.java
index 073ea143..213b1170 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Ledger.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Ledger.java
@@ -1,59 +1,59 @@
-//package com.jd.blockchain.ledger;
-//
-//import my.utils.io.ByteArray;
-//
-//import java.io.Serializable;
-//
-///**
-// * Ledger 账本;
-// *
-// * 账本只是一个逻辑上的对象,它是对一条区块的hash链的归纳抽象,而在存储上并没有具体的存在形式,而是具体化为由一个特定的创世区块作为开端的区块 hash
-// * 链;
-// *
-// * 账本的唯一标识也是其创世区块(GenisisBlock)的 hash;
-// *
-// * @author huanghaiquan
-// *
-// */
-//public interface Ledger extends Serializable {
-//
-// /**
-// * 账本的 hash;
-// *
-// * 同时也是账本的唯一,等同于其创世区块(GenisisBlock)的 hash {@link GenesisBlock#getBlockHash()};
-// *
-// * @return
-// */
-// ByteArray getLedgerHash();
-//
-// /**
-// * 账本结构版本;
-// *
-// * 等同于 {@link Block#getLedgerVersion()};
-// *
-// * @return
-// */
-// long getLedgerVersion();
-//
-// /**
-// * 由随机数构成的该账本的创世序列;
-// *
-// * @return
-// */
-// ByteArray getGenesisKey();
-//
-// /**
-// * 当前最新区块的 hash;
-// *
-// * @return
-// */
-// ByteArray getBlockHash();
-//
-// /**
-// * 账本的区块高度;
-// *
-// * @return
-// */
-// long getBlockHeight();
-//
-//}
+//package com.jd.blockchain.ledger;
+//
+//import my.utils.io.ByteArray;
+//
+//import java.io.Serializable;
+//
+///**
+// * Ledger 账本;
+// *
+// * 账本只是一个逻辑上的对象,它是对一条区块的hash链的归纳抽象,而在存储上并没有具体的存在形式,而是具体化为由一个特定的创世区块作为开端的区块 hash
+// * 链;
+// *
+// * 账本的唯一标识也是其创世区块(GenisisBlock)的 hash;
+// *
+// * @author huanghaiquan
+// *
+// */
+//public interface Ledger extends Serializable {
+//
+// /**
+// * 账本的 hash;
+// *
+// * 同时也是账本的唯一,等同于其创世区块(GenisisBlock)的 hash {@link GenesisBlock#getBlockHash()};
+// *
+// * @return
+// */
+// ByteArray getLedgerHash();
+//
+// /**
+// * 账本结构版本;
+// *
+// * 等同于 {@link Block#getLedgerVersion()};
+// *
+// * @return
+// */
+// long getLedgerVersion();
+//
+// /**
+// * 由随机数构成的该账本的创世序列;
+// *
+// * @return
+// */
+// ByteArray getGenesisKey();
+//
+// /**
+// * 当前最新区块的 hash;
+// *
+// * @return
+// */
+// ByteArray getBlockHash();
+//
+// /**
+// * 账本的区块高度;
+// *
+// * @return
+// */
+// long getBlockHeight();
+//
+//}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerImpl.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerImpl.java
index 50e307f5..e9caf22a 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerImpl.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerImpl.java
@@ -1,323 +1,323 @@
-//package com.jd.blockchain.ledger;
-//
-//import com.jd.blockchain.ledger.data.HashEncoding;
-//
-//import my.utils.io.ByteArray;
-//import my.utils.io.BytesEncoding;
-//import my.utils.io.BytesReader;
-//import my.utils.io.BytesUtils;
-//import my.utils.io.BytesWriter;
-//import my.utils.io.NumberMask;
-//
-//import java.io.IOException;
-//import java.io.InputStream;
-//import java.io.OutputStream;
-//import java.util.Objects;
-//
-///**
-// * Ledger 实现
-// *
-// * @author zhaoming9
-// */
-//public class LedgerImpl implements Ledger, BytesWriter, BytesReader {
-//
-// private HashAlgorithm ledgerHashAlgorithm = HashAlgorithm.SHA256; // 账本hash算法
-// private ByteArray ledgerHash = ByteArray.EMPTY; // 账本hash
-//
-// private long blockHeight = 0; // 账本当前高度
-// private long blockVersion = 0; // 账本当前版本
-//
-// private HashAlgorithm currentBlockHashAlgorithm = HashAlgorithm.SHA256; // 账本当前区块hash算法
-// private ByteArray currentBlockHash = ByteArray.EMPTY; // 账本当前区块hash
-//
-// private HashAlgorithm previousBlockHashAlgorithm = HashAlgorithm.SHA256; // 账本前一区块hash算法
-// private ByteArray previousBlockHash = ByteArray.EMPTY; // 账本前一区块hash
-//
-// private ByteArray accountRoot = ByteArray.EMPTY; // account mpt root hash
-// private long accountCount; // 账户数量
-// private long txTotalCount; // 交易数量
-//
-// private ByteArray genesisKey=ByteArray.EMPTY; // 创世块随机序列
-//
-// public LedgerImpl() {
-// }
-//
-// /**
-// * 初始化一个新的账本;
-// * @param genesisKey
-// */
-// public LedgerImpl(ByteArray genesisKey) {
-// this.genesisKey = genesisKey;
-// }
-//
-// /**
-// * @param ledgerHashAlgorithm
-// * @param ledgerHash
-// * @param height
-// * @param version
-// * @param currentBlockHashAlgorithm
-// * @param currentBlockHash
-// * @param previousBlockHashAlgorithm
-// * @param previousBlockHash
-// * @param accountRoot
-// * @param accountCount
-// * @param txTotalCount
-// * @param genesisKey
-// */
-// private LedgerImpl(HashAlgorithm ledgerHashAlgorithm, ByteArray ledgerHash, long height, long version,
-// HashAlgorithm currentBlockHashAlgorithm, ByteArray currentBlockHash,
-// HashAlgorithm previousBlockHashAlgorithm, ByteArray previousBlockHash,
-// ByteArray accountRoot, long accountCount, long txTotalCount, ByteArray genesisKey) {
-// this.ledgerHashAlgorithm = ledgerHashAlgorithm;
-// this.ledgerHash = ledgerHash;
-// this.blockHeight = height;
-// this.blockVersion = version;
-// this.currentBlockHashAlgorithm = currentBlockHashAlgorithm;
-// this.currentBlockHash = currentBlockHash;
-// this.previousBlockHashAlgorithm = previousBlockHashAlgorithm;
-// this.previousBlockHash = previousBlockHash;
-// this.accountRoot = accountRoot;
-// this.accountCount = accountCount;
-// this.txTotalCount = txTotalCount;
-// this.genesisKey = genesisKey;
-// }
-//
-// public LedgerImpl(ByteArray ledgerHash, long blockHeight, long blockVersion, ByteArray currentBlockHash,
-// ByteArray previousBlockHash, ByteArray accountRoot, long accountCount, long txTotalCount, ByteArray genesisKey) {
-// this(HashAlgorithm.SHA256, ledgerHash, blockHeight, blockVersion, HashAlgorithm.SHA256, currentBlockHash,
-// HashAlgorithm.SHA256, previousBlockHash, accountRoot, accountCount, txTotalCount, genesisKey);
-// }
-//
-// public LedgerImpl(LedgerImpl ledger) {
-// this(ledger.getLedgerHashAlgorithm(), ledger.getLedgerHash(), ledger.getBlockHeight(), ledger.getBlockVersion(),
-// ledger.getCurrentBlockHashAlgorithm(), ledger.getCurrentBlockHash(),
-// ledger.getPreviousBlockHashAlgorithm(), ledger.getPreviousBlockHash(),
-// ledger.getAccountRoot(), ledger.getAccountCount(), ledger.getTxTotalCount(),ledger.getGenesisKey());
-// }
-//
-// public LedgerImpl nextLedger(ByteArray nextBlockHash, ByteArray accountRoot, long newAccountCnt, long newTxCnt) {
-// LedgerImpl nextLedger = new LedgerImpl(this);
-// nextLedger.blockHeight+=1;
-// nextLedger.previousBlockHash = nextLedger.currentBlockHash;
-// nextLedger.currentBlockHash = nextBlockHash;
-// nextLedger.accountRoot = accountRoot;
-// nextLedger.accountCount += newAccountCnt;
-// nextLedger.txTotalCount += newTxCnt;
-//
-// return nextLedger;
-// }
-//
-// /**
-// * 账本的 hash;
-// *
-// * 同时也是账本的唯一,等同于其创世区块(GenisisBlock)的 hash
-// *
-// * @return
-// */
-// @Override
-// public ByteArray getLedgerHash() {
-// return ledgerHash;
-// }
-//
-// /**
-// * 由随机数构成的该账本的创世序列;
-// *
-// * @return
-// */
-// @Override
-// public ByteArray getGenesisKey() {
-// return genesisKey;
-// }
-//
-// /**
-// * 当前最新区块的 hash;
-// *
-// * @return
-// */
-// @Override
-// public ByteArray getBlockHash() {
-// return currentBlockHash;
-// }
-//
-// public HashAlgorithm getBlockHashAlgorithm() {
-// return currentBlockHashAlgorithm;
-// }
-//
-// /**
-// * 账本的区块高度;
-// *
-// * @return
-// */
-// @Override
-// public long getBlockHeight() {
-// return blockHeight;
-// }
-//
-// @Override
-// public void resolvFrom(InputStream in) throws IOException {
-// HashAlgorithm ledgerHashAlgorithm = HashAlgorithm.valueOf(BytesUtils.readByte(in));
-// HashAlgorithm.checkHashAlgorithm(ledgerHashAlgorithm);
-// ByteArray ledgerHash = HashEncoding.read(in);
-//
-// long height = BytesUtils.readLong(in);
-// long version = BytesUtils.readLong(in);
-//
-// HashAlgorithm currentBlockHashAlgorithm = HashAlgorithm.valueOf(BytesUtils.readByte(in));
-// HashAlgorithm.checkHashAlgorithm(currentBlockHashAlgorithm);
-// ByteArray currentBlockHash = HashEncoding.read(in);
-//
-// HashAlgorithm previousBlockHashAlgorithm = HashAlgorithm.valueOf(BytesUtils.readByte(in));
-// HashAlgorithm.checkHashAlgorithm(previousBlockHashAlgorithm);
-// ByteArray previousBlockHash = HashEncoding.read(in);
-//
-// ByteArray accountHash = HashEncoding.read(in);
-// long accountCount = BytesUtils.readLong(in);
-// long txTotalCount = BytesUtils.readLong(in);
-// ByteArray key = BytesEncoding.readAsByteArray(NumberMask.SHORT, in);
-//
-// this.ledgerHashAlgorithm = ledgerHashAlgorithm;
-// this.ledgerHash = ledgerHash;
-// this.blockHeight = height;
-// this.blockVersion = version;
-// this.currentBlockHashAlgorithm = currentBlockHashAlgorithm;
-// this.currentBlockHash = currentBlockHash;
-// this.previousBlockHashAlgorithm = previousBlockHashAlgorithm;
-// this.previousBlockHash = previousBlockHash;
-// this.accountRoot = accountHash;
-// this.accountCount = accountCount;
-// this.txTotalCount = txTotalCount;
-// this.genesisKey = key;
-// }
-//
-// @Override
-// public void writeTo(OutputStream out) throws IOException {
-// BytesUtils.writeByte(ledgerHashAlgorithm.getAlgorithm(), out);
-// HashEncoding.write(ledgerHash, out);
-//
-// BytesUtils.writeLong(blockHeight, out);
-// BytesUtils.writeLong(blockVersion, out);
-//
-// BytesUtils.writeByte(currentBlockHashAlgorithm.getAlgorithm(), out);
-// HashEncoding.write(currentBlockHash, out);
-//
-// BytesUtils.writeByte(previousBlockHashAlgorithm.getAlgorithm(), out);
-// HashEncoding.write(previousBlockHash, out);
-//
-// HashEncoding.write(accountRoot, out);
-// BytesUtils.writeLong(accountCount, out);
-// BytesUtils.writeLong(txTotalCount, out);
-// BytesEncoding.write(genesisKey, NumberMask.SHORT, out);
-// }
-//
-// public HashAlgorithm getLedgerHashAlgorithm() {
-// return ledgerHashAlgorithm;
-// }
-//
-// public void setLedgerHashAlgorithm(HashAlgorithm ledgerHashAlgorithm) {
-// this.ledgerHashAlgorithm = ledgerHashAlgorithm;
-// }
-//
-// public void setLedgerHash(ByteArray ledgerHash) {
-// this.ledgerHash = ledgerHash;
-// }
-//
-// public void setBlockHeight(long blockHeight) {
-// this.blockHeight = blockHeight;
-// }
-//
-// public HashAlgorithm getCurrentBlockHashAlgorithm() {
-// return currentBlockHashAlgorithm;
-// }
-//
-// public void setCurrentBlockHashAlgorithm(HashAlgorithm currentBlockHashAlgorithm) {
-// this.currentBlockHashAlgorithm = currentBlockHashAlgorithm;
-// }
-//
-// public long getBlockVersion() {
-// return blockVersion;
-// }
-//
-// public void setBlockVersion(long blockVersion) {
-// this.blockVersion = blockVersion;
-// }
-//
-// public void setGenesisKey(ByteArray genesisKey) {
-// this.genesisKey = genesisKey;
-// }
-//
-// public ByteArray getCurrentBlockHash() {
-// return currentBlockHash;
-// }
-//
-// public void setCurrentBlockHash(ByteArray currentBlockHash) {
-// this.currentBlockHash = currentBlockHash;
-// }
-//
-// public HashAlgorithm getPreviousBlockHashAlgorithm() {
-// return previousBlockHashAlgorithm;
-// }
-//
-// public void setPreviousBlockHashAlgorithm(HashAlgorithm previousBlockHashAlgorithm) {
-// this.previousBlockHashAlgorithm = previousBlockHashAlgorithm;
-// }
-//
-// public ByteArray getAccountRoot() {
-// return accountRoot;
-// }
-//
-// public void setAccountRoot(ByteArray accountRoot) {
-// this.accountRoot = accountRoot;
-// }
-//
-// public long getAccountCount() {
-// return accountCount;
-// }
-//
-// public void setAccountCount(long accountCount) {
-// this.accountCount = accountCount;
-// }
-//
-// public long getTxTotalCount() {
-// return txTotalCount;
-// }
-//
-// public void setTxTotalCount(long txTotalCount) {
-// this.txTotalCount = txTotalCount;
-// }
-//
-// public ByteArray getPreviousBlockHash() {
-// return previousBlockHash;
-// }
-//
-// public void setPreviousBlockHash(ByteArray previousBlockHash) {
-// this.previousBlockHash = previousBlockHash;
-// }
-//
-// @Override
-// public boolean equals(Object o) {
-// if (this == o) return true;
-// if (!(o instanceof LedgerImpl)) return false;
-// LedgerImpl ledger = (LedgerImpl) o;
-// return getBlockHeight() == ledger.getBlockHeight() &&
-// getBlockVersion() == ledger.getBlockVersion() &&
-// getLedgerHashAlgorithm() == ledger.getLedgerHashAlgorithm() &&
-// Objects.equals(getLedgerHash(), ledger.getLedgerHash()) &&
-// getCurrentBlockHashAlgorithm() == ledger.getCurrentBlockHashAlgorithm() &&
-// Objects.equals(getCurrentBlockHash(), ledger.getCurrentBlockHash()) &&
-// getPreviousBlockHashAlgorithm() == ledger.getPreviousBlockHashAlgorithm() &&
-// Objects.equals(getPreviousBlockHash(), ledger.getPreviousBlockHash()) &&
-// Objects.equals(getGenesisKey(), ledger.getGenesisKey());
-// }
-//
-// @Override
-// public int hashCode() {
-//
-// return Objects.hash(getLedgerHashAlgorithm(), getLedgerHash(), getBlockHeight(), getBlockVersion(), getCurrentBlockHashAlgorithm(), getCurrentBlockHash(), getPreviousBlockHashAlgorithm(), getPreviousBlockHash(), getGenesisKey());
-// }
-//
-// @Override
-// public long getLedgerVersion() {
-// // TODO Auto-generated method stub
-// return 0;
-// }
-//}
+//package com.jd.blockchain.ledger;
+//
+//import com.jd.blockchain.ledger.data.HashEncoding;
+//
+//import my.utils.io.ByteArray;
+//import my.utils.io.BytesEncoding;
+//import my.utils.io.BytesReader;
+//import my.utils.io.BytesUtils;
+//import my.utils.io.BytesWriter;
+//import my.utils.io.NumberMask;
+//
+//import java.io.IOException;
+//import java.io.InputStream;
+//import java.io.OutputStream;
+//import java.util.Objects;
+//
+///**
+// * Ledger 实现
+// *
+// * @author zhaoming9
+// */
+//public class LedgerImpl implements Ledger, BytesWriter, BytesReader {
+//
+// private HashAlgorithm ledgerHashAlgorithm = HashAlgorithm.SHA256; // 账本hash算法
+// private ByteArray ledgerHash = ByteArray.EMPTY; // 账本hash
+//
+// private long blockHeight = 0; // 账本当前高度
+// private long blockVersion = 0; // 账本当前版本
+//
+// private HashAlgorithm currentBlockHashAlgorithm = HashAlgorithm.SHA256; // 账本当前区块hash算法
+// private ByteArray currentBlockHash = ByteArray.EMPTY; // 账本当前区块hash
+//
+// private HashAlgorithm previousBlockHashAlgorithm = HashAlgorithm.SHA256; // 账本前一区块hash算法
+// private ByteArray previousBlockHash = ByteArray.EMPTY; // 账本前一区块hash
+//
+// private ByteArray accountRoot = ByteArray.EMPTY; // account mpt root hash
+// private long accountCount; // 账户数量
+// private long txTotalCount; // 交易数量
+//
+// private ByteArray genesisKey=ByteArray.EMPTY; // 创世块随机序列
+//
+// public LedgerImpl() {
+// }
+//
+// /**
+// * 初始化一个新的账本;
+// * @param genesisKey
+// */
+// public LedgerImpl(ByteArray genesisKey) {
+// this.genesisKey = genesisKey;
+// }
+//
+// /**
+// * @param ledgerHashAlgorithm
+// * @param ledgerHash
+// * @param height
+// * @param version
+// * @param currentBlockHashAlgorithm
+// * @param currentBlockHash
+// * @param previousBlockHashAlgorithm
+// * @param previousBlockHash
+// * @param accountRoot
+// * @param accountCount
+// * @param txTotalCount
+// * @param genesisKey
+// */
+// private LedgerImpl(HashAlgorithm ledgerHashAlgorithm, ByteArray ledgerHash, long height, long version,
+// HashAlgorithm currentBlockHashAlgorithm, ByteArray currentBlockHash,
+// HashAlgorithm previousBlockHashAlgorithm, ByteArray previousBlockHash,
+// ByteArray accountRoot, long accountCount, long txTotalCount, ByteArray genesisKey) {
+// this.ledgerHashAlgorithm = ledgerHashAlgorithm;
+// this.ledgerHash = ledgerHash;
+// this.blockHeight = height;
+// this.blockVersion = version;
+// this.currentBlockHashAlgorithm = currentBlockHashAlgorithm;
+// this.currentBlockHash = currentBlockHash;
+// this.previousBlockHashAlgorithm = previousBlockHashAlgorithm;
+// this.previousBlockHash = previousBlockHash;
+// this.accountRoot = accountRoot;
+// this.accountCount = accountCount;
+// this.txTotalCount = txTotalCount;
+// this.genesisKey = genesisKey;
+// }
+//
+// public LedgerImpl(ByteArray ledgerHash, long blockHeight, long blockVersion, ByteArray currentBlockHash,
+// ByteArray previousBlockHash, ByteArray accountRoot, long accountCount, long txTotalCount, ByteArray genesisKey) {
+// this(HashAlgorithm.SHA256, ledgerHash, blockHeight, blockVersion, HashAlgorithm.SHA256, currentBlockHash,
+// HashAlgorithm.SHA256, previousBlockHash, accountRoot, accountCount, txTotalCount, genesisKey);
+// }
+//
+// public LedgerImpl(LedgerImpl ledger) {
+// this(ledger.getLedgerHashAlgorithm(), ledger.getLedgerHash(), ledger.getBlockHeight(), ledger.getBlockVersion(),
+// ledger.getCurrentBlockHashAlgorithm(), ledger.getCurrentBlockHash(),
+// ledger.getPreviousBlockHashAlgorithm(), ledger.getPreviousBlockHash(),
+// ledger.getAccountRoot(), ledger.getAccountCount(), ledger.getTxTotalCount(),ledger.getGenesisKey());
+// }
+//
+// public LedgerImpl nextLedger(ByteArray nextBlockHash, ByteArray accountRoot, long newAccountCnt, long newTxCnt) {
+// LedgerImpl nextLedger = new LedgerImpl(this);
+// nextLedger.blockHeight+=1;
+// nextLedger.previousBlockHash = nextLedger.currentBlockHash;
+// nextLedger.currentBlockHash = nextBlockHash;
+// nextLedger.accountRoot = accountRoot;
+// nextLedger.accountCount += newAccountCnt;
+// nextLedger.txTotalCount += newTxCnt;
+//
+// return nextLedger;
+// }
+//
+// /**
+// * 账本的 hash;
+// *
+// * 同时也是账本的唯一,等同于其创世区块(GenisisBlock)的 hash
+// *
+// * @return
+// */
+// @Override
+// public ByteArray getLedgerHash() {
+// return ledgerHash;
+// }
+//
+// /**
+// * 由随机数构成的该账本的创世序列;
+// *
+// * @return
+// */
+// @Override
+// public ByteArray getGenesisKey() {
+// return genesisKey;
+// }
+//
+// /**
+// * 当前最新区块的 hash;
+// *
+// * @return
+// */
+// @Override
+// public ByteArray getBlockHash() {
+// return currentBlockHash;
+// }
+//
+// public HashAlgorithm getBlockHashAlgorithm() {
+// return currentBlockHashAlgorithm;
+// }
+//
+// /**
+// * 账本的区块高度;
+// *
+// * @return
+// */
+// @Override
+// public long getBlockHeight() {
+// return blockHeight;
+// }
+//
+// @Override
+// public void resolvFrom(InputStream in) throws IOException {
+// HashAlgorithm ledgerHashAlgorithm = HashAlgorithm.valueOf(BytesUtils.readByte(in));
+// HashAlgorithm.checkHashAlgorithm(ledgerHashAlgorithm);
+// ByteArray ledgerHash = HashEncoding.read(in);
+//
+// long height = BytesUtils.readLong(in);
+// long version = BytesUtils.readLong(in);
+//
+// HashAlgorithm currentBlockHashAlgorithm = HashAlgorithm.valueOf(BytesUtils.readByte(in));
+// HashAlgorithm.checkHashAlgorithm(currentBlockHashAlgorithm);
+// ByteArray currentBlockHash = HashEncoding.read(in);
+//
+// HashAlgorithm previousBlockHashAlgorithm = HashAlgorithm.valueOf(BytesUtils.readByte(in));
+// HashAlgorithm.checkHashAlgorithm(previousBlockHashAlgorithm);
+// ByteArray previousBlockHash = HashEncoding.read(in);
+//
+// ByteArray accountHash = HashEncoding.read(in);
+// long accountCount = BytesUtils.readLong(in);
+// long txTotalCount = BytesUtils.readLong(in);
+// ByteArray key = BytesEncoding.readAsByteArray(NumberMask.SHORT, in);
+//
+// this.ledgerHashAlgorithm = ledgerHashAlgorithm;
+// this.ledgerHash = ledgerHash;
+// this.blockHeight = height;
+// this.blockVersion = version;
+// this.currentBlockHashAlgorithm = currentBlockHashAlgorithm;
+// this.currentBlockHash = currentBlockHash;
+// this.previousBlockHashAlgorithm = previousBlockHashAlgorithm;
+// this.previousBlockHash = previousBlockHash;
+// this.accountRoot = accountHash;
+// this.accountCount = accountCount;
+// this.txTotalCount = txTotalCount;
+// this.genesisKey = key;
+// }
+//
+// @Override
+// public void writeTo(OutputStream out) throws IOException {
+// BytesUtils.writeByte(ledgerHashAlgorithm.getAlgorithm(), out);
+// HashEncoding.write(ledgerHash, out);
+//
+// BytesUtils.writeLong(blockHeight, out);
+// BytesUtils.writeLong(blockVersion, out);
+//
+// BytesUtils.writeByte(currentBlockHashAlgorithm.getAlgorithm(), out);
+// HashEncoding.write(currentBlockHash, out);
+//
+// BytesUtils.writeByte(previousBlockHashAlgorithm.getAlgorithm(), out);
+// HashEncoding.write(previousBlockHash, out);
+//
+// HashEncoding.write(accountRoot, out);
+// BytesUtils.writeLong(accountCount, out);
+// BytesUtils.writeLong(txTotalCount, out);
+// BytesEncoding.write(genesisKey, NumberMask.SHORT, out);
+// }
+//
+// public HashAlgorithm getLedgerHashAlgorithm() {
+// return ledgerHashAlgorithm;
+// }
+//
+// public void setLedgerHashAlgorithm(HashAlgorithm ledgerHashAlgorithm) {
+// this.ledgerHashAlgorithm = ledgerHashAlgorithm;
+// }
+//
+// public void setLedgerHash(ByteArray ledgerHash) {
+// this.ledgerHash = ledgerHash;
+// }
+//
+// public void setBlockHeight(long blockHeight) {
+// this.blockHeight = blockHeight;
+// }
+//
+// public HashAlgorithm getCurrentBlockHashAlgorithm() {
+// return currentBlockHashAlgorithm;
+// }
+//
+// public void setCurrentBlockHashAlgorithm(HashAlgorithm currentBlockHashAlgorithm) {
+// this.currentBlockHashAlgorithm = currentBlockHashAlgorithm;
+// }
+//
+// public long getBlockVersion() {
+// return blockVersion;
+// }
+//
+// public void setBlockVersion(long blockVersion) {
+// this.blockVersion = blockVersion;
+// }
+//
+// public void setGenesisKey(ByteArray genesisKey) {
+// this.genesisKey = genesisKey;
+// }
+//
+// public ByteArray getCurrentBlockHash() {
+// return currentBlockHash;
+// }
+//
+// public void setCurrentBlockHash(ByteArray currentBlockHash) {
+// this.currentBlockHash = currentBlockHash;
+// }
+//
+// public HashAlgorithm getPreviousBlockHashAlgorithm() {
+// return previousBlockHashAlgorithm;
+// }
+//
+// public void setPreviousBlockHashAlgorithm(HashAlgorithm previousBlockHashAlgorithm) {
+// this.previousBlockHashAlgorithm = previousBlockHashAlgorithm;
+// }
+//
+// public ByteArray getAccountRoot() {
+// return accountRoot;
+// }
+//
+// public void setAccountRoot(ByteArray accountRoot) {
+// this.accountRoot = accountRoot;
+// }
+//
+// public long getAccountCount() {
+// return accountCount;
+// }
+//
+// public void setAccountCount(long accountCount) {
+// this.accountCount = accountCount;
+// }
+//
+// public long getTxTotalCount() {
+// return txTotalCount;
+// }
+//
+// public void setTxTotalCount(long txTotalCount) {
+// this.txTotalCount = txTotalCount;
+// }
+//
+// public ByteArray getPreviousBlockHash() {
+// return previousBlockHash;
+// }
+//
+// public void setPreviousBlockHash(ByteArray previousBlockHash) {
+// this.previousBlockHash = previousBlockHash;
+// }
+//
+// @Override
+// public boolean equals(Object o) {
+// if (this == o) return true;
+// if (!(o instanceof LedgerImpl)) return false;
+// LedgerImpl ledger = (LedgerImpl) o;
+// return getBlockHeight() == ledger.getBlockHeight() &&
+// getBlockVersion() == ledger.getBlockVersion() &&
+// getLedgerHashAlgorithm() == ledger.getLedgerHashAlgorithm() &&
+// Objects.equals(getLedgerHash(), ledger.getLedgerHash()) &&
+// getCurrentBlockHashAlgorithm() == ledger.getCurrentBlockHashAlgorithm() &&
+// Objects.equals(getCurrentBlockHash(), ledger.getCurrentBlockHash()) &&
+// getPreviousBlockHashAlgorithm() == ledger.getPreviousBlockHashAlgorithm() &&
+// Objects.equals(getPreviousBlockHash(), ledger.getPreviousBlockHash()) &&
+// Objects.equals(getGenesisKey(), ledger.getGenesisKey());
+// }
+//
+// @Override
+// public int hashCode() {
+//
+// return Objects.hash(getLedgerHashAlgorithm(), getLedgerHash(), getBlockHeight(), getBlockVersion(), getCurrentBlockHashAlgorithm(), getCurrentBlockHash(), getPreviousBlockHashAlgorithm(), getPreviousBlockHash(), getGenesisKey());
+// }
+//
+// @Override
+// public long getLedgerVersion() {
+// // TODO Auto-generated method stub
+// return 0;
+// }
+//}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitOperation.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitOperation.java
index 08b02e07..fed721b7 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitOperation.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitOperation.java
@@ -1,13 +1,13 @@
-package com.jd.blockchain.ledger;
-
-import com.jd.blockchain.binaryproto.DataContract;
-import com.jd.blockchain.binaryproto.DataField;
-import com.jd.blockchain.consts.DataCodes;
-
-@DataContract(code= DataCodes.TX_OP_LEDGER_INIT)
-public interface LedgerInitOperation extends Operation{
-
- @DataField(order=1, refContract=true)
- LedgerInitSetting getInitSetting();
-
-}
+package com.jd.blockchain.ledger;
+
+import com.jd.blockchain.binaryproto.DataContract;
+import com.jd.blockchain.binaryproto.DataField;
+import com.jd.blockchain.consts.DataCodes;
+
+@DataContract(code= DataCodes.TX_OP_LEDGER_INIT)
+public interface LedgerInitOperation extends Operation{
+
+ @DataField(order=1, refContract=true)
+ LedgerInitSetting getInitSetting();
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/MagicNumber.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/MagicNumber.java
index a738e3fb..c1a7a272 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/MagicNumber.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/MagicNumber.java
@@ -1,67 +1,67 @@
-package com.jd.blockchain.ledger;
-
-/**
- * 魔数表;
- *
- * @author huanghaiquan
- *
- */
-public class MagicNumber {
-
- /**
- * JD区块链系统标识的高位,即小写字母 j 的 ASCII;
- *
- */
- public static final byte JD_HIGH = 0x6A;
-
- /**
- * JD区块链系统标识的低位, 即小写字母 d 的 ASCII;
- */
- public static final byte JD_LOW = 0x64;
-
- /**
- * 创世区块标识;
- */
- public static final byte GENESIS_BLOCK = 0x00;
-
- /**
- * 子区块标识;
- *
- * 注:“子区块”是除了“创世区块”之外其它的区块;
- */
- public static final byte CHILD_BLOCK = 0x01;
-
- /**
- * 交易内容标识;
- */
- public static final byte TX_CONTENT = 0x10;
-
- /**
- * 交易请求标识;
- */
- public static final byte TX_REQUEST = 0x11;
-
- /**
- * 交易持久标识;
- */
- public static final byte TX_PERSISTENCE = 0x12;
-
- /**
- * 数字签名标识;
- */
- public static final byte SIGNATURE = 0x20;
-
-// /**
-// * 公钥标识;
-// */
-// public static final byte PUB_KEY = 0x21;
-//
-// /**
-// * 私钥标识;
-// */
-// public static final byte PRIV_KEY = 0x22;
-
-
-
-
-}
+package com.jd.blockchain.ledger;
+
+/**
+ * 魔数表;
+ *
+ * @author huanghaiquan
+ *
+ */
+public class MagicNumber {
+
+ /**
+ * JD区块链系统标识的高位,即小写字母 j 的 ASCII;
+ *
+ */
+ public static final byte JD_HIGH = 0x6A;
+
+ /**
+ * JD区块链系统标识的低位, 即小写字母 d 的 ASCII;
+ */
+ public static final byte JD_LOW = 0x64;
+
+ /**
+ * 创世区块标识;
+ */
+ public static final byte GENESIS_BLOCK = 0x00;
+
+ /**
+ * 子区块标识;
+ *
+ * 注:“子区块”是除了“创世区块”之外其它的区块;
+ */
+ public static final byte CHILD_BLOCK = 0x01;
+
+ /**
+ * 交易内容标识;
+ */
+ public static final byte TX_CONTENT = 0x10;
+
+ /**
+ * 交易请求标识;
+ */
+ public static final byte TX_REQUEST = 0x11;
+
+ /**
+ * 交易持久标识;
+ */
+ public static final byte TX_PERSISTENCE = 0x12;
+
+ /**
+ * 数字签名标识;
+ */
+ public static final byte SIGNATURE = 0x20;
+
+// /**
+// * 公钥标识;
+// */
+// public static final byte PUB_KEY = 0x21;
+//
+// /**
+// * 私钥标识;
+// */
+// public static final byte PRIV_KEY = 0x22;
+
+
+
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/NodeRequest.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/NodeRequest.java
index 4ccd8051..93eab0ba 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/NodeRequest.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/NodeRequest.java
@@ -1,22 +1,22 @@
-package com.jd.blockchain.ledger;
-
-import com.jd.blockchain.binaryproto.DataContract;
-import com.jd.blockchain.binaryproto.DataField;
-import com.jd.blockchain.consts.DataCodes;
-
-@DataContract(code = DataCodes.REQUEST_NODE)
-public interface NodeRequest extends EndpointRequest {
-
-
- /**
- * 接入交易的节点的签名;
- *
- * 注:能够提交交易的节点可以是共识节点或网关节点;
- *
- * @return
- */
-
- @DataField(order=1, list=true, refContract=true)
- DigitalSignature[] getNodeSignatures();
-
-}
+package com.jd.blockchain.ledger;
+
+import com.jd.blockchain.binaryproto.DataContract;
+import com.jd.blockchain.binaryproto.DataField;
+import com.jd.blockchain.consts.DataCodes;
+
+@DataContract(code = DataCodes.REQUEST_NODE)
+public interface NodeRequest extends EndpointRequest {
+
+
+ /**
+ * 接入交易的节点的签名;
+ *
+ * 注:能够提交交易的节点可以是共识节点或网关节点;
+ *
+ * @return
+ */
+
+ @DataField(order=1, list=true, refContract=true)
+ DigitalSignature[] getNodeSignatures();
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/OperationArgument.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/OperationArgument.java
index 5c2f3b3b..c0c87e7a 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/OperationArgument.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/OperationArgument.java
@@ -1,27 +1,27 @@
-package com.jd.blockchain.ledger;
-
-import com.jd.blockchain.utils.io.ByteArray;
-
-/**
- * 操作参数;
- *
- * @author huanghaiquan
- *
- */
-public interface OperationArgument {
-
- /**
- * 参数类型;
- *
- * @return
- */
- byte getKey();
-
- /**
- * 参数值;
- *
- * @return
- */
- ByteArray getValue();
-
-}
+package com.jd.blockchain.ledger;
+
+import com.jd.blockchain.utils.io.ByteArray;
+
+/**
+ * 操作参数;
+ *
+ * @author huanghaiquan
+ *
+ */
+public interface OperationArgument {
+
+ /**
+ * 参数类型;
+ *
+ * @return
+ */
+ byte getKey();
+
+ /**
+ * 参数值;
+ *
+ * @return
+ */
+ ByteArray getValue();
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/PermissionType.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/PermissionType.java
index 3f6a4634..9176f36a 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/PermissionType.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/PermissionType.java
@@ -1,68 +1,68 @@
-package com.jd.blockchain.ledger;
-
-/**
- * 权限类型;
- *
- * @author huanghaiquan
- *
- */
-public enum PermissionType {
-
- /**
- * 账户权限配置;
- */
- SET_PRIVILEGE(1),
-
- /**
- * 注册参与方;
- */
- REG_PARTICIPANT(2),
-
- /**
- * 配置账本;包括除了{@link #SET_PRIVILEGE}、 {@link #REG_PARTICIPANT} 之外的其它账本设置,例如:设置密码参数、共识参数等;
- */
- CONFIG_LEDGER(4),
-
- /**
- * 用户注册;
- */
- REG_USER(8),
-
- /**
- * 注册数据账户;
- */
- REG_DATA_ACCOUNT(16),
-
- /**
- * 部署新的合约代码;
- */
- DEPLOY_CONTRACT(32),
-
- /**
- * 写入用户信息;
- */
- SET_USER(1024),
-
- /**
- * 写入数据;
- */
- SET_DATA(2048),
-
- /**
- * 写入数据;
- */
- INVOKE_CONTRACT(4096),
-
- /**
- * 升级合约代码;
- */
- UPDATE_CONTRACT(8192);
-
-
- public final int CODE;
-
- private PermissionType(int code) {
- this.CODE = code;
- }
-
-}
+package com.jd.blockchain.ledger;
+
+/**
+ * 权限类型;
+ *
+ * @author huanghaiquan
+ *
+ */
+public enum PermissionType {
+
+ /**
+ * 账户权限配置;
+ */
+ SET_PRIVILEGE(1),
+
+ /**
+ * 注册参与方;
+ */
+ REG_PARTICIPANT(2),
+
+ /**
+ * 配置账本;包括除了{@link #SET_PRIVILEGE}、 {@link #REG_PARTICIPANT} 之外的其它账本设置,例如:设置密码参数、共识参数等;
+ */
+ CONFIG_LEDGER(4),
+
+ /**
+ * 用户注册;
+ */
+ REG_USER(8),
+
+ /**
+ * 注册数据账户;
+ */
+ REG_DATA_ACCOUNT(16),
+
+ /**
+ * 部署新的合约代码;
+ */
+ DEPLOY_CONTRACT(32),
+
+ /**
+ * 写入用户信息;
+ */
+ SET_USER(1024),
+
+ /**
+ * 写入数据;
+ */
+ SET_DATA(2048),
+
+ /**
+ * 写入数据;
+ */
+ INVOKE_CONTRACT(4096),
+
+ /**
+ * 升级合约代码;
+ */
+ UPDATE_CONTRACT(8192);
+
+
+ public final int CODE;
+
+ private PermissionType(int code) {
+ this.CODE = code;
+ }
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RolesConfigureOperation.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RolesConfigureOperation.java
index 1e448740..c26b3bc5 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RolesConfigureOperation.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RolesConfigureOperation.java
@@ -1,39 +1,39 @@
-package com.jd.blockchain.ledger;
-
-import com.jd.blockchain.binaryproto.DataContract;
-import com.jd.blockchain.binaryproto.DataField;
-import com.jd.blockchain.binaryproto.PrimitiveType;
-import com.jd.blockchain.consts.DataCodes;
-
-/**
- * 角色配置操作;
- *
- * @author huanghaiquan
- *
- */
-@DataContract(code = DataCodes.TX_OP_ROLE_CONFIGURE)
-public interface RolesConfigureOperation extends Operation {
-
- @DataField(order = 2, refContract = true, list = true)
- RolePrivilegeEntry[] getRoles();
-
- @DataContract(code = DataCodes.TX_OP_ROLE_CONFIGURE_ENTRY)
- public static interface RolePrivilegeEntry {
-
- @DataField(order = 1, primitiveType = PrimitiveType.TEXT)
- String getRoleName();
-
- @DataField(order = 2, refEnum = true, list = true)
- LedgerPermission[] getEnableLedgerPermissions();
-
- @DataField(order = 3, refEnum = true, list = true)
- LedgerPermission[] getDisableLedgerPermissions();
-
- @DataField(order = 4, refEnum = true, list = true)
- TransactionPermission[] getEnableTransactionPermissions();
-
- @DataField(order = 5, refEnum = true, list = true)
- TransactionPermission[] getDisableTransactionPermissions();
-
- }
-}
+package com.jd.blockchain.ledger;
+
+import com.jd.blockchain.binaryproto.DataContract;
+import com.jd.blockchain.binaryproto.DataField;
+import com.jd.blockchain.binaryproto.PrimitiveType;
+import com.jd.blockchain.consts.DataCodes;
+
+/**
+ * 角色配置操作;
+ *
+ * @author huanghaiquan
+ *
+ */
+@DataContract(code = DataCodes.TX_OP_ROLE_CONFIGURE)
+public interface RolesConfigureOperation extends Operation {
+
+ @DataField(order = 2, refContract = true, list = true)
+ RolePrivilegeEntry[] getRoles();
+
+ @DataContract(code = DataCodes.TX_OP_ROLE_CONFIGURE_ENTRY)
+ public static interface RolePrivilegeEntry {
+
+ @DataField(order = 1, primitiveType = PrimitiveType.TEXT)
+ String getRoleName();
+
+ @DataField(order = 2, refEnum = true, list = true)
+ LedgerPermission[] getEnableLedgerPermissions();
+
+ @DataField(order = 3, refEnum = true, list = true)
+ LedgerPermission[] getDisableLedgerPermissions();
+
+ @DataField(order = 4, refEnum = true, list = true)
+ TransactionPermission[] getEnableTransactionPermissions();
+
+ @DataField(order = 5, refEnum = true, list = true)
+ TransactionPermission[] getDisableTransactionPermissions();
+
+ }
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/SignatureInfo.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/SignatureInfo.java
index 60b1532f..574c1038 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/SignatureInfo.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/SignatureInfo.java
@@ -1,21 +1,21 @@
-package com.jd.blockchain.ledger;
-
-public interface SignatureInfo {
-
- /**
- * 签署账户的地址;
- *
- * @return
- */
- String getAddress();
-
- /**
- * 签名的摘要;
- *
- * 注:采用Base64编码;
- *
- * @return
- */
- String getDigest();
-
-}
+package com.jd.blockchain.ledger;
+
+public interface SignatureInfo {
+
+ /**
+ * 签署账户的地址;
+ *
+ * @return
+ */
+ String getAddress();
+
+ /**
+ * 签名的摘要;
+ *
+ * 注:采用Base64编码;
+ *
+ * @return
+ */
+ String getDigest();
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/StateOpType.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/StateOpType.java
index 342b20c3..74ad6851 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/StateOpType.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/StateOpType.java
@@ -1,37 +1,37 @@
-package com.jd.blockchain.ledger;
-
-/**
- * 状态操作类型;
- *
- * @author huanghaiquan
- *
- */
-public enum StateOpType {
-
- /**
- * 设置状态值;
- */
- SET((byte) 1),
-
- /**
- * 移除状态值;
- */
- REMOVE((byte) 0);
-
- public final byte CODE;
-
- private StateOpType(byte code) {
- this.CODE = code;
- }
-
- public static StateOpType valueOf(byte code) {
- for (StateOpType opType : StateOpType.values()) {
- if (opType.CODE == code) {
- return opType;
- }
- }
- throw new IllegalArgumentException("Unsupported code[" + code + "] of StateOpType!");
-
- }
-
-}
+package com.jd.blockchain.ledger;
+
+/**
+ * 状态操作类型;
+ *
+ * @author huanghaiquan
+ *
+ */
+public enum StateOpType {
+
+ /**
+ * 设置状态值;
+ */
+ SET((byte) 1),
+
+ /**
+ * 移除状态值;
+ */
+ REMOVE((byte) 0);
+
+ public final byte CODE;
+
+ private StateOpType(byte code) {
+ this.CODE = code;
+ }
+
+ public static StateOpType valueOf(byte code) {
+ for (StateOpType opType : StateOpType.values()) {
+ if (opType.CODE == code) {
+ return opType;
+ }
+ }
+ throw new IllegalArgumentException("Unsupported code[" + code + "] of StateOpType!");
+
+ }
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Transaction.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Transaction.java
index 542a3a49..2581c223 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Transaction.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Transaction.java
@@ -1,54 +1,54 @@
-package com.jd.blockchain.ledger;
-
-import com.jd.blockchain.binaryproto.DataContract;
-import com.jd.blockchain.binaryproto.DataField;
-import com.jd.blockchain.binaryproto.PrimitiveType;
-import com.jd.blockchain.consts.DataCodes;
-import com.jd.blockchain.crypto.HashDigest;
-
-/**
- * Transaction 区块链交易,是被原子执行的操作集合;
- *
- * @author huanghaiquan
- *
- */
-@DataContract(code = DataCodes.TX)
-public interface Transaction extends NodeRequest, HashObject {
-
- /**
- * 交易 Hash;
- *
- * 这是包含交易内容、签名列表、交易结果的完整性 hash;
- *
- * @return
- */
- @DataField(order = 1, primitiveType = PrimitiveType.BYTES)
- @Override
- HashDigest getHash();
-
- /**
- * 交易被包含的区块高度;
- *
- * @return
- */
- @DataField(order = 2, primitiveType = PrimitiveType.INT64)
- long getBlockHeight();
-
- /**
- * 交易的执行结果;
- *
- * 值为枚举值 {@link TransactionState#CODE} 之一;
- *
- * @return
- */
- @DataField(order = 3, refEnum = true)
- TransactionState getExecutionState();
-
- /**
- * 交易的返回结果
- *
- * @return
- */
- @DataField(order=4, list = true, refContract=true)
- OperationResult[] getOperationResults();
-}
+package com.jd.blockchain.ledger;
+
+import com.jd.blockchain.binaryproto.DataContract;
+import com.jd.blockchain.binaryproto.DataField;
+import com.jd.blockchain.binaryproto.PrimitiveType;
+import com.jd.blockchain.consts.DataCodes;
+import com.jd.blockchain.crypto.HashDigest;
+
+/**
+ * Transaction 区块链交易,是被原子执行的操作集合;
+ *
+ * @author huanghaiquan
+ *
+ */
+@DataContract(code = DataCodes.TX)
+public interface Transaction extends NodeRequest, HashObject {
+
+ /**
+ * 交易 Hash;
+ *
+ * 这是包含交易内容、签名列表、交易结果的完整性 hash;
+ *
+ * @return
+ */
+ @DataField(order = 1, primitiveType = PrimitiveType.BYTES)
+ @Override
+ HashDigest getHash();
+
+ /**
+ * 交易被包含的区块高度;
+ *
+ * @return
+ */
+ @DataField(order = 2, primitiveType = PrimitiveType.INT64)
+ long getBlockHeight();
+
+ /**
+ * 交易的执行结果;
+ *
+ * 值为枚举值 {@link TransactionState#CODE} 之一;
+ *
+ * @return
+ */
+ @DataField(order = 3, refEnum = true)
+ TransactionState getExecutionState();
+
+ /**
+ * 交易的返回结果
+ *
+ * @return
+ */
+ @DataField(order=4, list = true, refContract=true)
+ OperationResult[] getOperationResults();
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionBuilder.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionBuilder.java
index 7f0c6c02..87251c33 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionBuilder.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionBuilder.java
@@ -1,51 +1,51 @@
-package com.jd.blockchain.ledger;
-
-import com.jd.blockchain.crypto.HashDigest;
-import com.jd.blockchain.transaction.ClientOperator;
-import com.jd.blockchain.transaction.LedgerInitOperator;
-
-/**
- * 区块链交易模板;
- *
- * @author huanghaiquan
- *
- */
-public interface TransactionBuilder extends ClientOperator, LedgerInitOperator {
-
- HashDigest getLedgerHash();
-
- /**
- * 基于当前的系统时间完成交易定义,并生成就绪的交易数据;
- *
- * 注:调用此方法后,不能再向当前对象加入更多的操作;
- *
- * @return
- */
- TransactionRequestBuilder prepareRequest();
-
- /**
- * 生成交易内容;
- *
- * @return
- */
- TransactionContent prepareContent();
-
- /**
- * 基于当前的系统时间完成交易定义,并生成就绪的交易数据;
- *
- * 注:调用此方法后,不能再向当前对象加入更多的操作;
- *
- * @param time 交易时间戳;
- * @return
- */
- TransactionRequestBuilder prepareRequest(long time);
-
- /**
- * 生成交易内容;
- *
- * @param time 交易时间戳;
- * @return
- */
- TransactionContent prepareContent(long time);
-
-}
+package com.jd.blockchain.ledger;
+
+import com.jd.blockchain.crypto.HashDigest;
+import com.jd.blockchain.transaction.ClientOperator;
+import com.jd.blockchain.transaction.LedgerInitOperator;
+
+/**
+ * 区块链交易模板;
+ *
+ * @author huanghaiquan
+ *
+ */
+public interface TransactionBuilder extends ClientOperator, LedgerInitOperator {
+
+ HashDigest getLedgerHash();
+
+ /**
+ * 基于当前的系统时间完成交易定义,并生成就绪的交易数据;
+ *
+ * 注:调用此方法后,不能再向当前对象加入更多的操作;
+ *
+ * @return
+ */
+ TransactionRequestBuilder prepareRequest();
+
+ /**
+ * 生成交易内容;
+ *
+ * @return
+ */
+ TransactionContent prepareContent();
+
+ /**
+ * 基于当前的系统时间完成交易定义,并生成就绪的交易数据;
+ *
+ * 注:调用此方法后,不能再向当前对象加入更多的操作;
+ *
+ * @param time 交易时间戳;
+ * @return
+ */
+ TransactionRequestBuilder prepareRequest(long time);
+
+ /**
+ * 生成交易内容;
+ *
+ * @param time 交易时间戳;
+ * @return
+ */
+ TransactionContent prepareContent(long time);
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionRequestBuilder.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionRequestBuilder.java
index 87c445ad..0a35155f 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionRequestBuilder.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionRequestBuilder.java
@@ -1,81 +1,81 @@
-package com.jd.blockchain.ledger;
-
-import com.jd.blockchain.crypto.AsymmetricKeypair;
-import com.jd.blockchain.crypto.HashDigest;
-
-/**
- * 已就绪的交易;
- *
- * @author huanghaiquan
- *
- */
-public interface TransactionRequestBuilder extends HashObject {
-
- /**
- * 交易内容的 Hash;
- *
- * @return
- */
- @Override
- HashDigest getHash();
-
- /**
- * 交易数据内容;
- *
- *
- * 如果需要对交易进行外部签名,可以将此数据块发送到外部进行签名;
- *
- * @return
- */
- TransactionContent getTransactionContent();
-
- /**
- * 对交易进行签名;
- *
- * @param address
- * 签名账户的地址;
- * @param privKey
- * 签名账户的私钥;
- * @return
- */
- DigitalSignature signAsEndpoint(AsymmetricKeypair keyPair);
-
- /**
- * 对交易进行签名;
- *
- * @param address
- * 签名账户的地址;
- * @param privKey
- * 签名账户的私钥;
- * @return
- */
- DigitalSignature signAsNode(AsymmetricKeypair keyPair);
-
- /**
- * 加入签名;
- *
- * @param address
- * 签名账户的地址;
- * @param digest
- * Base64格式的签名摘要;
- * @return
- */
- void addEndpointSignature(DigitalSignature... signature);
-
- /**
- * 加入签名;
- *
- * @param address
- * 签名账户的地址;
- * @param digest
- * Base64格式的签名摘要;
- * @return
- */
- void addNodeSignature(DigitalSignature... signatures);
-
- /**
- * 生成交易请求;
- *
- */
- TransactionRequest buildRequest();
-}
+package com.jd.blockchain.ledger;
+
+import com.jd.blockchain.crypto.AsymmetricKeypair;
+import com.jd.blockchain.crypto.HashDigest;
+
+/**
+ * 已就绪的交易;
+ *
+ * @author huanghaiquan
+ *
+ */
+public interface TransactionRequestBuilder extends HashObject {
+
+ /**
+ * 交易内容的 Hash;
+ *
+ * @return
+ */
+ @Override
+ HashDigest getHash();
+
+ /**
+ * 交易数据内容;
+ *
+ *
+ * 如果需要对交易进行外部签名,可以将此数据块发送到外部进行签名;
+ *
+ * @return
+ */
+ TransactionContent getTransactionContent();
+
+ /**
+ * 对交易进行签名;
+ *
+ * @param address
+ * 签名账户的地址;
+ * @param privKey
+ * 签名账户的私钥;
+ * @return
+ */
+ DigitalSignature signAsEndpoint(AsymmetricKeypair keyPair);
+
+ /**
+ * 对交易进行签名;
+ *
+ * @param address
+ * 签名账户的地址;
+ * @param privKey
+ * 签名账户的私钥;
+ * @return
+ */
+ DigitalSignature signAsNode(AsymmetricKeypair keyPair);
+
+ /**
+ * 加入签名;
+ *
+ * @param address
+ * 签名账户的地址;
+ * @param digest
+ * Base64格式的签名摘要;
+ * @return
+ */
+ void addEndpointSignature(DigitalSignature... signature);
+
+ /**
+ * 加入签名;
+ *
+ * @param address
+ * 签名账户的地址;
+ * @param digest
+ * Base64格式的签名摘要;
+ * @return
+ */
+ void addNodeSignature(DigitalSignature... signatures);
+
+ /**
+ * 生成交易请求;
+ *
+ */
+ TransactionRequest buildRequest();
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionResponse.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionResponse.java
index 662d595b..9c5d6b1b 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionResponse.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionResponse.java
@@ -1,68 +1,68 @@
-package com.jd.blockchain.ledger;
-
-import com.jd.blockchain.binaryproto.DataContract;
-import com.jd.blockchain.binaryproto.DataField;
-import com.jd.blockchain.binaryproto.PrimitiveType;
-import com.jd.blockchain.consts.DataCodes;
-import com.jd.blockchain.crypto.HashDigest;
-
-/**
- * 交易请求 {@link TransactionRequest} 的回复;
- *
- * @author huanghaiquan
- *
- */
-@DataContract(code = DataCodes.TX_RESPONSE)
-public interface TransactionResponse {
-
- /**
- * 交易原始内容的哈希;
- *
- * @return
- */
- @DataField(order = 1, primitiveType = PrimitiveType.BYTES)
- HashDigest getContentHash();
-
- /**
- * 执行状态;
- *
- * @return
- */
- @DataField(order = 2, refEnum = true)
- TransactionState getExecutionState();
-
- /**
- * 交易被纳入的区块哈希;
- *
- * @return
- */
- @DataField(order = 3, primitiveType = PrimitiveType.BYTES)
- HashDigest getBlockHash();
-
- /**
- * 交易被纳入的区块高度;
- *
- *
- * 如果未生成区块,则返回 -1;
- *
- * @return
- */
- @DataField(order = 4, primitiveType = PrimitiveType.INT64)
- long getBlockHeight();
-
- /**
- * 交易是否执行成功
- *
- * @return
- */
- @DataField(order = 5, primitiveType = PrimitiveType.BOOLEAN)
- boolean isSuccess();
-
- /**
- * 合约返回值
- *
- * @return
- */
- @DataField(order=6, list=true, refContract = true)
- OperationResult[] getOperationResults();
+package com.jd.blockchain.ledger;
+
+import com.jd.blockchain.binaryproto.DataContract;
+import com.jd.blockchain.binaryproto.DataField;
+import com.jd.blockchain.binaryproto.PrimitiveType;
+import com.jd.blockchain.consts.DataCodes;
+import com.jd.blockchain.crypto.HashDigest;
+
+/**
+ * 交易请求 {@link TransactionRequest} 的回复;
+ *
+ * @author huanghaiquan
+ *
+ */
+@DataContract(code = DataCodes.TX_RESPONSE)
+public interface TransactionResponse {
+
+ /**
+ * 交易原始内容的哈希;
+ *
+ * @return
+ */
+ @DataField(order = 1, primitiveType = PrimitiveType.BYTES)
+ HashDigest getContentHash();
+
+ /**
+ * 执行状态;
+ *
+ * @return
+ */
+ @DataField(order = 2, refEnum = true)
+ TransactionState getExecutionState();
+
+ /**
+ * 交易被纳入的区块哈希;
+ *
+ * @return
+ */
+ @DataField(order = 3, primitiveType = PrimitiveType.BYTES)
+ HashDigest getBlockHash();
+
+ /**
+ * 交易被纳入的区块高度;
+ *
+ *
+ * 如果未生成区块,则返回 -1;
+ *
+ * @return
+ */
+ @DataField(order = 4, primitiveType = PrimitiveType.INT64)
+ long getBlockHeight();
+
+ /**
+ * 交易是否执行成功
+ *
+ * @return
+ */
+ @DataField(order = 5, primitiveType = PrimitiveType.BOOLEAN)
+ boolean isSuccess();
+
+ /**
+ * 合约返回值
+ *
+ * @return
+ */
+ @DataField(order=6, list=true, refContract = true)
+ OperationResult[] getOperationResults();
}
\ No newline at end of file
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionRollbackException.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionRollbackException.java
index 7694d898..731b2ed8 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionRollbackException.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionRollbackException.java
@@ -1,16 +1,16 @@
-package com.jd.blockchain.ledger;
-
-public class TransactionRollbackException extends RuntimeException {
-
-
- private static final long serialVersionUID = -1223140447229570029L;
-
- public TransactionRollbackException(String message) {
- super(message);
- }
-
- public TransactionRollbackException(String message, Throwable cause) {
- super(message, cause);
- }
-
-}
+package com.jd.blockchain.ledger;
+
+public class TransactionRollbackException extends RuntimeException {
+
+
+ private static final long serialVersionUID = -1223140447229570029L;
+
+ public TransactionRollbackException(String message) {
+ super(message);
+ }
+
+ public TransactionRollbackException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionTemplate.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionTemplate.java
index 0696e768..f734e7e8 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionTemplate.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionTemplate.java
@@ -1,27 +1,27 @@
-package com.jd.blockchain.ledger;
-
-import java.io.Closeable;
-
-import com.jd.blockchain.crypto.HashDigest;
-import com.jd.blockchain.transaction.ClientOperator;
-
-/**
- * 区块链交易模板;
- *
- * @author huanghaiquan
- *
- */
-public interface TransactionTemplate extends ClientOperator, Closeable {
-
- HashDigest getLedgerHash();
-
- /**
- * 完成交易定义,并生成就绪的交易数据;
- *
- * 注:调用此方法后,不能再向当前对象加入更多的操作;
- *
- * @return
- */
- PreparedTransaction prepare();
-
-}
+package com.jd.blockchain.ledger;
+
+import java.io.Closeable;
+
+import com.jd.blockchain.crypto.HashDigest;
+import com.jd.blockchain.transaction.ClientOperator;
+
+/**
+ * 区块链交易模板;
+ *
+ * @author huanghaiquan
+ *
+ */
+public interface TransactionTemplate extends ClientOperator, Closeable {
+
+ HashDigest getLedgerHash();
+
+ /**
+ * 完成交易定义,并生成就绪的交易数据;
+ *
+ * 注:调用此方法后,不能再向当前对象加入更多的操作;
+ *
+ * @return
+ */
+ PreparedTransaction prepare();
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserAuthorizeOperation.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserAuthorizeOperation.java
index 67e37e17..8b396844 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserAuthorizeOperation.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserAuthorizeOperation.java
@@ -1,57 +1,57 @@
-package com.jd.blockchain.ledger;
-
-import com.jd.blockchain.binaryproto.DataContract;
-import com.jd.blockchain.binaryproto.DataField;
-import com.jd.blockchain.binaryproto.PrimitiveType;
-import com.jd.blockchain.consts.DataCodes;
-import com.jd.blockchain.utils.Bytes;
-
-/**
- * 角色配置操作;
- *
- * @author huanghaiquan
- *
- */
-@DataContract(code = DataCodes.TX_OP_USER_ROLES_AUTHORIZE)
-public interface UserAuthorizeOperation extends Operation {
-
- @DataField(order = 2, refContract = true, list = true)
- UserRolesEntry[] getUserRolesAuthorizations();
-
- @DataContract(code = DataCodes.TX_OP_USER_ROLE_AUTHORIZE_ENTRY)
- public static interface UserRolesEntry {
-
- /**
- * 用户地址;
- *
- * @return
- */
- @DataField(order = 0, primitiveType = PrimitiveType.BYTES, list = true)
- Bytes[] getUserAddresses();
-
- /**
- * 要更新的多角色权限策略;
- *
- * @return
- */
- @DataField(order = 2, refEnum = true)
- RolesPolicy getPolicy();
-
- /**
- * 授权的角色清单;
- *
- * @return
- */
- @DataField(order = 3, primitiveType = PrimitiveType.TEXT, list = true)
- String[] getAuthorizedRoles();
-
- /**
- * 取消授权的角色清单;
- *
- * @return
- */
- @DataField(order = 4, primitiveType = PrimitiveType.TEXT, list = true)
- String[] getUnauthorizedRoles();
-
- }
-}
+package com.jd.blockchain.ledger;
+
+import com.jd.blockchain.binaryproto.DataContract;
+import com.jd.blockchain.binaryproto.DataField;
+import com.jd.blockchain.binaryproto.PrimitiveType;
+import com.jd.blockchain.consts.DataCodes;
+import com.jd.blockchain.utils.Bytes;
+
+/**
+ * 角色配置操作;
+ *
+ * @author huanghaiquan
+ *
+ */
+@DataContract(code = DataCodes.TX_OP_USER_ROLES_AUTHORIZE)
+public interface UserAuthorizeOperation extends Operation {
+
+ @DataField(order = 2, refContract = true, list = true)
+ UserRolesEntry[] getUserRolesAuthorizations();
+
+ @DataContract(code = DataCodes.TX_OP_USER_ROLE_AUTHORIZE_ENTRY)
+ public static interface UserRolesEntry {
+
+ /**
+ * 用户地址;
+ *
+ * @return
+ */
+ @DataField(order = 0, primitiveType = PrimitiveType.BYTES, list = true)
+ Bytes[] getUserAddresses();
+
+ /**
+ * 要更新的多角色权限策略;
+ *
+ * @return
+ */
+ @DataField(order = 2, refEnum = true)
+ RolesPolicy getPolicy();
+
+ /**
+ * 授权的角色清单;
+ *
+ * @return
+ */
+ @DataField(order = 3, primitiveType = PrimitiveType.TEXT, list = true)
+ String[] getAuthorizedRoles();
+
+ /**
+ * 取消授权的角色清单;
+ *
+ * @return
+ */
+ @DataField(order = 4, primitiveType = PrimitiveType.TEXT, list = true)
+ String[] getUnauthorizedRoles();
+
+ }
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserInfoSetOperation.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserInfoSetOperation.java
index c6372b78..491378ed 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserInfoSetOperation.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserInfoSetOperation.java
@@ -1,29 +1,29 @@
-package com.jd.blockchain.ledger;
-
-import com.jd.blockchain.binaryproto.DataContract;
-import com.jd.blockchain.consts.DataCodes;
-
-/**
- * @author huanghaiquan
- *
- */
-@DataContract(code=DataCodes.TX_OP_USER_INFO_SET)
-public interface UserInfoSetOperation extends Operation {
-
- String getUserAddress();
-
- KVEntry[] getPropertiesWriteSet();
-
-
- @DataContract(code=DataCodes.TX_OP_USER_INFO_SET_KV)
- public static interface KVEntry{
-
- String getKey();
-
- String getValue();
-
- long getExpectedVersion();
- }
-
-
-}
+package com.jd.blockchain.ledger;
+
+import com.jd.blockchain.binaryproto.DataContract;
+import com.jd.blockchain.consts.DataCodes;
+
+/**
+ * @author huanghaiquan
+ *
+ */
+@DataContract(code=DataCodes.TX_OP_USER_INFO_SET)
+public interface UserInfoSetOperation extends Operation {
+
+ String getUserAddress();
+
+ KVEntry[] getPropertiesWriteSet();
+
+
+ @DataContract(code=DataCodes.TX_OP_USER_INFO_SET_KV)
+ public static interface KVEntry{
+
+ String getKey();
+
+ String getValue();
+
+ long getExpectedVersion();
+ }
+
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserRegisterOperation.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserRegisterOperation.java
index caa642de..59956645 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserRegisterOperation.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserRegisterOperation.java
@@ -1,13 +1,13 @@
-package com.jd.blockchain.ledger;
-
-import com.jd.blockchain.binaryproto.DataContract;
-import com.jd.blockchain.binaryproto.DataField;
-import com.jd.blockchain.consts.DataCodes;
-
-@DataContract(code = DataCodes.TX_OP_USER_REG)
-public interface UserRegisterOperation extends Operation {
-
- @DataField(order = 2, refContract = true)
- BlockchainIdentity getUserID();
-
-}
+package com.jd.blockchain.ledger;
+
+import com.jd.blockchain.binaryproto.DataContract;
+import com.jd.blockchain.binaryproto.DataField;
+import com.jd.blockchain.consts.DataCodes;
+
+@DataContract(code = DataCodes.TX_OP_USER_REG)
+public interface UserRegisterOperation extends Operation {
+
+ @DataField(order = 2, refContract = true)
+ BlockchainIdentity getUserID();
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/setting/GatewayIncomingSetting.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/setting/GatewayIncomingSetting.java
index d6212fd7..e066d34c 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/setting/GatewayIncomingSetting.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/setting/GatewayIncomingSetting.java
@@ -1,26 +1,26 @@
-package com.jd.blockchain.setting;
-
-/**
- * 网关接入设置;
- *
- * @author huanghaiquan
- *
- */
-public class GatewayIncomingSetting {
-
- private LedgerIncomingSetting[] ledgers;
-
- /**
- * 所有账本的接入设置;
- *
- * @return
- */
- public LedgerIncomingSetting[] getLedgers() {
- return ledgers;
- }
-
- public void setLedgers(LedgerIncomingSetting[] ledgerSettings) {
- this.ledgers = ledgerSettings;
- }
-
-}
+package com.jd.blockchain.setting;
+
+/**
+ * 网关接入设置;
+ *
+ * @author huanghaiquan
+ *
+ */
+public class GatewayIncomingSetting {
+
+ private LedgerIncomingSetting[] ledgers;
+
+ /**
+ * 所有账本的接入设置;
+ *
+ * @return
+ */
+ public LedgerIncomingSetting[] getLedgers() {
+ return ledgers;
+ }
+
+ public void setLedgers(LedgerIncomingSetting[] ledgerSettings) {
+ this.ledgers = ledgerSettings;
+ }
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/BlockchainOperationFactory.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/BlockchainOperationFactory.java
index 66cec3b8..25e97d6d 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/BlockchainOperationFactory.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/BlockchainOperationFactory.java
@@ -1,358 +1,358 @@
-package com.jd.blockchain.transaction;
-
-import com.jd.blockchain.ledger.*;
-import com.jd.blockchain.utils.Bytes;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import com.jd.blockchain.crypto.PubKey;
-import com.jd.blockchain.ledger.*;
-import com.jd.blockchain.utils.Bytes;
-import com.jd.blockchain.utils.net.NetworkAddress;
-
-/**
- * @author huanghaiquan
- *
- */
-public class BlockchainOperationFactory implements ClientOperator, LedgerInitOperator {
-
- private static final SecurityOperationBuilderImpl SECURITY_OP_BUILDER = new SecurityOperationBuilderImpl();
-
- private static final LedgerInitOperationBuilderImpl LEDGER_INIT_OP_BUILDER = new LedgerInitOperationBuilderImpl();
-
- private static final UserRegisterOperationBuilderImpl USER_REG_OP_BUILDER = new UserRegisterOperationBuilderImpl();
-
- private static final DataAccountRegisterOperationBuilderImpl DATA_ACC_REG_OP_BUILDER = new DataAccountRegisterOperationBuilderImpl();
-
- private static final ContractCodeDeployOperationBuilderImpl CONTRACT_CODE_DEPLOY_OP_BUILDER = new ContractCodeDeployOperationBuilderImpl();
-
-// private static final ContractEventSendOperationBuilderImpl CONTRACT_EVENT_SEND_OP_BUILDER = new ContractEventSendOperationBuilderImpl();
-
- private SecurityOperationBuilderFilter securityOpBuilder = new SecurityOperationBuilderFilter();
-
- private static final ParticipantRegisterOperationBuilderImpl PARTICIPANT_REG_OP_BUILDER = new ParticipantRegisterOperationBuilderImpl();
-
- private static final ParticipantStateUpdateOperationBuilderImpl PARTICIPANT_STATE_UPDATE_OP_BUILDER = new ParticipantStateUpdateOperationBuilderImpl();
-
- private LedgerInitOperationBuilder ledgerInitOpBuilder = new LedgerInitOperationBuilderFilter();
-
- private UserRegisterOperationBuilder userRegOpBuilder = new UserRegisterOperationBuilderFilter();
-
- private DataAccountRegisterOperationBuilder dataAccRegOpBuilder = new DataAccountRegisterOperationBuilderFilter();
-
- private ContractCodeDeployOperationBuilder contractCodeDeployOpBuilder = new ContractCodeDeployOperationBuilderFilter();
-
- private ContractEventSendOperationBuilder contractEventSendOpBuilder = new ContractEventSendOperationBuilderFilter();
-
- private ContractInvocationProxyBuilder contractInvoProxyBuilder = new ContractInvocationProxyBuilder();
-
- private ParticipantRegisterOperationBuilder participantRegOpBuilder = new ParticipantRegisterOperationBuilderFilter();
-
- private ParticipantStateUpdateOperationBuilder participantStateModifyOpBuilder = new ParticipantStateUpdateOperationBuilderFilter();
-
- // TODO: 暂时只支持单线程情形,未考虑多线程;
- private List operationList = new ArrayList<>();
-
- @Override
- public LedgerInitOperationBuilder ledgers() {
- return ledgerInitOpBuilder;
- }
-
- @Override
- public SecurityOperationBuilder security() {
- return securityOpBuilder;
- }
-
- @Override
- public UserRegisterOperationBuilder users() {
- return userRegOpBuilder;
- }
-
- @Override
- public DataAccountRegisterOperationBuilder dataAccounts() {
- return dataAccRegOpBuilder;
- }
-
- @Override
- public DataAccountKVSetOperationBuilder dataAccount(String accountAddress) {
- return new DataAccountKVSetOperationBuilderFilter(Bytes.fromBase58(accountAddress));
- }
-
- @Override
- public DataAccountKVSetOperationBuilder dataAccount(Bytes accountAddress) {
- return new DataAccountKVSetOperationBuilderFilter(accountAddress);
- }
-
- @Override
- public ContractCodeDeployOperationBuilder contracts() {
- return contractCodeDeployOpBuilder;
- }
-
- public ContractEventSendOperationBuilder contractEvents() {
- return contractEventSendOpBuilder;
- }
-
- @Override
- public ParticipantRegisterOperationBuilder participants() {return participantRegOpBuilder;}
-
- @Override
- public ParticipantStateUpdateOperationBuilder states() {return participantStateModifyOpBuilder;}
-
- @Override
- public T contract(String address, Class contractIntf) {
- return contractInvoProxyBuilder.create(address, contractIntf, contractEventSendOpBuilder);
- }
-
- @Override
- public T contract(Bytes address, Class contractIntf) {
- return contractInvoProxyBuilder.create(address, contractIntf, contractEventSendOpBuilder);
- }
-
- /**
- * 返回已经定义的操作列表;
- *
- * @return
- */
- public Collection getOperations() {
- return operationList;
- }
-
- /**
- * 返回与操作列表对应的返回值处理器;
- *
- * @return
- */
- public Collection getReturnValuetHandlers() {
- List resultHandlers = new ArrayList();
- int index = 0;
- for (Operation op : operationList) {
- if (op instanceof ContractEventSendOperation) {
- // 操作具有返回值,创建对应的结果处理器;
- ContractEventSendOpTemplate opTemp = (ContractEventSendOpTemplate) op;
- ContractInvocation invocation = opTemp.getInvocation();
- OperationResultHandle retnHandler;
- if (invocation == null) {
- retnHandler = new NullOperationReturnValueHandler(index);
- } else {
- invocation.setOperationIndex(index);
- retnHandler = invocation;
- }
- resultHandlers.add(retnHandler);
- }
- index++;
- }
-
- return resultHandlers;
- }
-
- public void clear() {
- operationList.clear();
- }
-
- // --------------------------------- 内部类型 -----------------------------------
-
- private class LedgerInitOperationBuilderFilter implements LedgerInitOperationBuilder {
-
- @Override
- public LedgerInitOperation create(LedgerInitSetting initSetting) {
- LedgerInitOperation op = LEDGER_INIT_OP_BUILDER.create(initSetting);
- operationList.add(op);
- return op;
- }
-
- }
-
- private class UserRegisterOperationBuilderFilter implements UserRegisterOperationBuilder {
-
- @Override
- public UserRegisterOperation register(BlockchainIdentity userID) {
- UserRegisterOperation op = USER_REG_OP_BUILDER.register(userID);
- operationList.add(op);
- return op;
- }
-
- }
-
- private class SecurityOperationBuilderFilter implements SecurityOperationBuilder {
-
- @Override
- public RolesConfigurer roles() {
- RolesConfigurer rolesConfigurer = SECURITY_OP_BUILDER.roles();
- operationList.add(rolesConfigurer.getOperation());
- return rolesConfigurer;
- }
-
- @Override
- public UserAuthorizer authorziations() {
- UserAuthorizer userAuthorizer = SECURITY_OP_BUILDER.authorziations();
- operationList.add(userAuthorizer.getOperation());
- return userAuthorizer;
- }
- }
-
- private class DataAccountRegisterOperationBuilderFilter implements DataAccountRegisterOperationBuilder {
-
- @Override
- public DataAccountRegisterOperation register(BlockchainIdentity accountID) {
- DataAccountRegisterOperation op = DATA_ACC_REG_OP_BUILDER.register(accountID);
- operationList.add(op);
- return op;
- }
- }
-
- private class DataAccountKVSetOperationBuilderFilter implements DataAccountKVSetOperationBuilder {
-
- private DataAccountKVSetOperationBuilder innerBuilder;
-
- private DataAccountKVSetOperation op;
-
- public DataAccountKVSetOperationBuilderFilter(Bytes accountAddress) {
- innerBuilder = new DataAccountKVSetOperationBuilderImpl(accountAddress);
- }
-
- @Override
- public DataAccountKVSetOperation getOperation() {
- return innerBuilder.getOperation();
- }
-
- private void addOperation() {
- if (op == null) {
- op = innerBuilder.getOperation();
- operationList.add(op);
- }
- }
-
- @Override
- public DataAccountKVSetOperationBuilder setText(String key, String value, long expVersion) {
- innerBuilder.setText(key, value, expVersion);
- addOperation();
- return this;
- }
-
- @Override
- public DataAccountKVSetOperationBuilder setInt64(String key, long value, long expVersion) {
- innerBuilder.setInt64(key, value, expVersion);
- addOperation();
- return this;
- }
-
- @Override
- public DataAccountKVSetOperationBuilder setBytes(String key, Bytes value, long expVersion) {
- innerBuilder.setBytes(key, value, expVersion);
- addOperation();
- return this;
- }
-
- @Override
- public DataAccountKVSetOperationBuilder setBytes(String key, byte[] value, long expVersion) {
- innerBuilder.setBytes(key, value, expVersion);
- addOperation();
- return this;
- }
-
- @Override
- public DataAccountKVSetOperationBuilder setImage(String key, byte[] value, long expVersion) {
- innerBuilder.setImage(key, value, expVersion);
- addOperation();
- return this;
- }
-
- @Override
- public DataAccountKVSetOperationBuilder setJSON(String key, String value, long expVersion) {
- innerBuilder.setJSON(key, value, expVersion);
- addOperation();
- return this;
- }
-
- @Override
- public DataAccountKVSetOperationBuilder setXML(String key, String value, long expVersion) {
- innerBuilder.setXML(key, value, expVersion);
- addOperation();
- return this;
- }
-
- @Override
- public DataAccountKVSetOperationBuilder setTimestamp(String key, long value, long expVersion) {
- innerBuilder.setTimestamp(key, value, expVersion);
- addOperation();
- return this;
- }
-
- }
-
- private class ContractCodeDeployOperationBuilderFilter implements ContractCodeDeployOperationBuilder {
- @Override
- public ContractCodeDeployOperation deploy(BlockchainIdentity id, byte[] chainCode) {
- ContractCodeDeployOperation op = CONTRACT_CODE_DEPLOY_OP_BUILDER.deploy(id, chainCode);
- operationList.add(op);
- return op;
- }
- }
-
- private class ParticipantRegisterOperationBuilderFilter implements ParticipantRegisterOperationBuilder {
- @Override
- public ParticipantRegisterOperation register(String participantName, BlockchainIdentity participantIdentity, NetworkAddress networkAddress) {
- ParticipantRegisterOperation op = PARTICIPANT_REG_OP_BUILDER.register(participantName, participantIdentity, networkAddress);
- operationList.add(op);
- return op;
- }
- }
-
- private class ParticipantStateUpdateOperationBuilderFilter implements ParticipantStateUpdateOperationBuilder {
- @Override
- public ParticipantStateUpdateOperation update(BlockchainIdentity blockchainIdentity, NetworkAddress networkAddress, ParticipantNodeState participantNodeState) {
- ParticipantStateUpdateOperation op = PARTICIPANT_STATE_UPDATE_OP_BUILDER.update(blockchainIdentity, networkAddress, participantNodeState);
- operationList.add(op);
- return op;
- }
- }
-
- private class ContractEventSendOperationBuilderFilter implements ContractEventSendOperationBuilder {
-
- @Override
- public ContractEventSendOperation send(String address, String event, BytesValueList args) {
- return send(Bytes.fromBase58(address), event, args);
- }
-
- @Override
- public synchronized ContractEventSendOperation send(Bytes address, String event, BytesValueList args) {
- ContractEventSendOpTemplate op = new ContractEventSendOpTemplate(address, event, args);
- operationList.add(op);
- return op;
- }
-
- }
-
- /**
- * 不做任何操作的返回值处理器;
- *
- * @author huanghaiquan
- *
- */
- private static class NullOperationReturnValueHandler implements OperationResultHandle {
-
- private int operationIndex;
-
- public NullOperationReturnValueHandler(int operationIndex) {
- this.operationIndex = operationIndex;
- }
-
- @Override
- public int getOperationIndex() {
- return operationIndex;
- }
-
- @Override
- public Object complete(BytesValue bytesValue) {
- return null;
- }
-
- @Override
- public void complete(Throwable error) {
- }
-
- }
-
-}
+package com.jd.blockchain.transaction;
+
+import com.jd.blockchain.ledger.*;
+import com.jd.blockchain.utils.Bytes;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import com.jd.blockchain.crypto.PubKey;
+import com.jd.blockchain.ledger.*;
+import com.jd.blockchain.utils.Bytes;
+import com.jd.blockchain.utils.net.NetworkAddress;
+
+/**
+ * @author huanghaiquan
+ *
+ */
+public class BlockchainOperationFactory implements ClientOperator, LedgerInitOperator {
+
+ private static final SecurityOperationBuilderImpl SECURITY_OP_BUILDER = new SecurityOperationBuilderImpl();
+
+ private static final LedgerInitOperationBuilderImpl LEDGER_INIT_OP_BUILDER = new LedgerInitOperationBuilderImpl();
+
+ private static final UserRegisterOperationBuilderImpl USER_REG_OP_BUILDER = new UserRegisterOperationBuilderImpl();
+
+ private static final DataAccountRegisterOperationBuilderImpl DATA_ACC_REG_OP_BUILDER = new DataAccountRegisterOperationBuilderImpl();
+
+ private static final ContractCodeDeployOperationBuilderImpl CONTRACT_CODE_DEPLOY_OP_BUILDER = new ContractCodeDeployOperationBuilderImpl();
+
+// private static final ContractEventSendOperationBuilderImpl CONTRACT_EVENT_SEND_OP_BUILDER = new ContractEventSendOperationBuilderImpl();
+
+ private SecurityOperationBuilderFilter securityOpBuilder = new SecurityOperationBuilderFilter();
+
+ private static final ParticipantRegisterOperationBuilderImpl PARTICIPANT_REG_OP_BUILDER = new ParticipantRegisterOperationBuilderImpl();
+
+ private static final ParticipantStateUpdateOperationBuilderImpl PARTICIPANT_STATE_UPDATE_OP_BUILDER = new ParticipantStateUpdateOperationBuilderImpl();
+
+ private LedgerInitOperationBuilder ledgerInitOpBuilder = new LedgerInitOperationBuilderFilter();
+
+ private UserRegisterOperationBuilder userRegOpBuilder = new UserRegisterOperationBuilderFilter();
+
+ private DataAccountRegisterOperationBuilder dataAccRegOpBuilder = new DataAccountRegisterOperationBuilderFilter();
+
+ private ContractCodeDeployOperationBuilder contractCodeDeployOpBuilder = new ContractCodeDeployOperationBuilderFilter();
+
+ private ContractEventSendOperationBuilder contractEventSendOpBuilder = new ContractEventSendOperationBuilderFilter();
+
+ private ContractInvocationProxyBuilder contractInvoProxyBuilder = new ContractInvocationProxyBuilder();
+
+ private ParticipantRegisterOperationBuilder participantRegOpBuilder = new ParticipantRegisterOperationBuilderFilter();
+
+ private ParticipantStateUpdateOperationBuilder participantStateModifyOpBuilder = new ParticipantStateUpdateOperationBuilderFilter();
+
+ // TODO: 暂时只支持单线程情形,未考虑多线程;
+ private List operationList = new ArrayList<>();
+
+ @Override
+ public LedgerInitOperationBuilder ledgers() {
+ return ledgerInitOpBuilder;
+ }
+
+ @Override
+ public SecurityOperationBuilder security() {
+ return securityOpBuilder;
+ }
+
+ @Override
+ public UserRegisterOperationBuilder users() {
+ return userRegOpBuilder;
+ }
+
+ @Override
+ public DataAccountRegisterOperationBuilder dataAccounts() {
+ return dataAccRegOpBuilder;
+ }
+
+ @Override
+ public DataAccountKVSetOperationBuilder dataAccount(String accountAddress) {
+ return new DataAccountKVSetOperationBuilderFilter(Bytes.fromBase58(accountAddress));
+ }
+
+ @Override
+ public DataAccountKVSetOperationBuilder dataAccount(Bytes accountAddress) {
+ return new DataAccountKVSetOperationBuilderFilter(accountAddress);
+ }
+
+ @Override
+ public ContractCodeDeployOperationBuilder contracts() {
+ return contractCodeDeployOpBuilder;
+ }
+
+ public ContractEventSendOperationBuilder contractEvents() {
+ return contractEventSendOpBuilder;
+ }
+
+ @Override
+ public ParticipantRegisterOperationBuilder participants() {return participantRegOpBuilder;}
+
+ @Override
+ public ParticipantStateUpdateOperationBuilder states() {return participantStateModifyOpBuilder;}
+
+ @Override
+ public T contract(String address, Class contractIntf) {
+ return contractInvoProxyBuilder.create(address, contractIntf, contractEventSendOpBuilder);
+ }
+
+ @Override
+ public T contract(Bytes address, Class contractIntf) {
+ return contractInvoProxyBuilder.create(address, contractIntf, contractEventSendOpBuilder);
+ }
+
+ /**
+ * 返回已经定义的操作列表;
+ *
+ * @return
+ */
+ public Collection getOperations() {
+ return operationList;
+ }
+
+ /**
+ * 返回与操作列表对应的返回值处理器;
+ *
+ * @return
+ */
+ public Collection getReturnValuetHandlers() {
+ List resultHandlers = new ArrayList();
+ int index = 0;
+ for (Operation op : operationList) {
+ if (op instanceof ContractEventSendOperation) {
+ // 操作具有返回值,创建对应的结果处理器;
+ ContractEventSendOpTemplate opTemp = (ContractEventSendOpTemplate) op;
+ ContractInvocation invocation = opTemp.getInvocation();
+ OperationResultHandle retnHandler;
+ if (invocation == null) {
+ retnHandler = new NullOperationReturnValueHandler(index);
+ } else {
+ invocation.setOperationIndex(index);
+ retnHandler = invocation;
+ }
+ resultHandlers.add(retnHandler);
+ }
+ index++;
+ }
+
+ return resultHandlers;
+ }
+
+ public void clear() {
+ operationList.clear();
+ }
+
+ // --------------------------------- 内部类型 -----------------------------------
+
+ private class LedgerInitOperationBuilderFilter implements LedgerInitOperationBuilder {
+
+ @Override
+ public LedgerInitOperation create(LedgerInitSetting initSetting) {
+ LedgerInitOperation op = LEDGER_INIT_OP_BUILDER.create(initSetting);
+ operationList.add(op);
+ return op;
+ }
+
+ }
+
+ private class UserRegisterOperationBuilderFilter implements UserRegisterOperationBuilder {
+
+ @Override
+ public UserRegisterOperation register(BlockchainIdentity userID) {
+ UserRegisterOperation op = USER_REG_OP_BUILDER.register(userID);
+ operationList.add(op);
+ return op;
+ }
+
+ }
+
+ private class SecurityOperationBuilderFilter implements SecurityOperationBuilder {
+
+ @Override
+ public RolesConfigurer roles() {
+ RolesConfigurer rolesConfigurer = SECURITY_OP_BUILDER.roles();
+ operationList.add(rolesConfigurer.getOperation());
+ return rolesConfigurer;
+ }
+
+ @Override
+ public UserAuthorizer authorziations() {
+ UserAuthorizer userAuthorizer = SECURITY_OP_BUILDER.authorziations();
+ operationList.add(userAuthorizer.getOperation());
+ return userAuthorizer;
+ }
+ }
+
+ private class DataAccountRegisterOperationBuilderFilter implements DataAccountRegisterOperationBuilder {
+
+ @Override
+ public DataAccountRegisterOperation register(BlockchainIdentity accountID) {
+ DataAccountRegisterOperation op = DATA_ACC_REG_OP_BUILDER.register(accountID);
+ operationList.add(op);
+ return op;
+ }
+ }
+
+ private class DataAccountKVSetOperationBuilderFilter implements DataAccountKVSetOperationBuilder {
+
+ private DataAccountKVSetOperationBuilder innerBuilder;
+
+ private DataAccountKVSetOperation op;
+
+ public DataAccountKVSetOperationBuilderFilter(Bytes accountAddress) {
+ innerBuilder = new DataAccountKVSetOperationBuilderImpl(accountAddress);
+ }
+
+ @Override
+ public DataAccountKVSetOperation getOperation() {
+ return innerBuilder.getOperation();
+ }
+
+ private void addOperation() {
+ if (op == null) {
+ op = innerBuilder.getOperation();
+ operationList.add(op);
+ }
+ }
+
+ @Override
+ public DataAccountKVSetOperationBuilder setText(String key, String value, long expVersion) {
+ innerBuilder.setText(key, value, expVersion);
+ addOperation();
+ return this;
+ }
+
+ @Override
+ public DataAccountKVSetOperationBuilder setInt64(String key, long value, long expVersion) {
+ innerBuilder.setInt64(key, value, expVersion);
+ addOperation();
+ return this;
+ }
+
+ @Override
+ public DataAccountKVSetOperationBuilder setBytes(String key, Bytes value, long expVersion) {
+ innerBuilder.setBytes(key, value, expVersion);
+ addOperation();
+ return this;
+ }
+
+ @Override
+ public DataAccountKVSetOperationBuilder setBytes(String key, byte[] value, long expVersion) {
+ innerBuilder.setBytes(key, value, expVersion);
+ addOperation();
+ return this;
+ }
+
+ @Override
+ public DataAccountKVSetOperationBuilder setImage(String key, byte[] value, long expVersion) {
+ innerBuilder.setImage(key, value, expVersion);
+ addOperation();
+ return this;
+ }
+
+ @Override
+ public DataAccountKVSetOperationBuilder setJSON(String key, String value, long expVersion) {
+ innerBuilder.setJSON(key, value, expVersion);
+ addOperation();
+ return this;
+ }
+
+ @Override
+ public DataAccountKVSetOperationBuilder setXML(String key, String value, long expVersion) {
+ innerBuilder.setXML(key, value, expVersion);
+ addOperation();
+ return this;
+ }
+
+ @Override
+ public DataAccountKVSetOperationBuilder setTimestamp(String key, long value, long expVersion) {
+ innerBuilder.setTimestamp(key, value, expVersion);
+ addOperation();
+ return this;
+ }
+
+ }
+
+ private class ContractCodeDeployOperationBuilderFilter implements ContractCodeDeployOperationBuilder {
+ @Override
+ public ContractCodeDeployOperation deploy(BlockchainIdentity id, byte[] chainCode) {
+ ContractCodeDeployOperation op = CONTRACT_CODE_DEPLOY_OP_BUILDER.deploy(id, chainCode);
+ operationList.add(op);
+ return op;
+ }
+ }
+
+ private class ParticipantRegisterOperationBuilderFilter implements ParticipantRegisterOperationBuilder {
+ @Override
+ public ParticipantRegisterOperation register(String participantName, BlockchainIdentity participantIdentity, NetworkAddress networkAddress) {
+ ParticipantRegisterOperation op = PARTICIPANT_REG_OP_BUILDER.register(participantName, participantIdentity, networkAddress);
+ operationList.add(op);
+ return op;
+ }
+ }
+
+ private class ParticipantStateUpdateOperationBuilderFilter implements ParticipantStateUpdateOperationBuilder {
+ @Override
+ public ParticipantStateUpdateOperation update(BlockchainIdentity blockchainIdentity, NetworkAddress networkAddress, ParticipantNodeState participantNodeState) {
+ ParticipantStateUpdateOperation op = PARTICIPANT_STATE_UPDATE_OP_BUILDER.update(blockchainIdentity, networkAddress, participantNodeState);
+ operationList.add(op);
+ return op;
+ }
+ }
+
+ private class ContractEventSendOperationBuilderFilter implements ContractEventSendOperationBuilder {
+
+ @Override
+ public ContractEventSendOperation send(String address, String event, BytesValueList args) {
+ return send(Bytes.fromBase58(address), event, args);
+ }
+
+ @Override
+ public synchronized ContractEventSendOperation send(Bytes address, String event, BytesValueList args) {
+ ContractEventSendOpTemplate op = new ContractEventSendOpTemplate(address, event, args);
+ operationList.add(op);
+ return op;
+ }
+
+ }
+
+ /**
+ * 不做任何操作的返回值处理器;
+ *
+ * @author huanghaiquan
+ *
+ */
+ private static class NullOperationReturnValueHandler implements OperationResultHandle {
+
+ private int operationIndex;
+
+ public NullOperationReturnValueHandler(int operationIndex) {
+ this.operationIndex = operationIndex;
+ }
+
+ @Override
+ public int getOperationIndex() {
+ return operationIndex;
+ }
+
+ @Override
+ public Object complete(BytesValue bytesValue) {
+ return null;
+ }
+
+ @Override
+ public void complete(Throwable error) {
+ }
+
+ }
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/BlockchainQueryService.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/BlockchainQueryService.java
index f63a7f2a..98694c60 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/BlockchainQueryService.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/BlockchainQueryService.java
@@ -1,330 +1,330 @@
-package com.jd.blockchain.transaction;
-
-import org.springframework.cglib.core.Block;
-
-import com.jd.blockchain.crypto.HashDigest;
-import com.jd.blockchain.ledger.BlockchainIdentity;
-import com.jd.blockchain.ledger.ContractInfo;
-import com.jd.blockchain.ledger.TypedKVEntry;
-import com.jd.blockchain.ledger.KVInfoVO;
-import com.jd.blockchain.ledger.LedgerAdminInfo;
-import com.jd.blockchain.ledger.LedgerBlock;
-import com.jd.blockchain.ledger.LedgerInfo;
-import com.jd.blockchain.ledger.LedgerMetadata;
-import com.jd.blockchain.ledger.LedgerTransaction;
-import com.jd.blockchain.ledger.ParticipantNode;
-import com.jd.blockchain.ledger.Transaction;
-import com.jd.blockchain.ledger.TransactionState;
-import com.jd.blockchain.ledger.UserInfo;
-
-/**
- * 区块链查询器;
- *
- * @author huanghaiquan
- *
- */
-public interface BlockchainQueryService {
-
- /**
- * 返回所有的账本的 hash 列表;
- *
- * 注:账本的 hash 既是该账本的创世区块的 hash;
- *
- * @return 账本 hash 的集合;
- */
- HashDigest[] getLedgerHashs();
-
- /**
- * 获取账本信息;
- *
- * @param ledgerHash
- * @return 账本对象;如果不存在,则返回 null;
- */
- LedgerInfo getLedger(HashDigest ledgerHash);
-
- /**
- * 获取账本信息;
- *
- * @param ledgerHash
- * @return 账本对象;如果不存在,则返回 null;
- */
- LedgerAdminInfo getLedgerAdminInfo(HashDigest ledgerHash);
-
- /**
- * 返回当前账本的参与者信息列表
- *
- * @param ledgerHash
- * @return
- */
- ParticipantNode[] getConsensusParticipants(HashDigest ledgerHash);
-
- /**
- * 返回当前账本的元数据
- *
- * @param ledgerHash
- * @return
- */
- LedgerMetadata getLedgerMetadata(HashDigest ledgerHash);
-
- /**
- * 返回指定账本序号的区块;
- *
- * @param ledgerHash 账本hash;
- * @param height 高度;
- * @return
- */
- LedgerBlock getBlock(HashDigest ledgerHash, long height);
-
- /**
- * 返回指定区块hash的区块;
- *
- * @param ledgerHash 账本hash;
- * @param blockHash 区块hash;
- * @return
- */
- LedgerBlock getBlock(HashDigest ledgerHash, HashDigest blockHash);
-
- /**
- * 返回指定高度的区块中记录的交易总数;
- *
- * @param ledgerHash
- * @param height
- * @return
- */
- long getTransactionCount(HashDigest ledgerHash, long height);
-
- /**
- * 返回指定高度的区块中记录的交易总数;
- *
- * @param ledgerHash
- * @param blockHash
- * @return
- */
- long getTransactionCount(HashDigest ledgerHash, HashDigest blockHash);
-
- /**
- * 返回当前账本的交易总数
- *
- * @param ledgerHash
- * @return
- */
- long getTransactionTotalCount(HashDigest ledgerHash);
-
- /**
- * 返回指定高度的区块中记录的数据账户总数
- *
- * @param ledgerHash
- * @param height
- * @return
- */
- long getDataAccountCount(HashDigest ledgerHash, long height);
-
- /**
- * 返回指定的区块中记录的数据账户总数
- *
- * @param ledgerHash
- * @param blockHash
- * @return
- */
- long getDataAccountCount(HashDigest ledgerHash, HashDigest blockHash);
-
- /**
- * 返回当前账本的数据账户总数
- *
- * @param ledgerHash
- * @return
- */
- long getDataAccountTotalCount(HashDigest ledgerHash);
-
- /**
- * 返回指定高度区块中的用户总数
- *
- * @param ledgerHash
- * @param height
- * @return
- */
- long getUserCount(HashDigest ledgerHash, long height);
-
- /**
- * 返回指定区块中的用户总数
- *
- * @param ledgerHash
- * @param blockHash
- * @return
- */
- long getUserCount(HashDigest ledgerHash, HashDigest blockHash);
-
- /**
- * 返回当前账本的用户总数
- *
- * @param ledgerHash
- * @return
- */
- long getUserTotalCount(HashDigest ledgerHash);
-
- /**
- * 返回指定高度区块中的合约总数
- *
- * @param ledgerHash
- * @param height
- * @return
- */
- long getContractCount(HashDigest ledgerHash, long height);
-
- /**
- * 返回指定区块中的合约总数
- *
- * @param ledgerHash
- * @param blockHash
- * @return
- */
- long getContractCount(HashDigest ledgerHash, HashDigest blockHash);
-
- /**
- * 返回当前账本的合约总数
- *
- * @param ledgerHash
- * @return
- */
- long getContractTotalCount(HashDigest ledgerHash);
-
- /**
- * 分页返回指定账本序号的区块中的交易列表;
- *
- * @param ledgerHash 账本hash;
- * @param height 账本高度;
- * @param fromIndex 开始的记录数;
- * @param count 本次返回的记录数;
- * 最小为1,最大值受到系统参数的限制;
- * 注:通过 {@link #getBlock(String, long)} 方法获得的区块信息中可以得到区块的总交易数
- * {@link Block#getTxCount()};
- * @return
- */
- LedgerTransaction[] getTransactions(HashDigest ledgerHash, long height, int fromIndex, int count);
-
- /**
- * 分页返回指定账本序号的区块中的交易列表;
- *
- * @param ledgerHash 账本hash;
- * @param blockHash 账本高度;
- * @param fromIndex 开始的记录数;
- * @param count 本次返回的记录数;
- * 如果参数值为 -1,则返回全部的记录;
- * 注:通过 {@link #getBlock(String, String)}
- * 方法获得的区块信息中可以得到区块的总交易数 {@link Block#getTxCount()};
- * @return
- */
- LedgerTransaction[] getTransactions(HashDigest ledgerHash, HashDigest blockHash, int fromIndex, int count);
-
- /**
- * 根据交易内容的哈希获取对应的交易记录;
- *
- * @param ledgerHash 账本hash;
- * @param contentHash 交易内容的hash,即交易的 {@link Transaction#getContentHash()} 属性的值;
- * @return
- */
- LedgerTransaction getTransactionByContentHash(HashDigest ledgerHash, HashDigest contentHash);
-
- /**
- * 根据交易内容的哈希获取对应的交易状态;
- *
- * @param ledgerHash 账本hash;
- * @param contentHash 交易内容的hash,即交易的 {@link Transaction#getContentHash()} 属性的值;
- * @return
- */
- TransactionState getTransactionStateByContentHash(HashDigest ledgerHash, HashDigest contentHash);
-
- /**
- * 返回用户信息;
- *
- * @param ledgerHash
- * @param address
- * @return
- */
- UserInfo getUser(HashDigest ledgerHash, String address);
-
- /**
- * 返回数据账户信息;
- *
- * @param ledgerHash
- * @param address
- * @return
- */
- BlockchainIdentity getDataAccount(HashDigest ledgerHash, String address);
-
- /**
- * 返回数据账户中指定的键的最新值;
- *
- * 返回结果的顺序与指定的键的顺序是一致的;
- *
- * 如果某个键不存在,则返回版本为 -1 的数据项;
- *
- * @param ledgerHash
- * @param address
- * @param keys
- * @return
- */
- TypedKVEntry[] getDataEntries(HashDigest ledgerHash, String address, String... keys);
-
- TypedKVEntry[] getDataEntries(HashDigest ledgerHash, String address, KVInfoVO kvInfoVO);
-
- /**
- * 返回指定数据账户中KV数据的总数;
- *
- * @param ledgerHash
- * @param address
- * @return
- */
- long getDataEntriesTotalCount(HashDigest ledgerHash, String address);
-
- /**
- * 返回数据账户中指定序号的最新值; 返回结果的顺序与指定的序号的顺序是一致的;
- *
- * @param ledgerHash 账本hash;
- * @param address 数据账户地址;
- * @param fromIndex 开始的记录数;
- * @param count 本次返回的记录数;
- * 如果参数值为 -1,则返回全部的记录;
- * @return
- */
- TypedKVEntry[] getDataEntries(HashDigest ledgerHash, String address, int fromIndex, int count);
-
- /**
- * 返回合约账户信息;
- *
- * @param ledgerHash
- * @param address
- * @return
- */
- ContractInfo getContract(HashDigest ledgerHash, String address);
-
- /**
- * get users by ledgerHash and its range;
- *
- * @param ledgerHash
- * @param fromIndex
- * @param count
- * @return
- */
- BlockchainIdentity[] getUsers(HashDigest ledgerHash, int fromIndex, int count);
-
- /**
- * get data accounts by ledgerHash and its range;
- *
- * @param ledgerHash
- * @param fromIndex
- * @param count
- * @return
- */
- BlockchainIdentity[] getDataAccounts(HashDigest ledgerHash, int fromIndex, int count);
-
- /**
- * get contract accounts by ledgerHash and its range;
- *
- * @param ledgerHash
- * @param fromIndex
- * @param count
- * @return
- */
- BlockchainIdentity[] getContractAccounts(HashDigest ledgerHash, int fromIndex, int count);
-}
+package com.jd.blockchain.transaction;
+
+import org.springframework.cglib.core.Block;
+
+import com.jd.blockchain.crypto.HashDigest;
+import com.jd.blockchain.ledger.BlockchainIdentity;
+import com.jd.blockchain.ledger.ContractInfo;
+import com.jd.blockchain.ledger.TypedKVEntry;
+import com.jd.blockchain.ledger.KVInfoVO;
+import com.jd.blockchain.ledger.LedgerAdminInfo;
+import com.jd.blockchain.ledger.LedgerBlock;
+import com.jd.blockchain.ledger.LedgerInfo;
+import com.jd.blockchain.ledger.LedgerMetadata;
+import com.jd.blockchain.ledger.LedgerTransaction;
+import com.jd.blockchain.ledger.ParticipantNode;
+import com.jd.blockchain.ledger.Transaction;
+import com.jd.blockchain.ledger.TransactionState;
+import com.jd.blockchain.ledger.UserInfo;
+
+/**
+ * 区块链查询器;
+ *
+ * @author huanghaiquan
+ *
+ */
+public interface BlockchainQueryService {
+
+ /**
+ * 返回所有的账本的 hash 列表;
+ *
+ * 注:账本的 hash 既是该账本的创世区块的 hash;
+ *
+ * @return 账本 hash 的集合;
+ */
+ HashDigest[] getLedgerHashs();
+
+ /**
+ * 获取账本信息;
+ *
+ * @param ledgerHash
+ * @return 账本对象;如果不存在,则返回 null;
+ */
+ LedgerInfo getLedger(HashDigest ledgerHash);
+
+ /**
+ * 获取账本信息;
+ *
+ * @param ledgerHash
+ * @return 账本对象;如果不存在,则返回 null;
+ */
+ LedgerAdminInfo getLedgerAdminInfo(HashDigest ledgerHash);
+
+ /**
+ * 返回当前账本的参与者信息列表
+ *
+ * @param ledgerHash
+ * @return
+ */
+ ParticipantNode[] getConsensusParticipants(HashDigest ledgerHash);
+
+ /**
+ * 返回当前账本的元数据
+ *
+ * @param ledgerHash
+ * @return
+ */
+ LedgerMetadata getLedgerMetadata(HashDigest ledgerHash);
+
+ /**
+ * 返回指定账本序号的区块;
+ *
+ * @param ledgerHash 账本hash;
+ * @param height 高度;
+ * @return
+ */
+ LedgerBlock getBlock(HashDigest ledgerHash, long height);
+
+ /**
+ * 返回指定区块hash的区块;
+ *
+ * @param ledgerHash 账本hash;
+ * @param blockHash 区块hash;
+ * @return
+ */
+ LedgerBlock getBlock(HashDigest ledgerHash, HashDigest blockHash);
+
+ /**
+ * 返回指定高度的区块中记录的交易总数;
+ *
+ * @param ledgerHash
+ * @param height
+ * @return
+ */
+ long getTransactionCount(HashDigest ledgerHash, long height);
+
+ /**
+ * 返回指定高度的区块中记录的交易总数;
+ *
+ * @param ledgerHash
+ * @param blockHash
+ * @return
+ */
+ long getTransactionCount(HashDigest ledgerHash, HashDigest blockHash);
+
+ /**
+ * 返回当前账本的交易总数
+ *
+ * @param ledgerHash
+ * @return
+ */
+ long getTransactionTotalCount(HashDigest ledgerHash);
+
+ /**
+ * 返回指定高度的区块中记录的数据账户总数
+ *
+ * @param ledgerHash
+ * @param height
+ * @return
+ */
+ long getDataAccountCount(HashDigest ledgerHash, long height);
+
+ /**
+ * 返回指定的区块中记录的数据账户总数
+ *
+ * @param ledgerHash
+ * @param blockHash
+ * @return
+ */
+ long getDataAccountCount(HashDigest ledgerHash, HashDigest blockHash);
+
+ /**
+ * 返回当前账本的数据账户总数
+ *
+ * @param ledgerHash
+ * @return
+ */
+ long getDataAccountTotalCount(HashDigest ledgerHash);
+
+ /**
+ * 返回指定高度区块中的用户总数
+ *
+ * @param ledgerHash
+ * @param height
+ * @return
+ */
+ long getUserCount(HashDigest ledgerHash, long height);
+
+ /**
+ * 返回指定区块中的用户总数
+ *
+ * @param ledgerHash
+ * @param blockHash
+ * @return
+ */
+ long getUserCount(HashDigest ledgerHash, HashDigest blockHash);
+
+ /**
+ * 返回当前账本的用户总数
+ *
+ * @param ledgerHash
+ * @return
+ */
+ long getUserTotalCount(HashDigest ledgerHash);
+
+ /**
+ * 返回指定高度区块中的合约总数
+ *
+ * @param ledgerHash
+ * @param height
+ * @return
+ */
+ long getContractCount(HashDigest ledgerHash, long height);
+
+ /**
+ * 返回指定区块中的合约总数
+ *
+ * @param ledgerHash
+ * @param blockHash
+ * @return
+ */
+ long getContractCount(HashDigest ledgerHash, HashDigest blockHash);
+
+ /**
+ * 返回当前账本的合约总数
+ *
+ * @param ledgerHash
+ * @return
+ */
+ long getContractTotalCount(HashDigest ledgerHash);
+
+ /**
+ * 分页返回指定账本序号的区块中的交易列表;
+ *
+ * @param ledgerHash 账本hash;
+ * @param height 账本高度;
+ * @param fromIndex 开始的记录数;
+ * @param count 本次返回的记录数;
+ * 最小为1,最大值受到系统参数的限制;
+ * 注:通过 {@link #getBlock(String, long)} 方法获得的区块信息中可以得到区块的总交易数
+ * {@link Block#getTxCount()};
+ * @return
+ */
+ LedgerTransaction[] getTransactions(HashDigest ledgerHash, long height, int fromIndex, int count);
+
+ /**
+ * 分页返回指定账本序号的区块中的交易列表;
+ *
+ * @param ledgerHash 账本hash;
+ * @param blockHash 账本高度;
+ * @param fromIndex 开始的记录数;
+ * @param count 本次返回的记录数;
+ * 如果参数值为 -1,则返回全部的记录;
+ * 注:通过 {@link #getBlock(String, String)}
+ * 方法获得的区块信息中可以得到区块的总交易数 {@link Block#getTxCount()};
+ * @return
+ */
+ LedgerTransaction[] getTransactions(HashDigest ledgerHash, HashDigest blockHash, int fromIndex, int count);
+
+ /**
+ * 根据交易内容的哈希获取对应的交易记录;
+ *
+ * @param ledgerHash 账本hash;
+ * @param contentHash 交易内容的hash,即交易的 {@link Transaction#getContentHash()} 属性的值;
+ * @return
+ */
+ LedgerTransaction getTransactionByContentHash(HashDigest ledgerHash, HashDigest contentHash);
+
+ /**
+ * 根据交易内容的哈希获取对应的交易状态;
+ *
+ * @param ledgerHash 账本hash;
+ * @param contentHash 交易内容的hash,即交易的 {@link Transaction#getContentHash()} 属性的值;
+ * @return
+ */
+ TransactionState getTransactionStateByContentHash(HashDigest ledgerHash, HashDigest contentHash);
+
+ /**
+ * 返回用户信息;
+ *
+ * @param ledgerHash
+ * @param address
+ * @return
+ */
+ UserInfo getUser(HashDigest ledgerHash, String address);
+
+ /**
+ * 返回数据账户信息;
+ *
+ * @param ledgerHash
+ * @param address
+ * @return
+ */
+ BlockchainIdentity getDataAccount(HashDigest ledgerHash, String address);
+
+ /**
+ * 返回数据账户中指定的键的最新值;
+ *
+ * 返回结果的顺序与指定的键的顺序是一致的;
+ *
+ * 如果某个键不存在,则返回版本为 -1 的数据项;
+ *
+ * @param ledgerHash
+ * @param address
+ * @param keys
+ * @return
+ */
+ TypedKVEntry[] getDataEntries(HashDigest ledgerHash, String address, String... keys);
+
+ TypedKVEntry[] getDataEntries(HashDigest ledgerHash, String address, KVInfoVO kvInfoVO);
+
+ /**
+ * 返回指定数据账户中KV数据的总数;
+ *
+ * @param ledgerHash
+ * @param address
+ * @return
+ */
+ long getDataEntriesTotalCount(HashDigest ledgerHash, String address);
+
+ /**
+ * 返回数据账户中指定序号的最新值; 返回结果的顺序与指定的序号的顺序是一致的;
+ *
+ * @param ledgerHash 账本hash;
+ * @param address 数据账户地址;
+ * @param fromIndex 开始的记录数;
+ * @param count 本次返回的记录数;
+ * 如果参数值为 -1,则返回全部的记录;
+ * @return
+ */
+ TypedKVEntry[] getDataEntries(HashDigest ledgerHash, String address, int fromIndex, int count);
+
+ /**
+ * 返回合约账户信息;
+ *
+ * @param ledgerHash
+ * @param address
+ * @return
+ */
+ ContractInfo getContract(HashDigest ledgerHash, String address);
+
+ /**
+ * get users by ledgerHash and its range;
+ *
+ * @param ledgerHash
+ * @param fromIndex
+ * @param count
+ * @return
+ */
+ BlockchainIdentity[] getUsers(HashDigest ledgerHash, int fromIndex, int count);
+
+ /**
+ * get data accounts by ledgerHash and its range;
+ *
+ * @param ledgerHash
+ * @param fromIndex
+ * @param count
+ * @return
+ */
+ BlockchainIdentity[] getDataAccounts(HashDigest ledgerHash, int fromIndex, int count);
+
+ /**
+ * get contract accounts by ledgerHash and its range;
+ *
+ * @param ledgerHash
+ * @param fromIndex
+ * @param count
+ * @return
+ */
+ BlockchainIdentity[] getContractAccounts(HashDigest ledgerHash, int fromIndex, int count);
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractCodeDeployOpTemplate.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractCodeDeployOpTemplate.java
index 4da74638..61ec8cc8 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractCodeDeployOpTemplate.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractCodeDeployOpTemplate.java
@@ -1,41 +1,41 @@
-package com.jd.blockchain.transaction;
-
-import com.jd.blockchain.binaryproto.DataContractRegistry;
-import com.jd.blockchain.ledger.BlockchainIdentity;
-import com.jd.blockchain.ledger.ContractCodeDeployOperation;
-import com.jd.blockchain.ledger.DigitalSignature;
-
-public class ContractCodeDeployOpTemplate implements ContractCodeDeployOperation {
- static {
- DataContractRegistry.register(ContractCodeDeployOperation.class);
- }
-
- private BlockchainIdentity contractID;
-
- private byte[] chainCode;
-
- public ContractCodeDeployOpTemplate() {
- }
-
- public ContractCodeDeployOpTemplate(BlockchainIdentity contractID, byte[] chainCode) {
- this.contractID = contractID;
- this.chainCode = chainCode;
- }
-
- @Override
- public BlockchainIdentity getContractID() {
- return contractID;
- }
-
- @Override
- public byte[] getChainCode() {
- return chainCode;
- }
-
- @Override
- public DigitalSignature getAddressSignature() {
- // TODO Auto-generated method stub
- return null;
- }
-
-}
+package com.jd.blockchain.transaction;
+
+import com.jd.blockchain.binaryproto.DataContractRegistry;
+import com.jd.blockchain.ledger.BlockchainIdentity;
+import com.jd.blockchain.ledger.ContractCodeDeployOperation;
+import com.jd.blockchain.ledger.DigitalSignature;
+
+public class ContractCodeDeployOpTemplate implements ContractCodeDeployOperation {
+ static {
+ DataContractRegistry.register(ContractCodeDeployOperation.class);
+ }
+
+ private BlockchainIdentity contractID;
+
+ private byte[] chainCode;
+
+ public ContractCodeDeployOpTemplate() {
+ }
+
+ public ContractCodeDeployOpTemplate(BlockchainIdentity contractID, byte[] chainCode) {
+ this.contractID = contractID;
+ this.chainCode = chainCode;
+ }
+
+ @Override
+ public BlockchainIdentity getContractID() {
+ return contractID;
+ }
+
+ @Override
+ public byte[] getChainCode() {
+ return chainCode;
+ }
+
+ @Override
+ public DigitalSignature getAddressSignature() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractCodeDeployOperationBuilder.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractCodeDeployOperationBuilder.java
index ff2c18fb..a75a34b9 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractCodeDeployOperationBuilder.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractCodeDeployOperationBuilder.java
@@ -1,19 +1,19 @@
-package com.jd.blockchain.transaction;
-
-import com.jd.blockchain.ledger.BlockchainIdentity;
-import com.jd.blockchain.ledger.ContractCodeDeployOperation;
-
-public interface ContractCodeDeployOperationBuilder {
-
- /**
- * 部署合约;
- *
- * @param id
- * 区块链身份;
- * @param chainCode
- * 合约应用的字节代码;
- * @return
- */
- ContractCodeDeployOperation deploy(BlockchainIdentity id, byte[] chainCode);
-
-}
+package com.jd.blockchain.transaction;
+
+import com.jd.blockchain.ledger.BlockchainIdentity;
+import com.jd.blockchain.ledger.ContractCodeDeployOperation;
+
+public interface ContractCodeDeployOperationBuilder {
+
+ /**
+ * 部署合约;
+ *
+ * @param id
+ * 区块链身份;
+ * @param chainCode
+ * 合约应用的字节代码;
+ * @return
+ */
+ ContractCodeDeployOperation deploy(BlockchainIdentity id, byte[] chainCode);
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractCodeDeployOperationBuilderImpl.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractCodeDeployOperationBuilderImpl.java
index a0c2bba4..fe69879c 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractCodeDeployOperationBuilderImpl.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractCodeDeployOperationBuilderImpl.java
@@ -1,14 +1,14 @@
-package com.jd.blockchain.transaction;
-
-import com.jd.blockchain.ledger.BlockchainIdentity;
-import com.jd.blockchain.ledger.ContractCodeDeployOperation;
-
-public class ContractCodeDeployOperationBuilderImpl implements ContractCodeDeployOperationBuilder{
-
- @Override
- public ContractCodeDeployOperation deploy(BlockchainIdentity id, byte[] chainCode) {
- ContractCodeDeployOpTemplate op = new ContractCodeDeployOpTemplate(id, chainCode);
- return op;
- }
-
-}
+package com.jd.blockchain.transaction;
+
+import com.jd.blockchain.ledger.BlockchainIdentity;
+import com.jd.blockchain.ledger.ContractCodeDeployOperation;
+
+public class ContractCodeDeployOperationBuilderImpl implements ContractCodeDeployOperationBuilder{
+
+ @Override
+ public ContractCodeDeployOperation deploy(BlockchainIdentity id, byte[] chainCode) {
+ ContractCodeDeployOpTemplate op = new ContractCodeDeployOpTemplate(id, chainCode);
+ return op;
+ }
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractEventSendOperationBuilder.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractEventSendOperationBuilder.java
index 675fd8d6..48124243 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractEventSendOperationBuilder.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractEventSendOperationBuilder.java
@@ -1,24 +1,24 @@
-package com.jd.blockchain.transaction;
-
-import com.jd.blockchain.ledger.BytesValueList;
-import com.jd.blockchain.ledger.ContractEventSendOperation;
-import com.jd.blockchain.utils.Bytes;
-
-public interface ContractEventSendOperationBuilder {
-
- /**
- * @param address 合约地址;
- * @param event 事件名;
- * @param args 事件参数;
- * @return
- */
- ContractEventSendOperation send(String address, String event, BytesValueList args);
-
- /**
- * @param address 合约地址;
- * @param event 事件名;
- * @param args 事件参数;
- * @return
- */
- ContractEventSendOperation send(Bytes address, String event, BytesValueList args);
-}
+package com.jd.blockchain.transaction;
+
+import com.jd.blockchain.ledger.BytesValueList;
+import com.jd.blockchain.ledger.ContractEventSendOperation;
+import com.jd.blockchain.utils.Bytes;
+
+public interface ContractEventSendOperationBuilder {
+
+ /**
+ * @param address 合约地址;
+ * @param event 事件名;
+ * @param args 事件参数;
+ * @return
+ */
+ ContractEventSendOperation send(String address, String event, BytesValueList args);
+
+ /**
+ * @param address 合约地址;
+ * @param event 事件名;
+ * @param args 事件参数;
+ * @return
+ */
+ ContractEventSendOperation send(Bytes address, String event, BytesValueList args);
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractEventSendOperationBuilderImpl.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractEventSendOperationBuilderImpl.java
index faae0029..96533720 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractEventSendOperationBuilderImpl.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractEventSendOperationBuilderImpl.java
@@ -1,21 +1,21 @@
-//package com.jd.blockchain.transaction;
-//
-//import com.jd.blockchain.ledger.ContractEventSendOperation;
-//import com.jd.blockchain.utils.Bytes;
-//
-//@Deprecated
-//class ContractEventSendOperationBuilderImpl implements ContractEventSendOperationBuilder {
-//
-// @Override
-// public ContractEventSendOperation send(String address, String event, byte[] args) {
-// ContractEventSendOpTemplate op = new ContractEventSendOpTemplate(Bytes.fromBase58(address), event, args);
-// return op;
-// }
-//
-// @Override
-// public ContractEventSendOperation send(Bytes address, String event, byte[] args) {
-// ContractEventSendOpTemplate op = new ContractEventSendOpTemplate(address, event, args);
-// return op;
-// }
-//
-//}
+//package com.jd.blockchain.transaction;
+//
+//import com.jd.blockchain.ledger.ContractEventSendOperation;
+//import com.jd.blockchain.utils.Bytes;
+//
+//@Deprecated
+//class ContractEventSendOperationBuilderImpl implements ContractEventSendOperationBuilder {
+//
+// @Override
+// public ContractEventSendOperation send(String address, String event, byte[] args) {
+// ContractEventSendOpTemplate op = new ContractEventSendOpTemplate(Bytes.fromBase58(address), event, args);
+// return op;
+// }
+//
+// @Override
+// public ContractEventSendOperation send(Bytes address, String event, byte[] args) {
+// ContractEventSendOpTemplate op = new ContractEventSendOpTemplate(address, event, args);
+// return op;
+// }
+//
+//}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractInvocationProxyBuilder.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractInvocationProxyBuilder.java
index e5e7b947..a536e5ac 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractInvocationProxyBuilder.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ContractInvocationProxyBuilder.java
@@ -1,44 +1,44 @@
-package com.jd.blockchain.transaction;
-
-import java.lang.reflect.Proxy;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import com.jd.blockchain.contract.ContractType;
-import com.jd.blockchain.utils.Bytes;
-
-/**
- * 合约调用代理的构建器;
- *
- * @author huanghaiquan
- *
- */
-public class ContractInvocationProxyBuilder {
-
- private Map, ContractType> contractTypes = new ConcurrentHashMap<>();
-
- public T create(String address, Class contractIntf, ContractEventSendOperationBuilder contractEventBuilder) {
- return create(Bytes.fromBase58(address), contractIntf, contractEventBuilder);
- }
-
- @SuppressWarnings("unchecked")
- public T create(Bytes address, Class contractIntf, ContractEventSendOperationBuilder contractEventBuilder) {
- ContractType contractType = resolveContractType(contractIntf);
-
- ContractInvocationHandler proxyHandler = new ContractInvocationHandler(address, contractType, contractEventBuilder);
-
- T proxy = (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
- new Class>[] { contractIntf }, proxyHandler);
- return proxy;
- }
-
- private ContractType resolveContractType(Class> contractIntf) {
- ContractType contractType = contractTypes.get(contractIntf);
- if (contractType != null) {
- return contractType;
- }
- ContractType ct = ContractType.resolve(contractIntf);
- contractTypes.put(contractIntf, ct);
- return ct;
- }
-}
+package com.jd.blockchain.transaction;
+
+import java.lang.reflect.Proxy;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import com.jd.blockchain.contract.ContractType;
+import com.jd.blockchain.utils.Bytes;
+
+/**
+ * 合约调用代理的构建器;
+ *
+ * @author huanghaiquan
+ *
+ */
+public class ContractInvocationProxyBuilder {
+
+ private Map, ContractType> contractTypes = new ConcurrentHashMap<>();
+
+ public T create(String address, Class contractIntf, ContractEventSendOperationBuilder contractEventBuilder) {
+ return create(Bytes.fromBase58(address), contractIntf, contractEventBuilder);
+ }
+
+ @SuppressWarnings("unchecked")
+ public T create(Bytes address, Class contractIntf, ContractEventSendOperationBuilder contractEventBuilder) {
+ ContractType contractType = resolveContractType(contractIntf);
+
+ ContractInvocationHandler proxyHandler = new ContractInvocationHandler(address, contractType, contractEventBuilder);
+
+ T proxy = (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
+ new Class>[] { contractIntf }, proxyHandler);
+ return proxy;
+ }
+
+ private ContractType resolveContractType(Class> contractIntf) {
+ ContractType contractType = contractTypes.get(contractIntf);
+ if (contractType != null) {
+ return contractType;
+ }
+ ContractType ct = ContractType.resolve(contractIntf);
+ contractTypes.put(contractIntf, ct);
+ return ct;
+ }
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountKVSetOpTemplate.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountKVSetOpTemplate.java
index a9873c4c..4154761a 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountKVSetOpTemplate.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountKVSetOpTemplate.java
@@ -1,65 +1,65 @@
-package com.jd.blockchain.transaction;
-
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-import com.jd.blockchain.binaryproto.DataContractRegistry;
-import com.jd.blockchain.ledger.BytesValue;
-import com.jd.blockchain.ledger.DataAccountKVSetOperation;
-import com.jd.blockchain.utils.Bytes;
-
-public class DataAccountKVSetOpTemplate implements DataAccountKVSetOperation {
- static {
- DataContractRegistry.register(DataAccountKVSetOperation.class);
- }
-
- private Bytes accountAddress;
-
- private Map kvset = new LinkedHashMap<>();
-
- public DataAccountKVSetOpTemplate() {
- }
-
- public DataAccountKVSetOpTemplate(Bytes accountAddress) {
- this.accountAddress = accountAddress;
- }
-
- public DataAccountKVSetOpTemplate(Bytes accountAddress, Map kvset) {
- this.accountAddress = accountAddress;
- this.kvset = kvset;
- }
-
- @Override
- public Bytes getAccountAddress() {
- return accountAddress;
- }
-
- @Override
- public KVWriteEntry[] getWriteSet() {
- return kvset.values().toArray(new KVWriteEntry[kvset.size()]);
- }
-
- public void setWriteSet(Object[] kvEntries) {
- for (Object object : kvEntries) {
- KVWriteEntry kvEntry = (KVWriteEntry) object;
- set(kvEntry.getKey(), kvEntry.getValue(), kvEntry.getExpectedVersion());
- }
- return;
- }
-
- public void set(String key, BytesValue value, long expVersion) {
- if (kvset.containsKey(key)) {
- throw new IllegalArgumentException("Cann't set the same key repeatedly!");
- }
- KVData kvdata = new KVData(key, value, expVersion);
- kvset.put(key, kvdata);
- }
-
- public void set(KVData kvData) {
- if (kvset.containsKey(kvData.getKey())) {
- throw new IllegalArgumentException("Cann't set the same key repeatedly!");
- }
- kvset.put(kvData.getKey(), kvData);
- }
-
-}
+package com.jd.blockchain.transaction;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import com.jd.blockchain.binaryproto.DataContractRegistry;
+import com.jd.blockchain.ledger.BytesValue;
+import com.jd.blockchain.ledger.DataAccountKVSetOperation;
+import com.jd.blockchain.utils.Bytes;
+
+public class DataAccountKVSetOpTemplate implements DataAccountKVSetOperation {
+ static {
+ DataContractRegistry.register(DataAccountKVSetOperation.class);
+ }
+
+ private Bytes accountAddress;
+
+ private Map kvset = new LinkedHashMap<>();
+
+ public DataAccountKVSetOpTemplate() {
+ }
+
+ public DataAccountKVSetOpTemplate(Bytes accountAddress) {
+ this.accountAddress = accountAddress;
+ }
+
+ public DataAccountKVSetOpTemplate(Bytes accountAddress, Map kvset) {
+ this.accountAddress = accountAddress;
+ this.kvset = kvset;
+ }
+
+ @Override
+ public Bytes getAccountAddress() {
+ return accountAddress;
+ }
+
+ @Override
+ public KVWriteEntry[] getWriteSet() {
+ return kvset.values().toArray(new KVWriteEntry[kvset.size()]);
+ }
+
+ public void setWriteSet(Object[] kvEntries) {
+ for (Object object : kvEntries) {
+ KVWriteEntry kvEntry = (KVWriteEntry) object;
+ set(kvEntry.getKey(), kvEntry.getValue(), kvEntry.getExpectedVersion());
+ }
+ return;
+ }
+
+ public void set(String key, BytesValue value, long expVersion) {
+ if (kvset.containsKey(key)) {
+ throw new IllegalArgumentException("Cann't set the same key repeatedly!");
+ }
+ KVData kvdata = new KVData(key, value, expVersion);
+ kvset.put(key, kvdata);
+ }
+
+ public void set(KVData kvData) {
+ if (kvset.containsKey(kvData.getKey())) {
+ throw new IllegalArgumentException("Cann't set the same key repeatedly!");
+ }
+ kvset.put(kvData.getKey(), kvData);
+ }
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountKVSetOperationBuilder.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountKVSetOperationBuilder.java
index f7c9ae8f..5a94e02f 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountKVSetOperationBuilder.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountKVSetOperationBuilder.java
@@ -1,151 +1,151 @@
-package com.jd.blockchain.transaction;
-
-import com.jd.blockchain.ledger.DataAccountKVSetOperation;
-import com.jd.blockchain.utils.Bytes;
-
-/**
- * @author huanghaiquan
- *
- */
-public interface DataAccountKVSetOperationBuilder {
-
- /**
- * 数据账户的KV写入操作;
- *
- * @return
- */
- DataAccountKVSetOperation getOperation();
-
-// /**
-// * 写入字节数组;
-// *
-// * @param key
-// * 键;
-// * @param value
-// * 值;byte[]格式
-// * @param expVersion
-// * 预期的当前版本;如果版本不匹配,则写入失败;
-// * @return
-// */
-// @Deprecated
-// DataAccountKVSetOperationBuilder set(String key, byte[] value, long expVersion);
-
- /**
- * 写入字节数组;
- *
- * @param key
- * 键;
- * @param value
- * 值;byte[]格式
- * @param expVersion
- * 预期的当前版本;如果版本不匹配,则写入失败;
- * @return
- */
- DataAccountKVSetOperationBuilder setBytes(String key, byte[] value, long expVersion);
-
- /**
- * 写入字节数组;
- *
- * @param key
- * 键;
- * @param value
- * 值;Bytes格式
- * @param expVersion
- * 预期的当前版本;如果版本不匹配,则写入失败;
- * @return
- */
- DataAccountKVSetOperationBuilder setBytes(String key, Bytes value, long expVersion);
-
- /**
- * 写入键值;
- *
- * @param key
- * 键;
- * @param value
- * 值;String格式
- * @param expVersion
- * 预期的当前版本;如果版本不匹配,则写入失败;
- * @return
- */
- DataAccountKVSetOperationBuilder setImage(String key, byte[] value, long expVersion);
-
-// /**
-// * 写入文本键值;
-// *
-// * @param key
-// * 键;
-// * @param value
-// * 值;String格式
-// * @param expVersion
-// * 预期的当前版本;如果版本不匹配,则写入失败;
-// * @return
-// */
-// @Deprecated
-// DataAccountKVSetOperationBuilder set(String key, String value, long expVersion);
-
- /**
- * 写入文本键值;
- *
- * @param key
- * 键;
- * @param value
- * 值;String格式
- * @param expVersion
- * 预期的当前版本;如果版本不匹配,则写入失败;
- * @return
- */
- DataAccountKVSetOperationBuilder setText(String key, String value, long expVersion);
-
- /**
- * 写入JSON键值;
- *
- * @param key
- * 键;
- * @param value
- * 值;String格式
- * @param expVersion
- * 预期的当前版本;如果版本不匹配,则写入失败;
- * @return
- */
- DataAccountKVSetOperationBuilder setJSON(String key, String value, long expVersion);
-
- /**
- * 写入XML键值;
- *
- * @param key
- * 键;
- * @param value
- * 值;String格式
- * @param expVersion
- * 预期的当前版本;如果版本不匹配,则写入失败;
- * @return
- */
- DataAccountKVSetOperationBuilder setXML(String key, String value, long expVersion);
-
- /**
- * 写入64位整数;
- *
- * @param key
- * 键;
- * @param value
- * 值;long格式
- * @param expVersion
- * 预期的当前版本;如果版本不匹配,则写入失败;
- * @return
- */
- DataAccountKVSetOperationBuilder setInt64(String key, long value, long expVersion);
-
- /**
- * 写入时间戳;
- *
- * @param key
- * 键;
- * @param value
- * 值;long格式
- * @param expVersion
- * 预期的当前版本;如果版本不匹配,则写入失败;
- * @return
- */
- DataAccountKVSetOperationBuilder setTimestamp(String key, long value, long expVersion);
-
-}
+package com.jd.blockchain.transaction;
+
+import com.jd.blockchain.ledger.DataAccountKVSetOperation;
+import com.jd.blockchain.utils.Bytes;
+
+/**
+ * @author huanghaiquan
+ *
+ */
+public interface DataAccountKVSetOperationBuilder {
+
+ /**
+ * 数据账户的KV写入操作;
+ *
+ * @return
+ */
+ DataAccountKVSetOperation getOperation();
+
+// /**
+// * 写入字节数组;
+// *
+// * @param key
+// * 键;
+// * @param value
+// * 值;byte[]格式
+// * @param expVersion
+// * 预期的当前版本;如果版本不匹配,则写入失败;
+// * @return
+// */
+// @Deprecated
+// DataAccountKVSetOperationBuilder set(String key, byte[] value, long expVersion);
+
+ /**
+ * 写入字节数组;
+ *
+ * @param key
+ * 键;
+ * @param value
+ * 值;byte[]格式
+ * @param expVersion
+ * 预期的当前版本;如果版本不匹配,则写入失败;
+ * @return
+ */
+ DataAccountKVSetOperationBuilder setBytes(String key, byte[] value, long expVersion);
+
+ /**
+ * 写入字节数组;
+ *
+ * @param key
+ * 键;
+ * @param value
+ * 值;Bytes格式
+ * @param expVersion
+ * 预期的当前版本;如果版本不匹配,则写入失败;
+ * @return
+ */
+ DataAccountKVSetOperationBuilder setBytes(String key, Bytes value, long expVersion);
+
+ /**
+ * 写入键值;
+ *
+ * @param key
+ * 键;
+ * @param value
+ * 值;String格式
+ * @param expVersion
+ * 预期的当前版本;如果版本不匹配,则写入失败;
+ * @return
+ */
+ DataAccountKVSetOperationBuilder setImage(String key, byte[] value, long expVersion);
+
+// /**
+// * 写入文本键值;
+// *
+// * @param key
+// * 键;
+// * @param value
+// * 值;String格式
+// * @param expVersion
+// * 预期的当前版本;如果版本不匹配,则写入失败;
+// * @return
+// */
+// @Deprecated
+// DataAccountKVSetOperationBuilder set(String key, String value, long expVersion);
+
+ /**
+ * 写入文本键值;
+ *
+ * @param key
+ * 键;
+ * @param value
+ * 值;String格式
+ * @param expVersion
+ * 预期的当前版本;如果版本不匹配,则写入失败;
+ * @return
+ */
+ DataAccountKVSetOperationBuilder setText(String key, String value, long expVersion);
+
+ /**
+ * 写入JSON键值;
+ *
+ * @param key
+ * 键;
+ * @param value
+ * 值;String格式
+ * @param expVersion
+ * 预期的当前版本;如果版本不匹配,则写入失败;
+ * @return
+ */
+ DataAccountKVSetOperationBuilder setJSON(String key, String value, long expVersion);
+
+ /**
+ * 写入XML键值;
+ *
+ * @param key
+ * 键;
+ * @param value
+ * 值;String格式
+ * @param expVersion
+ * 预期的当前版本;如果版本不匹配,则写入失败;
+ * @return
+ */
+ DataAccountKVSetOperationBuilder setXML(String key, String value, long expVersion);
+
+ /**
+ * 写入64位整数;
+ *
+ * @param key
+ * 键;
+ * @param value
+ * 值;long格式
+ * @param expVersion
+ * 预期的当前版本;如果版本不匹配,则写入失败;
+ * @return
+ */
+ DataAccountKVSetOperationBuilder setInt64(String key, long value, long expVersion);
+
+ /**
+ * 写入时间戳;
+ *
+ * @param key
+ * 键;
+ * @param value
+ * 值;long格式
+ * @param expVersion
+ * 预期的当前版本;如果版本不匹配,则写入失败;
+ * @return
+ */
+ DataAccountKVSetOperationBuilder setTimestamp(String key, long value, long expVersion);
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountKVSetOperationBuilderImpl.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountKVSetOperationBuilderImpl.java
index cec540c9..3992fefb 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountKVSetOperationBuilderImpl.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountKVSetOperationBuilderImpl.java
@@ -1,88 +1,88 @@
-package com.jd.blockchain.transaction;
-
-import com.jd.blockchain.ledger.BytesValue;
-import com.jd.blockchain.ledger.TypedValue;
-import com.jd.blockchain.ledger.DataAccountKVSetOperation;
-import com.jd.blockchain.utils.Bytes;
-
-public class DataAccountKVSetOperationBuilderImpl implements DataAccountKVSetOperationBuilder {
-
- private DataAccountKVSetOpTemplate operation;
-
- public DataAccountKVSetOperationBuilderImpl(Bytes accountAddress) {
- operation = new DataAccountKVSetOpTemplate(accountAddress);
- }
-
- @Override
- public DataAccountKVSetOperation getOperation() {
- return operation;
- }
-
-// @Deprecated
-// @Override
-// public DataAccountKVSetOperationBuilder set(String key, byte[] value, long expVersion) {
-// return setBytes(key, value, expVersion);
-// }
-
- @Override
- public DataAccountKVSetOperationBuilder setBytes(String key, byte[] value, long expVersion) {
- BytesValue bytesValue = TypedValue.fromBytes(value);
- operation.set(key, bytesValue, expVersion);
- return this;
- }
-
- @Override
- public DataAccountKVSetOperationBuilder setImage(String key, byte[] value, long expVersion) {
- BytesValue bytesValue = TypedValue.fromImage(value);
- operation.set(key, bytesValue, expVersion);
- return this;
- }
-
-// @Override
-// public DataAccountKVSetOperationBuilder set(String key, String value, long expVersion) {
-// return setText(key, value, expVersion);
-// }
-
- @Override
- public DataAccountKVSetOperationBuilder setText(String key, String value, long expVersion) {
- BytesValue bytesValue = TypedValue.fromText(value);
- operation.set(key, bytesValue, expVersion);
- return this;
- }
-
- @Override
- public DataAccountKVSetOperationBuilder setBytes(String key, Bytes value, long expVersion) {
- BytesValue bytesValue = TypedValue.fromBytes(value);
- operation.set(key, bytesValue, expVersion);
- return this;
- }
-
- @Override
- public DataAccountKVSetOperationBuilder setInt64(String key, long value, long expVersion) {
- BytesValue bytesValue = TypedValue.fromInt64(value);
- operation.set(key, bytesValue, expVersion);
- return this;
- }
-
- @Override
- public DataAccountKVSetOperationBuilder setJSON(String key, String value, long expVersion) {
- BytesValue bytesValue = TypedValue.fromJSON(value);
- operation.set(key, bytesValue, expVersion);
- return this;
- }
-
- @Override
- public DataAccountKVSetOperationBuilder setXML(String key, String value, long expVersion) {
- BytesValue bytesValue = TypedValue.fromXML(value);
- operation.set(key, bytesValue, expVersion);
- return this;
- }
-
- @Override
- public DataAccountKVSetOperationBuilder setTimestamp(String key, long value, long expVersion) {
- BytesValue bytesValue = TypedValue.fromTimestamp(value);
- operation.set(key, bytesValue, expVersion);
- return this;
- }
-
-}
+package com.jd.blockchain.transaction;
+
+import com.jd.blockchain.ledger.BytesValue;
+import com.jd.blockchain.ledger.TypedValue;
+import com.jd.blockchain.ledger.DataAccountKVSetOperation;
+import com.jd.blockchain.utils.Bytes;
+
+public class DataAccountKVSetOperationBuilderImpl implements DataAccountKVSetOperationBuilder {
+
+ private DataAccountKVSetOpTemplate operation;
+
+ public DataAccountKVSetOperationBuilderImpl(Bytes accountAddress) {
+ operation = new DataAccountKVSetOpTemplate(accountAddress);
+ }
+
+ @Override
+ public DataAccountKVSetOperation getOperation() {
+ return operation;
+ }
+
+// @Deprecated
+// @Override
+// public DataAccountKVSetOperationBuilder set(String key, byte[] value, long expVersion) {
+// return setBytes(key, value, expVersion);
+// }
+
+ @Override
+ public DataAccountKVSetOperationBuilder setBytes(String key, byte[] value, long expVersion) {
+ BytesValue bytesValue = TypedValue.fromBytes(value);
+ operation.set(key, bytesValue, expVersion);
+ return this;
+ }
+
+ @Override
+ public DataAccountKVSetOperationBuilder setImage(String key, byte[] value, long expVersion) {
+ BytesValue bytesValue = TypedValue.fromImage(value);
+ operation.set(key, bytesValue, expVersion);
+ return this;
+ }
+
+// @Override
+// public DataAccountKVSetOperationBuilder set(String key, String value, long expVersion) {
+// return setText(key, value, expVersion);
+// }
+
+ @Override
+ public DataAccountKVSetOperationBuilder setText(String key, String value, long expVersion) {
+ BytesValue bytesValue = TypedValue.fromText(value);
+ operation.set(key, bytesValue, expVersion);
+ return this;
+ }
+
+ @Override
+ public DataAccountKVSetOperationBuilder setBytes(String key, Bytes value, long expVersion) {
+ BytesValue bytesValue = TypedValue.fromBytes(value);
+ operation.set(key, bytesValue, expVersion);
+ return this;
+ }
+
+ @Override
+ public DataAccountKVSetOperationBuilder setInt64(String key, long value, long expVersion) {
+ BytesValue bytesValue = TypedValue.fromInt64(value);
+ operation.set(key, bytesValue, expVersion);
+ return this;
+ }
+
+ @Override
+ public DataAccountKVSetOperationBuilder setJSON(String key, String value, long expVersion) {
+ BytesValue bytesValue = TypedValue.fromJSON(value);
+ operation.set(key, bytesValue, expVersion);
+ return this;
+ }
+
+ @Override
+ public DataAccountKVSetOperationBuilder setXML(String key, String value, long expVersion) {
+ BytesValue bytesValue = TypedValue.fromXML(value);
+ operation.set(key, bytesValue, expVersion);
+ return this;
+ }
+
+ @Override
+ public DataAccountKVSetOperationBuilder setTimestamp(String key, long value, long expVersion) {
+ BytesValue bytesValue = TypedValue.fromTimestamp(value);
+ operation.set(key, bytesValue, expVersion);
+ return this;
+ }
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountRegisterOpTemplate.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountRegisterOpTemplate.java
index ffcbd455..d6c3591d 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountRegisterOpTemplate.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountRegisterOpTemplate.java
@@ -1,34 +1,34 @@
-package com.jd.blockchain.transaction;
-
-import com.jd.blockchain.binaryproto.DataContractRegistry;
-import com.jd.blockchain.ledger.BlockchainIdentity;
-import com.jd.blockchain.ledger.DataAccountKVSetOperation;
-import com.jd.blockchain.ledger.DataAccountRegisterOperation;
-import com.jd.blockchain.ledger.DigitalSignature;
-
-public class DataAccountRegisterOpTemplate implements DataAccountRegisterOperation {
- static {
- DataContractRegistry.register(DataAccountKVSetOperation.class);
- }
-
- private BlockchainIdentity accountID;
-
- public DataAccountRegisterOpTemplate() {
- }
-
- public DataAccountRegisterOpTemplate(BlockchainIdentity accountID) {
- this.accountID = accountID;
- }
-
- @Override
- public BlockchainIdentity getAccountID() {
- return accountID;
- }
-
- @Override
- public DigitalSignature getAddressSignature() {
- // TODO Auto-generated method stub
- return null;
- }
-
-}
+package com.jd.blockchain.transaction;
+
+import com.jd.blockchain.binaryproto.DataContractRegistry;
+import com.jd.blockchain.ledger.BlockchainIdentity;
+import com.jd.blockchain.ledger.DataAccountKVSetOperation;
+import com.jd.blockchain.ledger.DataAccountRegisterOperation;
+import com.jd.blockchain.ledger.DigitalSignature;
+
+public class DataAccountRegisterOpTemplate implements DataAccountRegisterOperation {
+ static {
+ DataContractRegistry.register(DataAccountKVSetOperation.class);
+ }
+
+ private BlockchainIdentity accountID;
+
+ public DataAccountRegisterOpTemplate() {
+ }
+
+ public DataAccountRegisterOpTemplate(BlockchainIdentity accountID) {
+ this.accountID = accountID;
+ }
+
+ @Override
+ public BlockchainIdentity getAccountID() {
+ return accountID;
+ }
+
+ @Override
+ public DigitalSignature getAddressSignature() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountRegisterOperationBuilder.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountRegisterOperationBuilder.java
index ca248fc4..65af0827 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountRegisterOperationBuilder.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountRegisterOperationBuilder.java
@@ -1,14 +1,14 @@
-package com.jd.blockchain.transaction;
-
-import com.jd.blockchain.ledger.BlockchainIdentity;
-import com.jd.blockchain.ledger.DataAccountRegisterOperation;
-
-public interface DataAccountRegisterOperationBuilder {
-
- /**
- * @param id
- * @return
- */
- DataAccountRegisterOperation register(BlockchainIdentity id);
-
-}
+package com.jd.blockchain.transaction;
+
+import com.jd.blockchain.ledger.BlockchainIdentity;
+import com.jd.blockchain.ledger.DataAccountRegisterOperation;
+
+public interface DataAccountRegisterOperationBuilder {
+
+ /**
+ * @param id
+ * @return
+ */
+ DataAccountRegisterOperation register(BlockchainIdentity id);
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountRegisterOperationBuilderImpl.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountRegisterOperationBuilderImpl.java
index eba6b97d..56271e6f 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountRegisterOperationBuilderImpl.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DataAccountRegisterOperationBuilderImpl.java
@@ -1,15 +1,15 @@
-package com.jd.blockchain.transaction;
-
-import com.jd.blockchain.ledger.BlockchainIdentity;
-import com.jd.blockchain.ledger.DataAccountRegisterOperation;
-
-public class DataAccountRegisterOperationBuilderImpl implements DataAccountRegisterOperationBuilder{
-
- @Override
- public DataAccountRegisterOperation register(BlockchainIdentity userID) {
- return new DataAccountRegisterOpTemplate(userID);
- }
-
-
-
-}
+package com.jd.blockchain.transaction;
+
+import com.jd.blockchain.ledger.BlockchainIdentity;
+import com.jd.blockchain.ledger.DataAccountRegisterOperation;
+
+public class DataAccountRegisterOperationBuilderImpl implements DataAccountRegisterOperationBuilder{
+
+ @Override
+ public DataAccountRegisterOperation register(BlockchainIdentity userID) {
+ return new DataAccountRegisterOpTemplate(userID);
+ }
+
+
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DigitalSignatureBlob.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DigitalSignatureBlob.java
index a2125490..ddbbd26f 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DigitalSignatureBlob.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/DigitalSignatureBlob.java
@@ -1,116 +1,116 @@
-package com.jd.blockchain.transaction;
-
-
-import com.jd.blockchain.crypto.PubKey;
-import com.jd.blockchain.crypto.SignatureDigest;
-import com.jd.blockchain.ledger.DigitalSignature;
-import com.jd.blockchain.ledger.MagicNumber;
-
-/**
- * 数字签名的字节块;
- *
- *
- * 字节位如下:
- * [第1字节]:标识数据类型为数字签名的魔数常量 ({@link MagicNumber#SIGNATURE});
- *
- * [第2字节] - [第N字节]: 公钥;
- * 注:公钥的值是包含了公钥算法标识和公钥内容的字节码编码;
- *
- * [第N+1字节] - 结束: 摘要;
- *
- *
- *
- * @author huanghaiquan
- *
- */
-public class DigitalSignatureBlob implements DigitalSignature {
-
- private PubKey pubKey;
-
- private SignatureDigest digest;
-
- @Override
- public PubKey getPubKey() {
- return pubKey;
- }
-
- @Override
- public SignatureDigest getDigest() {
- return digest;
- }
-
- public DigitalSignatureBlob() {
- }
-
- public DigitalSignatureBlob(PubKey pubKey, SignatureDigest digest) {
- this.pubKey = pubKey;
- this.digest = digest;
- }
-
-
-// @Override
-// public void resolvFrom(InputStream in) {
-// try {
-// byte[] buff = new byte[1];
-// int len = in.read(buff);
-// if (len < 1) {
-// throw new IllegalArgumentException("No enough bytes was read for the magic number [SIGNATURE]!");
-// }
-// if (buff[0] != MagicNumber.SIGNATURE) {
-// throw new IllegalArgumentException("Magic number [SIGNATURE] dismatch!");
-// }
-// PubKey pk = CryptoKeyEncoding.readPubKey(in);
-// ByteArray dg = BytesEncoding.readAsByteArray(NumberMask.SHORT, in);
-// this.pubKey = pk;
-// this.digest = dg;
-// } catch (IOException e) {
-// throw new RuntimeIOException(e.getMessage(), e);
-// }
-// }
-//
-// @Override
-// public void writeTo(OutputStream out) {
-// try {
-// out.write(MagicNumber.SIGNATURE);
-// CryptoKeyEncoding.writeKey(pubKey, out);
-// BytesEncoding.write(digest, NumberMask.SHORT, out);
-// } catch (IOException e) {
-// throw new RuntimeIOException(e.getMessage(), e);
-// }
-// }
-//
-// @Override
-// public boolean equals(Object o) {
-// if (this == o) return true;
-// if (!(o instanceof DigitalSignatureBlob)) return false;
-// DigitalSignatureBlob that = (DigitalSignatureBlob) o;
-// return Objects.equals(getPubKey(), that.getPubKey()) &&
-// Objects.equals(getDigest(), that.getDigest());
-// }
-//
-// public byte[] toBytes() {
-// ByteArrayOutputStream out = new ByteArrayOutputStream();
-// writeTo(out);
-// return out.toByteArray();
-// }
-//
-// @Override
-// public String toString() {
-// return toBytes().toString();
-// }
-//
-// @Override
-// public void writeExternal(ObjectOutput out) throws IOException {
-// byte[] bts = toBytes();
-// out.writeInt(bts.length);
-// out.write(bts, 0, bts.length);
-// }
-//
-// @Override
-// public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
-// int size = in.readInt();
-// byte[] bs = new byte[size];
-// in.readFully(bs, 0, size);
-// resolvFrom(new ByteArrayInputStream(bs));
-// }
-}
+package com.jd.blockchain.transaction;
+
+
+import com.jd.blockchain.crypto.PubKey;
+import com.jd.blockchain.crypto.SignatureDigest;
+import com.jd.blockchain.ledger.DigitalSignature;
+import com.jd.blockchain.ledger.MagicNumber;
+
+/**
+ * 数字签名的字节块;
+ *
+ *
+ * 字节位如下:
+ * [第1字节]:标识数据类型为数字签名的魔数常量 ({@link MagicNumber#SIGNATURE});
+ *
+ * [第2字节] - [第N字节]: 公钥;
+ * 注:公钥的值是包含了公钥算法标识和公钥内容的字节码编码;
+ *
+ * [第N+1字节] - 结束: 摘要;
+ *
+ *
+ *
+ * @author huanghaiquan
+ *
+ */
+public class DigitalSignatureBlob implements DigitalSignature {
+
+ private PubKey pubKey;
+
+ private SignatureDigest digest;
+
+ @Override
+ public PubKey getPubKey() {
+ return pubKey;
+ }
+
+ @Override
+ public SignatureDigest getDigest() {
+ return digest;
+ }
+
+ public DigitalSignatureBlob() {
+ }
+
+ public DigitalSignatureBlob(PubKey pubKey, SignatureDigest digest) {
+ this.pubKey = pubKey;
+ this.digest = digest;
+ }
+
+
+// @Override
+// public void resolvFrom(InputStream in) {
+// try {
+// byte[] buff = new byte[1];
+// int len = in.read(buff);
+// if (len < 1) {
+// throw new IllegalArgumentException("No enough bytes was read for the magic number [SIGNATURE]!");
+// }
+// if (buff[0] != MagicNumber.SIGNATURE) {
+// throw new IllegalArgumentException("Magic number [SIGNATURE] dismatch!");
+// }
+// PubKey pk = CryptoKeyEncoding.readPubKey(in);
+// ByteArray dg = BytesEncoding.readAsByteArray(NumberMask.SHORT, in);
+// this.pubKey = pk;
+// this.digest = dg;
+// } catch (IOException e) {
+// throw new RuntimeIOException(e.getMessage(), e);
+// }
+// }
+//
+// @Override
+// public void writeTo(OutputStream out) {
+// try {
+// out.write(MagicNumber.SIGNATURE);
+// CryptoKeyEncoding.writeKey(pubKey, out);
+// BytesEncoding.write(digest, NumberMask.SHORT, out);
+// } catch (IOException e) {
+// throw new RuntimeIOException(e.getMessage(), e);
+// }
+// }
+//
+// @Override
+// public boolean equals(Object o) {
+// if (this == o) return true;
+// if (!(o instanceof DigitalSignatureBlob)) return false;
+// DigitalSignatureBlob that = (DigitalSignatureBlob) o;
+// return Objects.equals(getPubKey(), that.getPubKey()) &&
+// Objects.equals(getDigest(), that.getDigest());
+// }
+//
+// public byte[] toBytes() {
+// ByteArrayOutputStream out = new ByteArrayOutputStream();
+// writeTo(out);
+// return out.toByteArray();
+// }
+//
+// @Override
+// public String toString() {
+// return toBytes().toString();
+// }
+//
+// @Override
+// public void writeExternal(ObjectOutput out) throws IOException {
+// byte[] bts = toBytes();
+// out.writeInt(bts.length);
+// out.write(bts, 0, bts.length);
+// }
+//
+// @Override
+// public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
+// int size = in.readInt();
+// byte[] bs = new byte[size];
+// in.readFully(bs, 0, size);
+// resolvFrom(new ByteArrayInputStream(bs));
+// }
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LedgerInitOpTemplate.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LedgerInitOpTemplate.java
index 4259c98c..48b9e305 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LedgerInitOpTemplate.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LedgerInitOpTemplate.java
@@ -1,26 +1,26 @@
-package com.jd.blockchain.transaction;
-
-import com.jd.blockchain.binaryproto.DataContractRegistry;
-import com.jd.blockchain.ledger.LedgerInitOperation;
-import com.jd.blockchain.ledger.LedgerInitSetting;
-
-public class LedgerInitOpTemplate implements LedgerInitOperation {
- static {
- DataContractRegistry.register(LedgerInitOperation.class);
- }
-
- private LedgerInitSetting initSetting;
-
- public LedgerInitOpTemplate() {
- }
-
- public LedgerInitOpTemplate(LedgerInitSetting initSetting) {
- this.initSetting = initSetting;
- }
-
- @Override
- public LedgerInitSetting getInitSetting() {
- return initSetting;
- }
-
-}
+package com.jd.blockchain.transaction;
+
+import com.jd.blockchain.binaryproto.DataContractRegistry;
+import com.jd.blockchain.ledger.LedgerInitOperation;
+import com.jd.blockchain.ledger.LedgerInitSetting;
+
+public class LedgerInitOpTemplate implements LedgerInitOperation {
+ static {
+ DataContractRegistry.register(LedgerInitOperation.class);
+ }
+
+ private LedgerInitSetting initSetting;
+
+ public LedgerInitOpTemplate() {
+ }
+
+ public LedgerInitOpTemplate(LedgerInitSetting initSetting) {
+ this.initSetting = initSetting;
+ }
+
+ @Override
+ public LedgerInitSetting getInitSetting() {
+ return initSetting;
+ }
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LedgerInitOperationBuilder.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LedgerInitOperationBuilder.java
index 9416d73d..bada0ff8 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LedgerInitOperationBuilder.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LedgerInitOperationBuilder.java
@@ -1,17 +1,17 @@
-package com.jd.blockchain.transaction;
-
-import com.jd.blockchain.ledger.LedgerInitOperation;
-import com.jd.blockchain.ledger.LedgerInitSetting;
-
-public interface LedgerInitOperationBuilder {
-
- /**
- * 注册;
- *
- * @param initSetting
- * 账本初始化配置;
- * @return LedgerInitOperation
- */
- LedgerInitOperation create(LedgerInitSetting initSetting);
-
-}
+package com.jd.blockchain.transaction;
+
+import com.jd.blockchain.ledger.LedgerInitOperation;
+import com.jd.blockchain.ledger.LedgerInitSetting;
+
+public interface LedgerInitOperationBuilder {
+
+ /**
+ * 注册;
+ *
+ * @param initSetting
+ * 账本初始化配置;
+ * @return LedgerInitOperation
+ */
+ LedgerInitOperation create(LedgerInitSetting initSetting);
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LedgerInitOperationBuilderImpl.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LedgerInitOperationBuilderImpl.java
index 9562ae64..2f39f8d4 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LedgerInitOperationBuilderImpl.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LedgerInitOperationBuilderImpl.java
@@ -1,13 +1,13 @@
-package com.jd.blockchain.transaction;
-
-import com.jd.blockchain.ledger.LedgerInitOperation;
-import com.jd.blockchain.ledger.LedgerInitSetting;
-
-public class LedgerInitOperationBuilderImpl implements LedgerInitOperationBuilder {
-
- @Override
- public LedgerInitOperation create(LedgerInitSetting initSetting) {
- return new LedgerInitOpTemplate(initSetting);
- }
-
-}
+package com.jd.blockchain.transaction;
+
+import com.jd.blockchain.ledger.LedgerInitOperation;
+import com.jd.blockchain.ledger.LedgerInitSetting;
+
+public class LedgerInitOperationBuilderImpl implements LedgerInitOperationBuilder {
+
+ @Override
+ public LedgerInitOperation create(LedgerInitSetting initSetting) {
+ return new LedgerInitOpTemplate(initSetting);
+ }
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/NewLedgerOpBlob.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/NewLedgerOpBlob.java
index ee496969..ef9293e7 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/NewLedgerOpBlob.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/NewLedgerOpBlob.java
@@ -1,38 +1,38 @@
-package com.jd.blockchain.transaction;
-//package com.jd.blockchain.ledger.data;
-//
-//import com.jd.blockchain.ledger.OperationType;
-//import my.utils.io.ByteArray;
-//
-//public class NewLedgerOpBlob {
-//
-// private ByteArray genesisKey;
-//
-// public NewLedgerOpBlob() {
-// }
-//
-// public NewLedgerOpBlob(ByteArray genesisKey) {
-// this.genesisKey = genesisKey;
-// }
-//
-// public void resolvFrom(OpBlob opBlob) {
-//// if (OperationType.NEW_LEDGER.CODE != opBlob.getCode()) {
-//// throw new IllegalArgumentException(
-//// "Could not resolve operation info due to NEW_LEDGER operation code mismatch!");
-//// }
-////
-//// genesisKey = opBlob.getArg(0);
-// }
-//
-// public OpBlob toBlob() {
-// // 写入操作码;
-// OpBlob opBlob = new OpBlob();
-// opBlob.setOperation(OperationType.NEW_LEDGER.CODE, genesisKey);
-//
-// return opBlob;
-// }
-//
-// public ByteArray getGenesisKey() {
-// return genesisKey;
-// }
-//}
+package com.jd.blockchain.transaction;
+//package com.jd.blockchain.ledger.data;
+//
+//import com.jd.blockchain.ledger.OperationType;
+//import my.utils.io.ByteArray;
+//
+//public class NewLedgerOpBlob {
+//
+// private ByteArray genesisKey;
+//
+// public NewLedgerOpBlob() {
+// }
+//
+// public NewLedgerOpBlob(ByteArray genesisKey) {
+// this.genesisKey = genesisKey;
+// }
+//
+// public void resolvFrom(OpBlob opBlob) {
+//// if (OperationType.NEW_LEDGER.CODE != opBlob.getCode()) {
+//// throw new IllegalArgumentException(
+//// "Could not resolve operation info due to NEW_LEDGER operation code mismatch!");
+//// }
+////
+//// genesisKey = opBlob.getArg(0);
+// }
+//
+// public OpBlob toBlob() {
+// // 写入操作码;
+// OpBlob opBlob = new OpBlob();
+// opBlob.setOperation(OperationType.NEW_LEDGER.CODE, genesisKey);
+//
+// return opBlob;
+// }
+//
+// public ByteArray getGenesisKey() {
+// return genesisKey;
+// }
+//}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/PrivilegeSettingOperationBuilder.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/PrivilegeSettingOperationBuilder.java
index f10d77e1..027ae891 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/PrivilegeSettingOperationBuilder.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/PrivilegeSettingOperationBuilder.java
@@ -1,25 +1,25 @@
-package com.jd.blockchain.transaction;
-
-import com.jd.blockchain.ledger.PermissionType;
-
-/**
- * 账户权限设置操作;
- *
- *
- *
- * 注:默认情况下,在账户被注册时,账户自身会包含在权限设置表中,具有全部的权限;
- *
- * 但这不是必须的,使用者可以根据业务需要,去掉账户自身的权限,并将权限赋予其它的账户,以此实现将区块链账户分别用于表示“角色”和“数据”这两种目的;
- *
- * @author huanghaiquan
- *
- */
-public interface PrivilegeSettingOperationBuilder {
-
- PrivilegeSettingOperationBuilder setThreshhold(PermissionType privilege, long threshhold);
-
- PrivilegeSettingOperationBuilder enable(PermissionType privilege, String address, int weight);
-
- PrivilegeSettingOperationBuilder disable(PermissionType privilege, String address);
-
-}
+package com.jd.blockchain.transaction;
+
+import com.jd.blockchain.ledger.PermissionType;
+
+/**
+ * 账户权限设置操作;
+ *
+ *
+ *
+ * 注:默认情况下,在账户被注册时,账户自身会包含在权限设置表中,具有全部的权限;
+ *
+ * 但这不是必须的,使用者可以根据业务需要,去掉账户自身的权限,并将权限赋予其它的账户,以此实现将区块链账户分别用于表示“角色”和“数据”这两种目的;
+ *
+ * @author huanghaiquan
+ *
+ */
+public interface PrivilegeSettingOperationBuilder {
+
+ PrivilegeSettingOperationBuilder setThreshhold(PermissionType privilege, long threshhold);
+
+ PrivilegeSettingOperationBuilder enable(PermissionType privilege, String address, int weight);
+
+ PrivilegeSettingOperationBuilder disable(PermissionType privilege, String address);
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/PubKeyData.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/PubKeyData.java
index a31864e6..205e66b6 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/PubKeyData.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/PubKeyData.java
@@ -1,30 +1,30 @@
-package com.jd.blockchain.transaction;
-//package com.jd.blockchain.ledger.data;
-//
-//import com.jd.blockchain.ledger.KeyType;
-//import com.jd.blockchain.ledger.PubKey;
-//
-//import my.utils.io.ByteArray;
-//
-//public class PubKeyData implements PubKey{
-//
-// private KeyType type;
-//
-// private ByteArray value;
-//
-// public PubKeyData(KeyType type, ByteArray value) {
-// this.type = type;
-// this.value = value;
-// }
-//
-// @Override
-// public KeyType getType() {
-// return type;
-// }
-//
-// @Override
-// public ByteArray getValue() {
-// return value;
-// }
-//
-//}
+package com.jd.blockchain.transaction;
+//package com.jd.blockchain.ledger.data;
+//
+//import com.jd.blockchain.ledger.KeyType;
+//import com.jd.blockchain.ledger.PubKey;
+//
+//import my.utils.io.ByteArray;
+//
+//public class PubKeyData implements PubKey{
+//
+// private KeyType type;
+//
+// private ByteArray value;
+//
+// public PubKeyData(KeyType type, ByteArray value) {
+// this.type = type;
+// this.value = value;
+// }
+//
+// @Override
+// public KeyType getType() {
+// return type;
+// }
+//
+// @Override
+// public ByteArray getValue() {
+// return value;
+// }
+//
+//}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/RolesConfigureOpTemplate.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/RolesConfigureOpTemplate.java
index ba5fc4e5..6d8a4d0e 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/RolesConfigureOpTemplate.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/RolesConfigureOpTemplate.java
@@ -1,139 +1,139 @@
-package com.jd.blockchain.transaction;
-
-import java.util.Collections;
-import java.util.LinkedHashMap;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import com.jd.blockchain.binaryproto.DataContractRegistry;
-import com.jd.blockchain.ledger.LedgerPermission;
-import com.jd.blockchain.ledger.RolesConfigureOperation;
-import com.jd.blockchain.ledger.SecurityUtils;
-import com.jd.blockchain.ledger.TransactionPermission;
-import com.jd.blockchain.ledger.UserRegisterOperation;
-import com.jd.blockchain.utils.ArrayUtils;
-
-public class RolesConfigureOpTemplate implements RolesConfigurer, RolesConfigureOperation {
-
- static {
- DataContractRegistry.register(UserRegisterOperation.class);
- DataContractRegistry.register(RolesConfigureOperation.class);
- DataContractRegistry.register(RolePrivilegeEntry.class);
- }
-
- private Map rolesMap = Collections
- .synchronizedMap(new LinkedHashMap());
-
- public RolesConfigureOpTemplate() {
- }
-
- boolean isEmpty() {
- return rolesMap.isEmpty();
- }
-
- @Override
- public RolePrivilegeEntry[] getRoles() {
- return rolesMap.values().toArray(new RolePrivilegeEntry[rolesMap.size()]);
- }
-
- @Override
- public RolesConfigureOperation getOperation() {
- return this;
- }
-
- @Override
- public RolePrivilegeConfigurer configure(String roleName) {
- roleName = SecurityUtils.formatRoleName(roleName);
-
- RolePrivilegeConfig roleConfig = rolesMap.get(roleName);
- if (roleConfig == null) {
- roleConfig = new RolePrivilegeConfig(roleName);
- rolesMap.put(roleName, roleConfig);
- }
- return roleConfig;
- }
-
- private class RolePrivilegeConfig implements RolePrivilegeConfigurer, RolePrivilegeEntry {
-
- private String roleName;
-
- private Set enableLedgerPermissions = new LinkedHashSet();
- private Set disableLedgerPermissions = new LinkedHashSet();
-
- private Set enableTxPermissions = new LinkedHashSet();
- private Set disableTxPermissions = new LinkedHashSet();
-
- private RolePrivilegeConfig(String roleName) {
- this.roleName = roleName;
- }
-
- @Override
- public String getRoleName() {
- return roleName;
- }
-
- @Override
- public LedgerPermission[] getEnableLedgerPermissions() {
- return ArrayUtils.toArray(enableLedgerPermissions, LedgerPermission.class);
- }
-
- @Override
- public LedgerPermission[] getDisableLedgerPermissions() {
- return ArrayUtils.toArray(disableLedgerPermissions, LedgerPermission.class);
- }
-
- @Override
- public TransactionPermission[] getEnableTransactionPermissions() {
- return ArrayUtils.toArray(enableTxPermissions, TransactionPermission.class);
- }
-
- @Override
- public TransactionPermission[] getDisableTransactionPermissions() {
- return ArrayUtils.toArray(disableTxPermissions, TransactionPermission.class);
- }
-
- @Override
- public RolePrivilegeConfigurer enable(LedgerPermission... permissions) {
- List permissionList = ArrayUtils.asList(permissions);
- enableLedgerPermissions.addAll(permissionList);
- disableLedgerPermissions.removeAll(permissionList);
-
- return this;
- }
-
- @Override
- public RolePrivilegeConfigurer disable(LedgerPermission... permissions) {
- List permissionList = ArrayUtils.asList(permissions);
- disableLedgerPermissions.addAll(permissionList);
- enableLedgerPermissions.removeAll(permissionList);
-
- return this;
- }
-
- @Override
- public RolePrivilegeConfigurer enable(TransactionPermission... permissions) {
- List permissionList = ArrayUtils.asList(permissions);
- enableTxPermissions.addAll(permissionList);
- disableTxPermissions.removeAll(permissionList);
-
- return this;
- }
-
- @Override
- public RolePrivilegeConfigurer disable(TransactionPermission... permissions) {
- List permissionList = ArrayUtils.asList(permissions);
- disableTxPermissions.addAll(permissionList);
- enableTxPermissions.removeAll(permissionList);
-
- return this;
- }
-
- @Override
- public RolePrivilegeConfigurer configure(String roleName) {
- return RolesConfigureOpTemplate.this.configure(roleName);
- }
-
- }
-}
+package com.jd.blockchain.transaction;
+
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import com.jd.blockchain.binaryproto.DataContractRegistry;
+import com.jd.blockchain.ledger.LedgerPermission;
+import com.jd.blockchain.ledger.RolesConfigureOperation;
+import com.jd.blockchain.ledger.SecurityUtils;
+import com.jd.blockchain.ledger.TransactionPermission;
+import com.jd.blockchain.ledger.UserRegisterOperation;
+import com.jd.blockchain.utils.ArrayUtils;
+
+public class RolesConfigureOpTemplate implements RolesConfigurer, RolesConfigureOperation {
+
+ static {
+ DataContractRegistry.register(UserRegisterOperation.class);
+ DataContractRegistry.register(RolesConfigureOperation.class);
+ DataContractRegistry.register(RolePrivilegeEntry.class);
+ }
+
+ private Map rolesMap = Collections
+ .synchronizedMap(new LinkedHashMap());
+
+ public RolesConfigureOpTemplate() {
+ }
+
+ boolean isEmpty() {
+ return rolesMap.isEmpty();
+ }
+
+ @Override
+ public RolePrivilegeEntry[] getRoles() {
+ return rolesMap.values().toArray(new RolePrivilegeEntry[rolesMap.size()]);
+ }
+
+ @Override
+ public RolesConfigureOperation getOperation() {
+ return this;
+ }
+
+ @Override
+ public RolePrivilegeConfigurer configure(String roleName) {
+ roleName = SecurityUtils.formatRoleName(roleName);
+
+ RolePrivilegeConfig roleConfig = rolesMap.get(roleName);
+ if (roleConfig == null) {
+ roleConfig = new RolePrivilegeConfig(roleName);
+ rolesMap.put(roleName, roleConfig);
+ }
+ return roleConfig;
+ }
+
+ private class RolePrivilegeConfig implements RolePrivilegeConfigurer, RolePrivilegeEntry {
+
+ private String roleName;
+
+ private Set enableLedgerPermissions = new LinkedHashSet();
+ private Set disableLedgerPermissions = new LinkedHashSet();
+
+ private Set enableTxPermissions = new LinkedHashSet();
+ private Set disableTxPermissions = new LinkedHashSet();
+
+ private RolePrivilegeConfig(String roleName) {
+ this.roleName = roleName;
+ }
+
+ @Override
+ public String getRoleName() {
+ return roleName;
+ }
+
+ @Override
+ public LedgerPermission[] getEnableLedgerPermissions() {
+ return ArrayUtils.toArray(enableLedgerPermissions, LedgerPermission.class);
+ }
+
+ @Override
+ public LedgerPermission[] getDisableLedgerPermissions() {
+ return ArrayUtils.toArray(disableLedgerPermissions, LedgerPermission.class);
+ }
+
+ @Override
+ public TransactionPermission[] getEnableTransactionPermissions() {
+ return ArrayUtils.toArray(enableTxPermissions, TransactionPermission.class);
+ }
+
+ @Override
+ public TransactionPermission[] getDisableTransactionPermissions() {
+ return ArrayUtils.toArray(disableTxPermissions, TransactionPermission.class);
+ }
+
+ @Override
+ public RolePrivilegeConfigurer enable(LedgerPermission... permissions) {
+ List permissionList = ArrayUtils.asList(permissions);
+ enableLedgerPermissions.addAll(permissionList);
+ disableLedgerPermissions.removeAll(permissionList);
+
+ return this;
+ }
+
+ @Override
+ public RolePrivilegeConfigurer disable(LedgerPermission... permissions) {
+ List permissionList = ArrayUtils.asList(permissions);
+ disableLedgerPermissions.addAll(permissionList);
+ enableLedgerPermissions.removeAll(permissionList);
+
+ return this;
+ }
+
+ @Override
+ public RolePrivilegeConfigurer enable(TransactionPermission... permissions) {
+ List permissionList = ArrayUtils.asList(permissions);
+ enableTxPermissions.addAll(permissionList);
+ disableTxPermissions.removeAll(permissionList);
+
+ return this;
+ }
+
+ @Override
+ public RolePrivilegeConfigurer disable(TransactionPermission... permissions) {
+ List permissionList = ArrayUtils.asList(permissions);
+ disableTxPermissions.addAll(permissionList);
+ enableTxPermissions.removeAll(permissionList);
+
+ return this;
+ }
+
+ @Override
+ public RolePrivilegeConfigurer configure(String roleName) {
+ return RolesConfigureOpTemplate.this.configure(roleName);
+ }
+
+ }
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/SecurityOperationBuilder.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/SecurityOperationBuilder.java
index f3b6622c..44051b10 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/SecurityOperationBuilder.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/SecurityOperationBuilder.java
@@ -1,19 +1,19 @@
-package com.jd.blockchain.transaction;
-
-public interface SecurityOperationBuilder {
-
- /**
- * 配置角色;
- *
- * @return
- */
- RolesConfigurer roles();
-
- /**
- * 授权用户;
- *
- * @return
- */
- UserAuthorizer authorziations();
-
-}
+package com.jd.blockchain.transaction;
+
+public interface SecurityOperationBuilder {
+
+ /**
+ * 配置角色;
+ *
+ * @return
+ */
+ RolesConfigurer roles();
+
+ /**
+ * 授权用户;
+ *
+ * @return
+ */
+ UserAuthorizer authorziations();
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/SignatureEncoding.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/SignatureEncoding.java
index d28c829e..280a7882 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/SignatureEncoding.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/SignatureEncoding.java
@@ -1,27 +1,27 @@
-package com.jd.blockchain.transaction;
-
-import org.springframework.util.Base64Utils;
-
-import com.jd.blockchain.binaryproto.BinaryProtocol;
-import com.jd.blockchain.ledger.DigitalSignature;
-
-public class SignatureEncoding {
-
- public static byte[] encode(DigitalSignature signature) {
- return BinaryProtocol.encode(signature, DigitalSignature.class);
- }
-
- public static DigitalSignature decode(byte[] bytesSignature) {
- return BinaryProtocol.decode(bytesSignature);
- }
-
- public static DigitalSignature decodeFromBase64(String base64Signature) {
- byte[] bytesSignature = Base64Utils.decodeFromUrlSafeString(base64Signature);
- return decode(bytesSignature);
- }
-
- public static String encodeToBase64(DigitalSignature signature) {
- byte[] bytesSignature = encode(signature);
- return Base64Utils.encodeToUrlSafeString(bytesSignature);
- }
-}
+package com.jd.blockchain.transaction;
+
+import org.springframework.util.Base64Utils;
+
+import com.jd.blockchain.binaryproto.BinaryProtocol;
+import com.jd.blockchain.ledger.DigitalSignature;
+
+public class SignatureEncoding {
+
+ public static byte[] encode(DigitalSignature signature) {
+ return BinaryProtocol.encode(signature, DigitalSignature.class);
+ }
+
+ public static DigitalSignature decode(byte[] bytesSignature) {
+ return BinaryProtocol.decode(bytesSignature);
+ }
+
+ public static DigitalSignature decodeFromBase64(String base64Signature) {
+ byte[] bytesSignature = Base64Utils.decodeFromUrlSafeString(base64Signature);
+ return decode(bytesSignature);
+ }
+
+ public static String encodeToBase64(DigitalSignature signature) {
+ byte[] bytesSignature = encode(signature);
+ return Base64Utils.encodeToUrlSafeString(bytesSignature);
+ }
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TransactionService.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TransactionService.java
index 9d9a9ab8..014e5117 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TransactionService.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TransactionService.java
@@ -1,10 +1,10 @@
-package com.jd.blockchain.transaction;
-
-import com.jd.blockchain.ledger.TransactionRequest;
-import com.jd.blockchain.ledger.TransactionResponse;
-
-public interface TransactionService {
-
- TransactionResponse process(TransactionRequest txRequest);
-
-}
+package com.jd.blockchain.transaction;
+
+import com.jd.blockchain.ledger.TransactionRequest;
+import com.jd.blockchain.ledger.TransactionResponse;
+
+public interface TransactionService {
+
+ TransactionResponse process(TransactionRequest txRequest);
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxRequestBuilder.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxRequestBuilder.java
index 68653c0e..3ff1fd4c 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxRequestBuilder.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxRequestBuilder.java
@@ -1,106 +1,106 @@
-package com.jd.blockchain.transaction;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.jd.blockchain.binaryproto.BinaryProtocol;
-import com.jd.blockchain.crypto.AsymmetricKeypair;
-import com.jd.blockchain.crypto.Crypto;
-import com.jd.blockchain.crypto.HashDigest;
-import com.jd.blockchain.ledger.DigitalSignature;
-import com.jd.blockchain.ledger.NodeRequest;
-import com.jd.blockchain.ledger.TransactionContent;
-import com.jd.blockchain.ledger.TransactionRequest;
-import com.jd.blockchain.ledger.TransactionRequestBuilder;
-
-public class TxRequestBuilder implements TransactionRequestBuilder {
-
- private static final String DEFAULT_HASH_ALGORITHM = "SHA256";
-
- private TransactionContent txContent;
-
- private List endpointSignatures = new ArrayList<>();
-
- private List nodeSignatures = new ArrayList<>();
-
- public TxRequestBuilder(TransactionContent txContent) {
- this.txContent = txContent;
- }
-
- @Override
- public HashDigest getHash() {
- return txContent.getHash();
- }
-
- @Override
- public TransactionContent getTransactionContent() {
- return txContent;
- }
-
- @Override
- public DigitalSignature signAsEndpoint(AsymmetricKeypair keyPair) {
- DigitalSignature signature = SignatureUtils.sign(txContent, keyPair);
- addEndpointSignature(signature);
- return signature;
- }
-
- @Override
- public DigitalSignature signAsNode(AsymmetricKeypair keyPair) {
- DigitalSignature signature = SignatureUtils.sign(txContent, keyPair);
- addNodeSignature(signature);
- return signature;
- }
-
- @Override
- public void addNodeSignature(DigitalSignature... signatures) {
- if (signatures != null) {
- for (DigitalSignature s : signatures) {
- nodeSignatures.add(s);
- }
- }
- }
-
- @Override
- public void addEndpointSignature(DigitalSignature... signatures) {
- if (signatures != null) {
- for (DigitalSignature s : signatures) {
- endpointSignatures.add(s);
- }
- }
- }
-
-// public static DigitalSignature sign(TransactionContent txContent, AsymmetricKeypair keyPair) {
-// SignatureDigest signatureDigest = sign(txContent, keyPair.getPrivKey());
-// DigitalSignature signature = new DigitalSignatureBlob(keyPair.getPubKey(), signatureDigest);
-// return signature;
-// }
-//
-// public static SignatureDigest sign(TransactionContent txContent, PrivKey privKey) {
-// return Crypto.getSignatureFunction(privKey.getAlgorithm()).sign(privKey, txContent.getHash().toBytes());
-// }
-
-// public static boolean verifySignature(TransactionContent txContent, SignatureDigest signDigest, PubKey pubKey) {
-// if (!TxBuilder.verifyTxContentHash(txContent, txContent.getHash())) {
-// return false;
-// }
-// return verifyHashSignature(txContent.getHash(), signDigest, pubKey);
-// }
-//
-// public static boolean verifyHashSignature(HashDigest hash, SignatureDigest signDigest, PubKey pubKey) {
-// return Crypto.getSignatureFunction(pubKey.getAlgorithm()).verify(signDigest, pubKey, hash.toBytes());
-// }
-
- @Override
- public TransactionRequest buildRequest() {
- TxRequestMessage txMessage = new TxRequestMessage(txContent);
- txMessage.addEndpointSignatures(endpointSignatures);
- txMessage.addNodeSignatures(nodeSignatures);
-
- byte[] reqBytes = BinaryProtocol.encode(txMessage, NodeRequest.class);
- HashDigest reqHash = Crypto.getHashFunction(DEFAULT_HASH_ALGORITHM).hash(reqBytes);
- txMessage.setHash(reqHash);
-
- return txMessage;
- }
-
-}
+package com.jd.blockchain.transaction;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.jd.blockchain.binaryproto.BinaryProtocol;
+import com.jd.blockchain.crypto.AsymmetricKeypair;
+import com.jd.blockchain.crypto.Crypto;
+import com.jd.blockchain.crypto.HashDigest;
+import com.jd.blockchain.ledger.DigitalSignature;
+import com.jd.blockchain.ledger.NodeRequest;
+import com.jd.blockchain.ledger.TransactionContent;
+import com.jd.blockchain.ledger.TransactionRequest;
+import com.jd.blockchain.ledger.TransactionRequestBuilder;
+
+public class TxRequestBuilder implements TransactionRequestBuilder {
+
+ private static final String DEFAULT_HASH_ALGORITHM = "SHA256";
+
+ private TransactionContent txContent;
+
+ private List endpointSignatures = new ArrayList<>();
+
+ private List nodeSignatures = new ArrayList<>();
+
+ public TxRequestBuilder(TransactionContent txContent) {
+ this.txContent = txContent;
+ }
+
+ @Override
+ public HashDigest getHash() {
+ return txContent.getHash();
+ }
+
+ @Override
+ public TransactionContent getTransactionContent() {
+ return txContent;
+ }
+
+ @Override
+ public DigitalSignature signAsEndpoint(AsymmetricKeypair keyPair) {
+ DigitalSignature signature = SignatureUtils.sign(txContent, keyPair);
+ addEndpointSignature(signature);
+ return signature;
+ }
+
+ @Override
+ public DigitalSignature signAsNode(AsymmetricKeypair keyPair) {
+ DigitalSignature signature = SignatureUtils.sign(txContent, keyPair);
+ addNodeSignature(signature);
+ return signature;
+ }
+
+ @Override
+ public void addNodeSignature(DigitalSignature... signatures) {
+ if (signatures != null) {
+ for (DigitalSignature s : signatures) {
+ nodeSignatures.add(s);
+ }
+ }
+ }
+
+ @Override
+ public void addEndpointSignature(DigitalSignature... signatures) {
+ if (signatures != null) {
+ for (DigitalSignature s : signatures) {
+ endpointSignatures.add(s);
+ }
+ }
+ }
+
+// public static DigitalSignature sign(TransactionContent txContent, AsymmetricKeypair keyPair) {
+// SignatureDigest signatureDigest = sign(txContent, keyPair.getPrivKey());
+// DigitalSignature signature = new DigitalSignatureBlob(keyPair.getPubKey(), signatureDigest);
+// return signature;
+// }
+//
+// public static SignatureDigest sign(TransactionContent txContent, PrivKey privKey) {
+// return Crypto.getSignatureFunction(privKey.getAlgorithm()).sign(privKey, txContent.getHash().toBytes());
+// }
+
+// public static boolean verifySignature(TransactionContent txContent, SignatureDigest signDigest, PubKey pubKey) {
+// if (!TxBuilder.verifyTxContentHash(txContent, txContent.getHash())) {
+// return false;
+// }
+// return verifyHashSignature(txContent.getHash(), signDigest, pubKey);
+// }
+//
+// public static boolean verifyHashSignature(HashDigest hash, SignatureDigest signDigest, PubKey pubKey) {
+// return Crypto.getSignatureFunction(pubKey.getAlgorithm()).verify(signDigest, pubKey, hash.toBytes());
+// }
+
+ @Override
+ public TransactionRequest buildRequest() {
+ TxRequestMessage txMessage = new TxRequestMessage(txContent);
+ txMessage.addEndpointSignatures(endpointSignatures);
+ txMessage.addNodeSignatures(nodeSignatures);
+
+ byte[] reqBytes = BinaryProtocol.encode(txMessage, NodeRequest.class);
+ HashDigest reqHash = Crypto.getHashFunction(DEFAULT_HASH_ALGORITHM).hash(reqBytes);
+ txMessage.setHash(reqHash);
+
+ return txMessage;
+ }
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxRequestMessage.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxRequestMessage.java
index 50037ee4..c2cd4df8 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxRequestMessage.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxRequestMessage.java
@@ -1,385 +1,385 @@
-package com.jd.blockchain.transaction;
-
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-import com.jd.blockchain.binaryproto.DataContractRegistry;
-import com.jd.blockchain.crypto.AddressEncoding;
-import com.jd.blockchain.crypto.HashDigest;
-import com.jd.blockchain.ledger.BlockchainIdentity;
-import com.jd.blockchain.ledger.DigitalSignature;
-import com.jd.blockchain.ledger.MagicNumber;
-import com.jd.blockchain.ledger.NodeRequest;
-import com.jd.blockchain.ledger.TransactionContent;
-import com.jd.blockchain.ledger.TransactionRequest;
-import com.jd.blockchain.utils.Bytes;
-
-/**
- * TxRequestMessage 交易消息;
- *
- *
- * TxRequestMessage 表示参与者提交的交易请求,由3部分组成:交易内容、参与者签名、网关节点签名;
- *
- *
- * 字节位如下:
- * [第1字节]:标识数据类型为交易请求的魔数常量 ({@link MagicNumber#TX_REQUEST});
- *
- * [第2字节] - [第N字节]: 交易内容;
- *
- * [第N+1字节]: 交易参与者数量(有效值范围 0 - 255);
- * 注:在单个交易中,参与者的数量总是有限的,对于那些需要更多参与者且数量不确定的场景,可以通过合约来实现把参与者分为多次 TX 提交,最终组合完成一次完整的业务进程;
- * [第N+2字节] - [第X字节]: 参与者的签名列表;
- *
- * [第X+1字节]:对交易请求的哈希算法的代码;
- * [第X+2字节] - [第Y字节]:对交易请求的哈希值;针对交易请求中此段之前的全部内容进行哈希计算,包括:交易请求魔数、交易内容、签名者列表、哈希算法代码;
- *
- * [第Y+1字节] - 结束: 网关节点针对交易请求的签名;
- *
- *
- * @author huanghaiquan
- *
- */
-public class TxRequestMessage implements TransactionRequest {// , Externalizable {
-
- /**
- * 交易参与者的个数的最大值;
- */
- public static final int MAX_TX_PARTICIPANT_COUNT = 0xFF;
-
- private HashDigest hash;
-
- private TransactionContent transactionContent;
-
- private Map endpointSignatureMap = new LinkedHashMap<>();
-
- private Map nodeSignatureMap = new LinkedHashMap<>();
-
- // private CryptoAlgorithm defaultHashAlgorithm = CryptoAlgorithm.SHA_256;
-
- // public TxRequestMessage() {
- // }
-
- static {
- DataContractRegistry.register(NodeRequest.class);
- }
-
- public TxRequestMessage(TransactionContent txContent) {
- // if (!(txContent instanceof BytesWriter)) {
- // throw new IllegalArgumentException("The tx content must be instance of
- // BytesWriter!");
- // }
- this.transactionContent = txContent;
- }
-
- public TxRequestMessage(TransactionRequest txRequest) {
- this.transactionContent = txRequest.getTransactionContent();
- setHash(txRequest.getHash());
- setEndpointSignatures(txRequest.getEndpointSignatures());
- setNodeSignatures(txRequest.getNodeSignatures());
- }
-
- @Override
- public TransactionContent getTransactionContent() {
- return this.transactionContent;
- }
-
- @Override
- public DigitalSignature[] getEndpointSignatures() {
- return endpointSignatureMap.values().toArray(new DigitalSignature[endpointSignatureMap.size()]);
- }
-
- @Override
- public DigitalSignature[] getNodeSignatures() {
- return nodeSignatureMap.values().toArray(new DigitalSignature[nodeSignatureMap.size()]);
- }
-
- public void setEndpointSignatures(Object[] endpointSignatures) {
- if (endpointSignatures != null) {
- for (Object object : endpointSignatures) {
- DigitalSignature endpointSignature = (DigitalSignature) object;
- addEndpointSignatures(endpointSignature);
- }
- }
- return;
- }
-
- public void setNodeSignatures(Object[] nodeSignatures) {
- if (nodeSignatures != null) {
- for (Object object : nodeSignatures) {
- DigitalSignature nodeSignature = (DigitalSignature) object;
- addNodeSignatures(nodeSignature);
- }
- }
- return;
- }
-
- private void doAddEndpointSignature(DigitalSignature signature) {
- Bytes address = AddressEncoding.generateAddress(signature.getPubKey());
- if (endpointSignatureMap.containsKey(address)) {
- throw new IllegalArgumentException(
- String.format("Participant signature of Address[%s] already exist!", address));
- }
- endpointSignatureMap.put(address, signature);
- }
-
- /**
- * 从参与者签名列表中检查是否包含指定的参与者;
- *
- * @param userBid
- * 参与者的身份;
- * @return
- */
- public boolean containsEndpointSignature(BlockchainIdentity userBid) {
- return endpointSignatureMap.containsKey(userBid.getAddress());
- }
-
- public boolean containsEndpointSignature(Bytes userAddress) {
- return endpointSignatureMap.containsKey(userAddress);
- }
-
- public void addEndpointSignatures(DigitalSignature... signature) {
- for (DigitalSignature sign : signature) {
- doAddEndpointSignature(sign);
- }
- }
-
- public void addEndpointSignatures(List signature) {
- for (DigitalSignature sign : signature) {
- doAddEndpointSignature(sign);
- }
- }
-
- /**
- * 从节点签名列表中检查是否包含指定的节点;
- *
- * @param nodeBid
- * 节点的身份;
- * @return
- */
- public boolean containsNodeSignature(BlockchainIdentity nodeBid) {
- return nodeSignatureMap.containsKey(nodeBid.getAddress());
- }
-
- public boolean containsNodeSignature(Bytes nodeAddress) {
- return nodeSignatureMap.containsKey(nodeAddress);
- }
-
- private void doAddNodeSignatures(DigitalSignature signature) {
- Bytes address = AddressEncoding.generateAddress(signature.getPubKey());
- if (nodeSignatureMap.containsKey(address)) {
- throw new IllegalArgumentException(String.format("Node signature of Address[%s] already exist!", address));
- }
- nodeSignatureMap.put(address, signature);
- }
-
- public void addNodeSignatures(DigitalSignature... signature) {
- for (DigitalSignature sign : signature) {
- doAddNodeSignatures(sign);
- }
- }
-
- public void addNodeSignatures(List signature) {
- for (DigitalSignature sign : signature) {
- doAddNodeSignatures(sign);
- }
- }
-
- @Override
- public HashDigest getHash() {
- return hash;
- }
-
- public void setHash(HashDigest hash) {
- this.hash = hash;
- }
-
- // public HashDigest updateHash() {
- // return computeHash(this.defaultHashAlgorithm);
- // }
-
- // public HashDigest updateHash(CryptoAlgorithm hashAlgorithm) {
- // return computeHash(hashAlgorithm);
- // }
- //
- // private HashDigest computeHash(CryptoAlgorithm hashAlgorithm) {
- // byte[] reqBody = getRequestBody();
- // this.hash = CryptoUtils.hash(hashAlgorithm).hash(reqBody);
- // return this.hash;
- // }
-
- // @Override
- // public void resolvFrom(InputStream in) throws IOException {
- // // 解析校验交易请求魔数;
- // byte[] buff = new byte[1];
- // int len = in.read(buff, 0, 1);
- // if (len < 1) {
- // throw new IllegalArgumentException("No bytes was read for the magic number
- // [TX_REQUEST]!");
- // }
- // if (MagicNumber.TX_REQUEST != buff[0]) {
- // throw new IllegalArgumentException("Magic number [TX_REQUEST] dismatch!");
- // }
- //
- // // 解析交易内容;
- // TxContentBlob txContentBlob = new TxContentBlob();
- // txContentBlob.resolvFrom(in);
- //
- // // 解析参与者签名列表;
- // int participantCount = NumberMask.TINY.resolveMaskedNumber(in);
- // List partiSignList = new ArrayList<>();
- // for (int i = 0; i < participantCount; i++) {
- // DigitalSignatureBlob signature = new DigitalSignatureBlob();
- // signature.resolvFrom(in);
- //
- // partiSignList.add(signature);
- // }
- //
- // // 解析节点签名列表;
- // int nodeCount = NumberMask.TINY.resolveMaskedNumber(in);
- // List nodeSignList = new ArrayList<>();
- // for (int i = 0; i < nodeCount; i++) {
- // DigitalSignatureBlob nodeSign = new DigitalSignatureBlob();
- // nodeSign.resolvFrom(in);
- // nodeSignList.add(nodeSign);
- // }
- //
- // // 解析哈希算法标识符;
- // HashAlgorithm hashAlgorithm = HashAlgorithm.valueOf((byte) in.read());
- //
- // // 解析原始的哈希;
- // ByteArray hash = HashEncoding.read(in);
- //
- // this.txContent = txContentBlob;
- // addParticipantSignatures(partiSignList);
- // addNodeSignatures(nodeSignList);
- // this.hash = hash;
- //
- // // 校验原始哈希;
- // byte[] bodyBytes = getRequestBody();
- // ByteArray rHash = HashEncoding.computeHash(bodyBytes, hashAlgorithm);
- // if (!rHash.equals(hash)) {
- // throw new IllegalArgumentException("The hash is not match with request
- // content!");
- // }
- // }
- //
- // /**
- // * 输出交易请求消息;
- // *
- // * 注:此方法不会自动重新计算hash;如果消息的内容发生改变后,需要调用主动调用 {@link #updateHash()} 方法重新计算 hash;
- // */
- // @Override
- // public void writeTo(OutputStream out) throws IOException {
- // if (this.hash == null) {
- // updateHash();
- // }
- //
- // buildRequestBody(out);
- //
- // // 写入 hash 值;
- // HashEncoding.write(hash, out);
- // }
-
- // /**
- // * 生成请求体,包括:交易请求魔数、交易内容、参与者签名者列表、哈希算法代号;
- // *
- // * @param out
- // * @throws IOException
- // */
- // private void buildRequestBody(OutputStream out) throws IOException {
- //
- // buildParticipantRequest(out);
- //
- // // 写入节点签名列表;
- // NumberMask.TINY.writeMask(nodeSignatureMap.size(), out);
- // for (DigitalSignature nodeSignatureBlob : nodeSignatureMap.values()) {
- // nodeSignatureBlob.writeTo(out);
- // }
- //
- // // 写入 hash 算法代号;
- // out.write(hashAlgorithm.getAlgorithm());
- // }
-
- // /**
- // * 生成参与者的请求数据;
- // *
- // *
- // * 参与者的请求数据仅包含“交易请求模数({@link MagicNumber#TX_REQUEST })”
- // * “交易内容({@link #getTransactionContent()})”
- // * 和“参与者签名列表({@link #getParticipantSignatures()})”三项属性;
- // *
- // * @param out
- // */
- // public void buildParticipantRequest(OutputStream out) {
- // try {
- // // 写入魔数;
- // out.write(MagicNumber.TX_REQUEST);
- //
- // // 写入交易内容;
- // txContent.writeTo(out);
- //
- // // 写入 1 个字节的参与者签名数量;
- // if (participantSignatureMap.size() > MAX_TX_PARTICIPANT_COUNT) {
- // throw new IllegalArgumentException("The number of participant signatures is
- // out of the max count["
- // + MAX_TX_PARTICIPANT_COUNT + "]!");
- // }
- //
- // NumberMask.TINY.writeMask(participantSignatureMap.size(), out);
- // // 写入参与者签名列表;
- // for (DigitalSignature digitalSignatureBlob :
- // participantSignatureMap.values()) {
- // digitalSignatureBlob.writeTo(out);
- // }
- //
- // } catch (IOException e) {
- // throw new RuntimeIOException(e.getMessage(), e);
- // }
- // }
- //
- // @Override
- // public void writeExternal(ObjectOutput out) throws IOException {
- // ByteArrayOutputStream os = new ByteArrayOutputStream();
- // writeTo(os);
- // byte[] bts = os.toByteArray();
- // out.writeInt(bts.length);
- // out.write(bts);
- // }
- //
- // @Override
- // public void readExternal(ObjectInput in) throws IOException,
- // ClassNotFoundException {
- // int len = in.readInt();
- // byte[] bts = new byte[len];
- // in.readFully(bts);
- // this.resolvFrom(new ByteArrayInputStream(bts));
- // }
-
- // @Override
- // public byte[] toBytes() {
- // ByteArrayOutputStream out = new ByteArrayOutputStream();
- // try {
- // writeTo(out);
- // } catch (IOException e) {
- // throw new RuntimeIOException(e.getMessage(), e);
- // }
- // return out.toByteArray();
- // }
-
- // @Override
- // public ByteArray getHashData() {
- // return ByteArray.wrap(getRequestBody());
- // }
-
- // private byte[] getRequestBody() {
- // try {
- // ByteArrayOutputStream out = new ByteArrayOutputStream();
- // buildRequestBody(out);
- //
- // return out.toByteArray();
- // } catch (IOException e) {
- // throw new RuntimeIOException(e.getMessage(), e);
- // }
- // }
-}
+package com.jd.blockchain.transaction;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import com.jd.blockchain.binaryproto.DataContractRegistry;
+import com.jd.blockchain.crypto.AddressEncoding;
+import com.jd.blockchain.crypto.HashDigest;
+import com.jd.blockchain.ledger.BlockchainIdentity;
+import com.jd.blockchain.ledger.DigitalSignature;
+import com.jd.blockchain.ledger.MagicNumber;
+import com.jd.blockchain.ledger.NodeRequest;
+import com.jd.blockchain.ledger.TransactionContent;
+import com.jd.blockchain.ledger.TransactionRequest;
+import com.jd.blockchain.utils.Bytes;
+
+/**
+ * TxRequestMessage 交易消息;
+ *
+ *
+ * TxRequestMessage 表示参与者提交的交易请求,由3部分组成:交易内容、参与者签名、网关节点签名;
+ *
+ *
+ * 字节位如下:
+ * [第1字节]:标识数据类型为交易请求的魔数常量 ({@link MagicNumber#TX_REQUEST});
+ *
+ * [第2字节] - [第N字节]: 交易内容;
+ *
+ * [第N+1字节]: 交易参与者数量(有效值范围 0 - 255);
+ * 注:在单个交易中,参与者的数量总是有限的,对于那些需要更多参与者且数量不确定的场景,可以通过合约来实现把参与者分为多次 TX 提交,最终组合完成一次完整的业务进程;
+ * [第N+2字节] - [第X字节]: 参与者的签名列表;
+ *
+ * [第X+1字节]:对交易请求的哈希算法的代码;
+ * [第X+2字节] - [第Y字节]:对交易请求的哈希值;针对交易请求中此段之前的全部内容进行哈希计算,包括:交易请求魔数、交易内容、签名者列表、哈希算法代码;
+ *
+ * [第Y+1字节] - 结束: 网关节点针对交易请求的签名;
+ *
+ *
+ * @author huanghaiquan
+ *
+ */
+public class TxRequestMessage implements TransactionRequest {// , Externalizable {
+
+ /**
+ * 交易参与者的个数的最大值;
+ */
+ public static final int MAX_TX_PARTICIPANT_COUNT = 0xFF;
+
+ private HashDigest hash;
+
+ private TransactionContent transactionContent;
+
+ private Map endpointSignatureMap = new LinkedHashMap<>();
+
+ private Map nodeSignatureMap = new LinkedHashMap<>();
+
+ // private CryptoAlgorithm defaultHashAlgorithm = CryptoAlgorithm.SHA_256;
+
+ // public TxRequestMessage() {
+ // }
+
+ static {
+ DataContractRegistry.register(NodeRequest.class);
+ }
+
+ public TxRequestMessage(TransactionContent txContent) {
+ // if (!(txContent instanceof BytesWriter)) {
+ // throw new IllegalArgumentException("The tx content must be instance of
+ // BytesWriter!");
+ // }
+ this.transactionContent = txContent;
+ }
+
+ public TxRequestMessage(TransactionRequest txRequest) {
+ this.transactionContent = txRequest.getTransactionContent();
+ setHash(txRequest.getHash());
+ setEndpointSignatures(txRequest.getEndpointSignatures());
+ setNodeSignatures(txRequest.getNodeSignatures());
+ }
+
+ @Override
+ public TransactionContent getTransactionContent() {
+ return this.transactionContent;
+ }
+
+ @Override
+ public DigitalSignature[] getEndpointSignatures() {
+ return endpointSignatureMap.values().toArray(new DigitalSignature[endpointSignatureMap.size()]);
+ }
+
+ @Override
+ public DigitalSignature[] getNodeSignatures() {
+ return nodeSignatureMap.values().toArray(new DigitalSignature[nodeSignatureMap.size()]);
+ }
+
+ public void setEndpointSignatures(Object[] endpointSignatures) {
+ if (endpointSignatures != null) {
+ for (Object object : endpointSignatures) {
+ DigitalSignature endpointSignature = (DigitalSignature) object;
+ addEndpointSignatures(endpointSignature);
+ }
+ }
+ return;
+ }
+
+ public void setNodeSignatures(Object[] nodeSignatures) {
+ if (nodeSignatures != null) {
+ for (Object object : nodeSignatures) {
+ DigitalSignature nodeSignature = (DigitalSignature) object;
+ addNodeSignatures(nodeSignature);
+ }
+ }
+ return;
+ }
+
+ private void doAddEndpointSignature(DigitalSignature signature) {
+ Bytes address = AddressEncoding.generateAddress(signature.getPubKey());
+ if (endpointSignatureMap.containsKey(address)) {
+ throw new IllegalArgumentException(
+ String.format("Participant signature of Address[%s] already exist!", address));
+ }
+ endpointSignatureMap.put(address, signature);
+ }
+
+ /**
+ * 从参与者签名列表中检查是否包含指定的参与者;
+ *
+ * @param userBid
+ * 参与者的身份;
+ * @return
+ */
+ public boolean containsEndpointSignature(BlockchainIdentity userBid) {
+ return endpointSignatureMap.containsKey(userBid.getAddress());
+ }
+
+ public boolean containsEndpointSignature(Bytes userAddress) {
+ return endpointSignatureMap.containsKey(userAddress);
+ }
+
+ public void addEndpointSignatures(DigitalSignature... signature) {
+ for (DigitalSignature sign : signature) {
+ doAddEndpointSignature(sign);
+ }
+ }
+
+ public void addEndpointSignatures(List signature) {
+ for (DigitalSignature sign : signature) {
+ doAddEndpointSignature(sign);
+ }
+ }
+
+ /**
+ * 从节点签名列表中检查是否包含指定的节点;
+ *
+ * @param nodeBid
+ * 节点的身份;
+ * @return
+ */
+ public boolean containsNodeSignature(BlockchainIdentity nodeBid) {
+ return nodeSignatureMap.containsKey(nodeBid.getAddress());
+ }
+
+ public boolean containsNodeSignature(Bytes nodeAddress) {
+ return nodeSignatureMap.containsKey(nodeAddress);
+ }
+
+ private void doAddNodeSignatures(DigitalSignature signature) {
+ Bytes address = AddressEncoding.generateAddress(signature.getPubKey());
+ if (nodeSignatureMap.containsKey(address)) {
+ throw new IllegalArgumentException(String.format("Node signature of Address[%s] already exist!", address));
+ }
+ nodeSignatureMap.put(address, signature);
+ }
+
+ public void addNodeSignatures(DigitalSignature... signature) {
+ for (DigitalSignature sign : signature) {
+ doAddNodeSignatures(sign);
+ }
+ }
+
+ public void addNodeSignatures(List signature) {
+ for (DigitalSignature sign : signature) {
+ doAddNodeSignatures(sign);
+ }
+ }
+
+ @Override
+ public HashDigest getHash() {
+ return hash;
+ }
+
+ public void setHash(HashDigest hash) {
+ this.hash = hash;
+ }
+
+ // public HashDigest updateHash() {
+ // return computeHash(this.defaultHashAlgorithm);
+ // }
+
+ // public HashDigest updateHash(CryptoAlgorithm hashAlgorithm) {
+ // return computeHash(hashAlgorithm);
+ // }
+ //
+ // private HashDigest computeHash(CryptoAlgorithm hashAlgorithm) {
+ // byte[] reqBody = getRequestBody();
+ // this.hash = CryptoUtils.hash(hashAlgorithm).hash(reqBody);
+ // return this.hash;
+ // }
+
+ // @Override
+ // public void resolvFrom(InputStream in) throws IOException {
+ // // 解析校验交易请求魔数;
+ // byte[] buff = new byte[1];
+ // int len = in.read(buff, 0, 1);
+ // if (len < 1) {
+ // throw new IllegalArgumentException("No bytes was read for the magic number
+ // [TX_REQUEST]!");
+ // }
+ // if (MagicNumber.TX_REQUEST != buff[0]) {
+ // throw new IllegalArgumentException("Magic number [TX_REQUEST] dismatch!");
+ // }
+ //
+ // // 解析交易内容;
+ // TxContentBlob txContentBlob = new TxContentBlob();
+ // txContentBlob.resolvFrom(in);
+ //
+ // // 解析参与者签名列表;
+ // int participantCount = NumberMask.TINY.resolveMaskedNumber(in);
+ // List partiSignList = new ArrayList<>();
+ // for (int i = 0; i < participantCount; i++) {
+ // DigitalSignatureBlob signature = new DigitalSignatureBlob();
+ // signature.resolvFrom(in);
+ //
+ // partiSignList.add(signature);
+ // }
+ //
+ // // 解析节点签名列表;
+ // int nodeCount = NumberMask.TINY.resolveMaskedNumber(in);
+ // List nodeSignList = new ArrayList<>();
+ // for (int i = 0; i < nodeCount; i++) {
+ // DigitalSignatureBlob nodeSign = new DigitalSignatureBlob();
+ // nodeSign.resolvFrom(in);
+ // nodeSignList.add(nodeSign);
+ // }
+ //
+ // // 解析哈希算法标识符;
+ // HashAlgorithm hashAlgorithm = HashAlgorithm.valueOf((byte) in.read());
+ //
+ // // 解析原始的哈希;
+ // ByteArray hash = HashEncoding.read(in);
+ //
+ // this.txContent = txContentBlob;
+ // addParticipantSignatures(partiSignList);
+ // addNodeSignatures(nodeSignList);
+ // this.hash = hash;
+ //
+ // // 校验原始哈希;
+ // byte[] bodyBytes = getRequestBody();
+ // ByteArray rHash = HashEncoding.computeHash(bodyBytes, hashAlgorithm);
+ // if (!rHash.equals(hash)) {
+ // throw new IllegalArgumentException("The hash is not match with request
+ // content!");
+ // }
+ // }
+ //
+ // /**
+ // * 输出交易请求消息;
+ // *
+ // * 注:此方法不会自动重新计算hash;如果消息的内容发生改变后,需要调用主动调用 {@link #updateHash()} 方法重新计算 hash;
+ // */
+ // @Override
+ // public void writeTo(OutputStream out) throws IOException {
+ // if (this.hash == null) {
+ // updateHash();
+ // }
+ //
+ // buildRequestBody(out);
+ //
+ // // 写入 hash 值;
+ // HashEncoding.write(hash, out);
+ // }
+
+ // /**
+ // * 生成请求体,包括:交易请求魔数、交易内容、参与者签名者列表、哈希算法代号;
+ // *
+ // * @param out
+ // * @throws IOException
+ // */
+ // private void buildRequestBody(OutputStream out) throws IOException {
+ //
+ // buildParticipantRequest(out);
+ //
+ // // 写入节点签名列表;
+ // NumberMask.TINY.writeMask(nodeSignatureMap.size(), out);
+ // for (DigitalSignature nodeSignatureBlob : nodeSignatureMap.values()) {
+ // nodeSignatureBlob.writeTo(out);
+ // }
+ //
+ // // 写入 hash 算法代号;
+ // out.write(hashAlgorithm.getAlgorithm());
+ // }
+
+ // /**
+ // * 生成参与者的请求数据;
+ // *
+ // *
+ // * 参与者的请求数据仅包含“交易请求模数({@link MagicNumber#TX_REQUEST })”
+ // * “交易内容({@link #getTransactionContent()})”
+ // * 和“参与者签名列表({@link #getParticipantSignatures()})”三项属性;
+ // *
+ // * @param out
+ // */
+ // public void buildParticipantRequest(OutputStream out) {
+ // try {
+ // // 写入魔数;
+ // out.write(MagicNumber.TX_REQUEST);
+ //
+ // // 写入交易内容;
+ // txContent.writeTo(out);
+ //
+ // // 写入 1 个字节的参与者签名数量;
+ // if (participantSignatureMap.size() > MAX_TX_PARTICIPANT_COUNT) {
+ // throw new IllegalArgumentException("The number of participant signatures is
+ // out of the max count["
+ // + MAX_TX_PARTICIPANT_COUNT + "]!");
+ // }
+ //
+ // NumberMask.TINY.writeMask(participantSignatureMap.size(), out);
+ // // 写入参与者签名列表;
+ // for (DigitalSignature digitalSignatureBlob :
+ // participantSignatureMap.values()) {
+ // digitalSignatureBlob.writeTo(out);
+ // }
+ //
+ // } catch (IOException e) {
+ // throw new RuntimeIOException(e.getMessage(), e);
+ // }
+ // }
+ //
+ // @Override
+ // public void writeExternal(ObjectOutput out) throws IOException {
+ // ByteArrayOutputStream os = new ByteArrayOutputStream();
+ // writeTo(os);
+ // byte[] bts = os.toByteArray();
+ // out.writeInt(bts.length);
+ // out.write(bts);
+ // }
+ //
+ // @Override
+ // public void readExternal(ObjectInput in) throws IOException,
+ // ClassNotFoundException {
+ // int len = in.readInt();
+ // byte[] bts = new byte[len];
+ // in.readFully(bts);
+ // this.resolvFrom(new ByteArrayInputStream(bts));
+ // }
+
+ // @Override
+ // public byte[] toBytes() {
+ // ByteArrayOutputStream out = new ByteArrayOutputStream();
+ // try {
+ // writeTo(out);
+ // } catch (IOException e) {
+ // throw new RuntimeIOException(e.getMessage(), e);
+ // }
+ // return out.toByteArray();
+ // }
+
+ // @Override
+ // public ByteArray getHashData() {
+ // return ByteArray.wrap(getRequestBody());
+ // }
+
+ // private byte[] getRequestBody() {
+ // try {
+ // ByteArrayOutputStream out = new ByteArrayOutputStream();
+ // buildRequestBody(out);
+ //
+ // return out.toByteArray();
+ // } catch (IOException e) {
+ // throw new RuntimeIOException(e.getMessage(), e);
+ // }
+ // }
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxResponseMessage.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxResponseMessage.java
index 57107ff3..0bed71b5 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxResponseMessage.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxResponseMessage.java
@@ -1,86 +1,86 @@
-package com.jd.blockchain.transaction;
-
-import com.jd.blockchain.ledger.TransactionState;
-import com.jd.blockchain.crypto.HashDigest;
-import com.jd.blockchain.ledger.OperationResult;
-import com.jd.blockchain.ledger.TransactionResponse;
-
-/**
- * @author huanghaiquan
- *
- */
-public class TxResponseMessage implements TransactionResponse {
-
- private HashDigest contentHash;
-
- private HashDigest blockHash;
-
- private long blockHeight;
-
- private TransactionState executionState;
-
- private OperationResult[] operationResults;
-
- public TxResponseMessage() {
- }
-
- // 重新包装operationResults
- public TxResponseMessage(TransactionResponse transactionResponse, OperationResult[] operationResults) {
- this.contentHash = transactionResponse.getContentHash();
- this.blockHash = transactionResponse.getBlockHash();
- this.blockHeight = transactionResponse.getBlockHeight();
- this.executionState = transactionResponse.getExecutionState();
- this.operationResults = operationResults;
- }
-
- public TxResponseMessage(HashDigest contentHash) {
- this.contentHash = contentHash;
- }
-
- @Override
- public HashDigest getContentHash() {
- return contentHash;
- }
-
- @Override
- public TransactionState getExecutionState() {
- return executionState;
- }
-
- public void setExecutionState(TransactionState executionState) {
- this.executionState = executionState;
- }
-
- @Override
- public HashDigest getBlockHash() {
- return blockHash;
- }
-
- public void setBlockHash(HashDigest blockHash) {
- this.blockHash = blockHash;
- }
-
- @Override
- public long getBlockHeight() {
- return blockHeight;
- }
-
- public void setBlockHeight(long blockHeight) {
- this.blockHeight = blockHeight;
- }
-
- public void setOperationResults(OperationResult[] operationResults) {
- this.operationResults = operationResults;
- }
-
- @Override
- public boolean isSuccess() {
- return blockHash != null & executionState == TransactionState.SUCCESS;
- }
-
- @Override
- public OperationResult[] getOperationResults() {
- return operationResults;
- }
-
-}
+package com.jd.blockchain.transaction;
+
+import com.jd.blockchain.ledger.TransactionState;
+import com.jd.blockchain.crypto.HashDigest;
+import com.jd.blockchain.ledger.OperationResult;
+import com.jd.blockchain.ledger.TransactionResponse;
+
+/**
+ * @author huanghaiquan
+ *
+ */
+public class TxResponseMessage implements TransactionResponse {
+
+ private HashDigest contentHash;
+
+ private HashDigest blockHash;
+
+ private long blockHeight;
+
+ private TransactionState executionState;
+
+ private OperationResult[] operationResults;
+
+ public TxResponseMessage() {
+ }
+
+ // 重新包装operationResults
+ public TxResponseMessage(TransactionResponse transactionResponse, OperationResult[] operationResults) {
+ this.contentHash = transactionResponse.getContentHash();
+ this.blockHash = transactionResponse.getBlockHash();
+ this.blockHeight = transactionResponse.getBlockHeight();
+ this.executionState = transactionResponse.getExecutionState();
+ this.operationResults = operationResults;
+ }
+
+ public TxResponseMessage(HashDigest contentHash) {
+ this.contentHash = contentHash;
+ }
+
+ @Override
+ public HashDigest getContentHash() {
+ return contentHash;
+ }
+
+ @Override
+ public TransactionState getExecutionState() {
+ return executionState;
+ }
+
+ public void setExecutionState(TransactionState executionState) {
+ this.executionState = executionState;
+ }
+
+ @Override
+ public HashDigest getBlockHash() {
+ return blockHash;
+ }
+
+ public void setBlockHash(HashDigest blockHash) {
+ this.blockHash = blockHash;
+ }
+
+ @Override
+ public long getBlockHeight() {
+ return blockHeight;
+ }
+
+ public void setBlockHeight(long blockHeight) {
+ this.blockHeight = blockHeight;
+ }
+
+ public void setOperationResults(OperationResult[] operationResults) {
+ this.operationResults = operationResults;
+ }
+
+ @Override
+ public boolean isSuccess() {
+ return blockHash != null & executionState == TransactionState.SUCCESS;
+ }
+
+ @Override
+ public OperationResult[] getOperationResults() {
+ return operationResults;
+ }
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxTemplate.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxTemplate.java
index 5f006111..01fb8caf 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxTemplate.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxTemplate.java
@@ -1,111 +1,111 @@
-package com.jd.blockchain.transaction;
-
-import java.io.IOException;
-import java.util.Collection;
-
-import com.jd.blockchain.crypto.HashDigest;
-import com.jd.blockchain.ledger.PreparedTransaction;
-import com.jd.blockchain.ledger.TransactionRequestBuilder;
-import com.jd.blockchain.ledger.TransactionTemplate;
-import com.jd.blockchain.utils.Bytes;
-
-public class TxTemplate implements TransactionTemplate {
-
- private TxBuilder txBuilder;
-
- private TransactionService txService;
-
- private TxStateManager stateManager;
-
- public TxTemplate(HashDigest ledgerHash, TransactionService txService) {
- this.stateManager = new TxStateManager();
- this.txBuilder = new TxBuilder(ledgerHash);
- this.txService = txService;
- }
-
- @Override
- public HashDigest getLedgerHash() {
- return txBuilder.getLedgerHash();
- }
-
- @Override
- public PreparedTransaction prepare() {
- stateManager.prepare();
- TransactionRequestBuilder txReqBuilder = txBuilder.prepareRequest();
- return new PreparedTx(stateManager, txReqBuilder, txService, txBuilder.getReturnValuehandlers());
- }
-
- @Override
- public SecurityOperationBuilder security() {
- stateManager.operate();
- return txBuilder.security();
- }
-
- @Override
- public UserRegisterOperationBuilder users() {
- stateManager.operate();
- return txBuilder.users();
- }
-
- @Override
- public DataAccountRegisterOperationBuilder dataAccounts() {
- stateManager.operate();
- return txBuilder.dataAccounts();
- }
-
- @Override
- public DataAccountKVSetOperationBuilder dataAccount(String accountAddress) {
- stateManager.operate();
- return txBuilder.dataAccount(accountAddress);
- }
-
- @Override
- public DataAccountKVSetOperationBuilder dataAccount(Bytes accountAddress) {
- stateManager.operate();
- return txBuilder.dataAccount(accountAddress);
- }
-
- @Override
- public ContractCodeDeployOperationBuilder contracts() {
- stateManager.operate();
- return txBuilder.contracts();
- }
-
- @Override
- public ParticipantRegisterOperationBuilder participants() {
- stateManager.operate();
- return txBuilder.participants();
- }
-
- @Override
- public ParticipantStateUpdateOperationBuilder states() {
- stateManager.operate();
- return txBuilder.states();
- }
-
- @Override
- public T contract(Bytes address, Class contractIntf) {
- stateManager.operate();
- return txBuilder.contract(address, contractIntf);
- }
-
- @Override
- public T contract(String address, Class contractIntf) {
- stateManager.operate();
- return txBuilder.contract(address, contractIntf);
- }
-
- @Override
- public void close() throws IOException {
- if (!stateManager.close()) {
- Collection handlers = txBuilder.getReturnValuehandlers();
- if (handlers.size() > 0) {
- TransactionCancelledExeption error = new TransactionCancelledExeption(
- "Transaction template has been cancelled!");
- for (OperationResultHandle handle : handlers) {
- handle.complete(error);
- }
- }
- }
- }
-}
+package com.jd.blockchain.transaction;
+
+import java.io.IOException;
+import java.util.Collection;
+
+import com.jd.blockchain.crypto.HashDigest;
+import com.jd.blockchain.ledger.PreparedTransaction;
+import com.jd.blockchain.ledger.TransactionRequestBuilder;
+import com.jd.blockchain.ledger.TransactionTemplate;
+import com.jd.blockchain.utils.Bytes;
+
+public class TxTemplate implements TransactionTemplate {
+
+ private TxBuilder txBuilder;
+
+ private TransactionService txService;
+
+ private TxStateManager stateManager;
+
+ public TxTemplate(HashDigest ledgerHash, TransactionService txService) {
+ this.stateManager = new TxStateManager();
+ this.txBuilder = new TxBuilder(ledgerHash);
+ this.txService = txService;
+ }
+
+ @Override
+ public HashDigest getLedgerHash() {
+ return txBuilder.getLedgerHash();
+ }
+
+ @Override
+ public PreparedTransaction prepare() {
+ stateManager.prepare();
+ TransactionRequestBuilder txReqBuilder = txBuilder.prepareRequest();
+ return new PreparedTx(stateManager, txReqBuilder, txService, txBuilder.getReturnValuehandlers());
+ }
+
+ @Override
+ public SecurityOperationBuilder security() {
+ stateManager.operate();
+ return txBuilder.security();
+ }
+
+ @Override
+ public UserRegisterOperationBuilder users() {
+ stateManager.operate();
+ return txBuilder.users();
+ }
+
+ @Override
+ public DataAccountRegisterOperationBuilder dataAccounts() {
+ stateManager.operate();
+ return txBuilder.dataAccounts();
+ }
+
+ @Override
+ public DataAccountKVSetOperationBuilder dataAccount(String accountAddress) {
+ stateManager.operate();
+ return txBuilder.dataAccount(accountAddress);
+ }
+
+ @Override
+ public DataAccountKVSetOperationBuilder dataAccount(Bytes accountAddress) {
+ stateManager.operate();
+ return txBuilder.dataAccount(accountAddress);
+ }
+
+ @Override
+ public ContractCodeDeployOperationBuilder contracts() {
+ stateManager.operate();
+ return txBuilder.contracts();
+ }
+
+ @Override
+ public ParticipantRegisterOperationBuilder participants() {
+ stateManager.operate();
+ return txBuilder.participants();
+ }
+
+ @Override
+ public ParticipantStateUpdateOperationBuilder states() {
+ stateManager.operate();
+ return txBuilder.states();
+ }
+
+ @Override
+ public T contract(Bytes address, Class contractIntf) {
+ stateManager.operate();
+ return txBuilder.contract(address, contractIntf);
+ }
+
+ @Override
+ public T contract(String address, Class contractIntf) {
+ stateManager.operate();
+ return txBuilder.contract(address, contractIntf);
+ }
+
+ @Override
+ public void close() throws IOException {
+ if (!stateManager.close()) {
+ Collection handlers = txBuilder.getReturnValuehandlers();
+ if (handlers.size() > 0) {
+ TransactionCancelledExeption error = new TransactionCancelledExeption(
+ "Transaction template has been cancelled!");
+ for (OperationResultHandle handle : handlers) {
+ handle.complete(error);
+ }
+ }
+ }
+ }
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserAuthorizeOpTemplate.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserAuthorizeOpTemplate.java
index ca66a6d9..d4c06cc0 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserAuthorizeOpTemplate.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserAuthorizeOpTemplate.java
@@ -1,130 +1,130 @@
-package com.jd.blockchain.transaction;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.LinkedHashSet;
-import java.util.Set;
-
-import com.jd.blockchain.binaryproto.DataContractRegistry;
-import com.jd.blockchain.ledger.BlockchainIdentity;
-import com.jd.blockchain.ledger.RolesPolicy;
-import com.jd.blockchain.ledger.SecurityUtils;
-import com.jd.blockchain.ledger.UserAuthorizeOperation;
-import com.jd.blockchain.ledger.UserRegisterOperation;
-import com.jd.blockchain.utils.ArrayUtils;
-import com.jd.blockchain.utils.Bytes;
-
-public class UserAuthorizeOpTemplate implements UserAuthorizer, UserAuthorizeOperation {
-
- static {
- DataContractRegistry.register(UserRegisterOperation.class);
- DataContractRegistry.register(UserAuthorizeOperation.class);
- DataContractRegistry.register(UserRolesEntry.class);
- }
-
- private Set userAuthMap = Collections
- .synchronizedSet(new LinkedHashSet());
-
- public UserAuthorizeOpTemplate() {
- }
-
- public UserAuthorizeOpTemplate(BlockchainIdentity userID) {
- }
-
- @Override
- public AuthorizationDataEntry[] getUserRolesAuthorizations() {
- return ArrayUtils.toArray(userAuthMap, AuthorizationDataEntry.class);
- }
-
- @Override
- public UserAuthorizeOperation getOperation() {
- return this;
- }
-
- @Override
- public UserRolesAuthorizer forUser(Bytes... userAddresses) {
- AuthorizationDataEntry userRolesAuth = new AuthorizationDataEntry(userAddresses);
- userAuthMap.add(userRolesAuth);
- return userRolesAuth;
- }
-
- @Override
- public UserRolesAuthorizer forUser(BlockchainIdentity... userIds) {
- Bytes[] addresses = Arrays.stream(userIds).map(p -> p.getAddress()).toArray(Bytes[]::new);
- return forUser(addresses);
- }
-
- private class AuthorizationDataEntry implements UserRolesAuthorizer, UserRolesEntry {
-
- private Bytes[] userAddress;
-
- private RolesPolicy policy = RolesPolicy.UNION;
-
- private Set authRoles = new LinkedHashSet();
- private Set unauthRoles = new LinkedHashSet();
-
- private AuthorizationDataEntry(Bytes[] userAddress) {
- this.userAddress = userAddress;
- }
-
- @Override
- public Bytes[] getUserAddresses() {
- return userAddress;
- }
-
- @Override
- public RolesPolicy getPolicy() {
- return policy;
- }
-
- @Override
- public String[] getAuthorizedRoles() {
- return ArrayUtils.toArray(authRoles, String.class);
- }
-
- @Override
- public String[] getUnauthorizedRoles() {
- return ArrayUtils.toArray(unauthRoles, String.class);
- }
-
- @Override
- public UserRolesAuthorizer setPolicy(RolesPolicy policy) {
- this.policy = policy;
- return this;
- }
-
- @Override
- public UserRolesAuthorizer authorize(String... roles) {
- String roleName;
- for (String r : roles) {
- roleName = SecurityUtils.formatRoleName(r);
- authRoles.add(roleName);
- unauthRoles.remove(roleName);
- }
-
- return this;
- }
-
- @Override
- public UserRolesAuthorizer unauthorize(String... roles) {
- String roleName;
- for (String r : roles) {
- roleName = SecurityUtils.formatRoleName(r);
- unauthRoles.add(roleName);
- authRoles.remove(roleName);
- }
-
- return this;
- }
-
- @Override
- public UserRolesAuthorizer forUser(BlockchainIdentity... userIds) {
- return UserAuthorizeOpTemplate.this.forUser(userIds);
- }
-
- @Override
- public UserRolesAuthorizer forUser(Bytes... userAddresses) {
- return UserAuthorizeOpTemplate.this.forUser(userAddresses);
- }
- }
-}
+package com.jd.blockchain.transaction;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.LinkedHashSet;
+import java.util.Set;
+
+import com.jd.blockchain.binaryproto.DataContractRegistry;
+import com.jd.blockchain.ledger.BlockchainIdentity;
+import com.jd.blockchain.ledger.RolesPolicy;
+import com.jd.blockchain.ledger.SecurityUtils;
+import com.jd.blockchain.ledger.UserAuthorizeOperation;
+import com.jd.blockchain.ledger.UserRegisterOperation;
+import com.jd.blockchain.utils.ArrayUtils;
+import com.jd.blockchain.utils.Bytes;
+
+public class UserAuthorizeOpTemplate implements UserAuthorizer, UserAuthorizeOperation {
+
+ static {
+ DataContractRegistry.register(UserRegisterOperation.class);
+ DataContractRegistry.register(UserAuthorizeOperation.class);
+ DataContractRegistry.register(UserRolesEntry.class);
+ }
+
+ private Set userAuthMap = Collections
+ .synchronizedSet(new LinkedHashSet());
+
+ public UserAuthorizeOpTemplate() {
+ }
+
+ public UserAuthorizeOpTemplate(BlockchainIdentity userID) {
+ }
+
+ @Override
+ public AuthorizationDataEntry[] getUserRolesAuthorizations() {
+ return ArrayUtils.toArray(userAuthMap, AuthorizationDataEntry.class);
+ }
+
+ @Override
+ public UserAuthorizeOperation getOperation() {
+ return this;
+ }
+
+ @Override
+ public UserRolesAuthorizer forUser(Bytes... userAddresses) {
+ AuthorizationDataEntry userRolesAuth = new AuthorizationDataEntry(userAddresses);
+ userAuthMap.add(userRolesAuth);
+ return userRolesAuth;
+ }
+
+ @Override
+ public UserRolesAuthorizer forUser(BlockchainIdentity... userIds) {
+ Bytes[] addresses = Arrays.stream(userIds).map(p -> p.getAddress()).toArray(Bytes[]::new);
+ return forUser(addresses);
+ }
+
+ private class AuthorizationDataEntry implements UserRolesAuthorizer, UserRolesEntry {
+
+ private Bytes[] userAddress;
+
+ private RolesPolicy policy = RolesPolicy.UNION;
+
+ private Set authRoles = new LinkedHashSet();
+ private Set unauthRoles = new LinkedHashSet();
+
+ private AuthorizationDataEntry(Bytes[] userAddress) {
+ this.userAddress = userAddress;
+ }
+
+ @Override
+ public Bytes[] getUserAddresses() {
+ return userAddress;
+ }
+
+ @Override
+ public RolesPolicy getPolicy() {
+ return policy;
+ }
+
+ @Override
+ public String[] getAuthorizedRoles() {
+ return ArrayUtils.toArray(authRoles, String.class);
+ }
+
+ @Override
+ public String[] getUnauthorizedRoles() {
+ return ArrayUtils.toArray(unauthRoles, String.class);
+ }
+
+ @Override
+ public UserRolesAuthorizer setPolicy(RolesPolicy policy) {
+ this.policy = policy;
+ return this;
+ }
+
+ @Override
+ public UserRolesAuthorizer authorize(String... roles) {
+ String roleName;
+ for (String r : roles) {
+ roleName = SecurityUtils.formatRoleName(r);
+ authRoles.add(roleName);
+ unauthRoles.remove(roleName);
+ }
+
+ return this;
+ }
+
+ @Override
+ public UserRolesAuthorizer unauthorize(String... roles) {
+ String roleName;
+ for (String r : roles) {
+ roleName = SecurityUtils.formatRoleName(r);
+ unauthRoles.add(roleName);
+ authRoles.remove(roleName);
+ }
+
+ return this;
+ }
+
+ @Override
+ public UserRolesAuthorizer forUser(BlockchainIdentity... userIds) {
+ return UserAuthorizeOpTemplate.this.forUser(userIds);
+ }
+
+ @Override
+ public UserRolesAuthorizer forUser(Bytes... userAddresses) {
+ return UserAuthorizeOpTemplate.this.forUser(userAddresses);
+ }
+ }
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserRegisterOpTemplate.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserRegisterOpTemplate.java
index 91ea541a..38f921df 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserRegisterOpTemplate.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserRegisterOpTemplate.java
@@ -1,27 +1,27 @@
-package com.jd.blockchain.transaction;
-
-import com.jd.blockchain.binaryproto.DataContractRegistry;
-import com.jd.blockchain.ledger.BlockchainIdentity;
-import com.jd.blockchain.ledger.UserRegisterOperation;
-
-public class UserRegisterOpTemplate implements UserRegisterOperation {
-
- static {
- DataContractRegistry.register(UserRegisterOperation.class);
- }
-
- private BlockchainIdentity userID;
-
- public UserRegisterOpTemplate() {
- }
-
- public UserRegisterOpTemplate(BlockchainIdentity userID) {
- this.userID = userID;
- }
-
- @Override
- public BlockchainIdentity getUserID() {
- return userID;
- }
-
-}
+package com.jd.blockchain.transaction;
+
+import com.jd.blockchain.binaryproto.DataContractRegistry;
+import com.jd.blockchain.ledger.BlockchainIdentity;
+import com.jd.blockchain.ledger.UserRegisterOperation;
+
+public class UserRegisterOpTemplate implements UserRegisterOperation {
+
+ static {
+ DataContractRegistry.register(UserRegisterOperation.class);
+ }
+
+ private BlockchainIdentity userID;
+
+ public UserRegisterOpTemplate() {
+ }
+
+ public UserRegisterOpTemplate(BlockchainIdentity userID) {
+ this.userID = userID;
+ }
+
+ @Override
+ public BlockchainIdentity getUserID() {
+ return userID;
+ }
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserRegisterOperationBuilder.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserRegisterOperationBuilder.java
index 76f0e956..283f2a9f 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserRegisterOperationBuilder.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserRegisterOperationBuilder.java
@@ -1,19 +1,19 @@
-package com.jd.blockchain.transaction;
-
-import com.jd.blockchain.ledger.BlockchainIdentity;
-import com.jd.blockchain.ledger.UserRegisterOperation;
-
-public interface UserRegisterOperationBuilder {
-
- /**
- * 注册;
- *
- * @param id
- * 区块链身份;
- * @param stateType
- * 负载类型;
- * @return
- */
- UserRegisterOperation register(BlockchainIdentity userID);
-
-}
+package com.jd.blockchain.transaction;
+
+import com.jd.blockchain.ledger.BlockchainIdentity;
+import com.jd.blockchain.ledger.UserRegisterOperation;
+
+public interface UserRegisterOperationBuilder {
+
+ /**
+ * 注册;
+ *
+ * @param id
+ * 区块链身份;
+ * @param stateType
+ * 负载类型;
+ * @return
+ */
+ UserRegisterOperation register(BlockchainIdentity userID);
+
+}
diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserRegisterOperationBuilderImpl.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserRegisterOperationBuilderImpl.java
index 39a84725..c33f91cd 100644
--- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserRegisterOperationBuilderImpl.java
+++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserRegisterOperationBuilderImpl.java
@@ -1,15 +1,15 @@
-package com.jd.blockchain.transaction;
-
-import com.jd.blockchain.ledger.BlockchainIdentity;
-import com.jd.blockchain.ledger.UserRegisterOperation;
-
-public class UserRegisterOperationBuilderImpl implements UserRegisterOperationBuilder{
-
- @Override
- public UserRegisterOperation register(BlockchainIdentity userID) {
- return new UserRegisterOpTemplate(userID);
- }
-
-
-
-}
+package com.jd.blockchain.transaction;
+
+import com.jd.blockchain.ledger.BlockchainIdentity;
+import com.jd.blockchain.ledger.UserRegisterOperation;
+
+public class UserRegisterOperationBuilderImpl implements UserRegisterOperationBuilder{
+
+ @Override
+ public UserRegisterOperation register(BlockchainIdentity userID) {
+ return new UserRegisterOpTemplate(userID);
+ }
+
+
+
+}
diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/BytesEncodingTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/BytesEncodingTest.java
index 32d48aba..69b244a1 100644
--- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/BytesEncodingTest.java
+++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/BytesEncodingTest.java
@@ -1,84 +1,84 @@
-package test.com.jd.blockchain.ledger;
-
-import static org.junit.Assert.*;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-
-import org.junit.Test;
-import org.mockito.Mockito;
-
-import com.jd.blockchain.utils.io.BytesEncoding;
-import com.jd.blockchain.utils.io.NumberMask;
-
-public class BytesEncodingTest {
-
- @Test
- public void testReadAndWriteSize() {
- assertReadAndWriteSizeOK(0, NumberMask.TINY);
- assertReadAndWriteSizeOK(255, NumberMask.TINY);
- assertReadAndWriteSizeOK(1, NumberMask.TINY);
- assertReadAndWriteSizeOK(128, NumberMask.TINY);
- assertReadAndWriteSizeError(256, NumberMask.TINY);
- assertReadAndWriteSizeError(Integer.MIN_VALUE, NumberMask.TINY);
- assertReadAndWriteSizeError(Integer.MAX_VALUE, NumberMask.TINY);
-
- assertReadAndWriteSizeOK(0, NumberMask.SHORT);
- assertReadAndWriteSizeOK(255, NumberMask.SHORT);
- assertReadAndWriteSizeOK(1, NumberMask.SHORT);
- assertReadAndWriteSizeOK(128, NumberMask.SHORT);
- assertReadAndWriteSizeOK(256, NumberMask.SHORT);
- assertReadAndWriteSizeOK(1 << 7, NumberMask.SHORT);
- assertReadAndWriteSizeOK((1 << 15) - 1, NumberMask.SHORT);
- assertReadAndWriteSizeError((1 << 15) + 1, NumberMask.SHORT);
- assertReadAndWriteSizeError(1 << 16, NumberMask.SHORT);
- assertReadAndWriteSizeError(Integer.MIN_VALUE, NumberMask.SHORT);
- assertReadAndWriteSizeError(Integer.MAX_VALUE, NumberMask.SHORT);
-
- assertReadAndWriteSizeOK(0, NumberMask.NORMAL);
- assertReadAndWriteSizeOK(255, NumberMask.NORMAL);
- assertReadAndWriteSizeOK(1, NumberMask.NORMAL);
- assertReadAndWriteSizeOK(128, NumberMask.NORMAL);
- assertReadAndWriteSizeOK(256, NumberMask.NORMAL);
- assertReadAndWriteSizeOK(1 << 7, NumberMask.NORMAL);
- assertReadAndWriteSizeOK((1 << 15) - 1, NumberMask.NORMAL);
- assertReadAndWriteSizeOK((1 << 15) + 1, NumberMask.NORMAL);
- assertReadAndWriteSizeOK(1 << 16, NumberMask.NORMAL);
- assertReadAndWriteSizeOK(Short.MAX_VALUE, NumberMask.NORMAL);
- assertReadAndWriteSizeOK((1 << 16) - 1, NumberMask.NORMAL);
- assertReadAndWriteSizeOK(1 << 24, NumberMask.NORMAL);
- assertReadAndWriteSizeOK((1 << 24) - 1, NumberMask.NORMAL);
- assertReadAndWriteSizeOK((1 << 30) - 1, NumberMask.NORMAL);
- assertReadAndWriteSizeError(1 << 30, NumberMask.NORMAL);
- assertReadAndWriteSizeError(Integer.MIN_VALUE, NumberMask.NORMAL);
- assertReadAndWriteSizeError(Integer.MAX_VALUE, NumberMask.NORMAL);
- }
-
- private void assertReadAndWriteSizeError(int size, NumberMask mask) {
- Exception error = null;
- try {
- assertReadAndWriteSizeOK(size, mask);
- } catch (Exception e) {
- error = e;
- }
- assertNotNull(error);
- }
-
- private void assertReadAndWriteSizeOK(int size, NumberMask mask) {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- mask.writeMask(size, out);
-
- byte[] sizebytes = out.toByteArray();
-
- assertTrue(sizebytes.length <= mask.MAX_HEADER_LENGTH);
- assertTrue(size <= mask.getBoundarySize(sizebytes.length));
-
- ByteArrayInputStream in = new ByteArrayInputStream(sizebytes);
- int sizeResolved = mask.resolveMaskedNumber(in);
-
- assertEquals(size, sizeResolved);
-
- assertTrue(in.available() == 0);
- }
-
-}
+package test.com.jd.blockchain.ledger;
+
+import static org.junit.Assert.*;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import com.jd.blockchain.utils.io.BytesEncoding;
+import com.jd.blockchain.utils.io.NumberMask;
+
+public class BytesEncodingTest {
+
+ @Test
+ public void testReadAndWriteSize() {
+ assertReadAndWriteSizeOK(0, NumberMask.TINY);
+ assertReadAndWriteSizeOK(255, NumberMask.TINY);
+ assertReadAndWriteSizeOK(1, NumberMask.TINY);
+ assertReadAndWriteSizeOK(128, NumberMask.TINY);
+ assertReadAndWriteSizeError(256, NumberMask.TINY);
+ assertReadAndWriteSizeError(Integer.MIN_VALUE, NumberMask.TINY);
+ assertReadAndWriteSizeError(Integer.MAX_VALUE, NumberMask.TINY);
+
+ assertReadAndWriteSizeOK(0, NumberMask.SHORT);
+ assertReadAndWriteSizeOK(255, NumberMask.SHORT);
+ assertReadAndWriteSizeOK(1, NumberMask.SHORT);
+ assertReadAndWriteSizeOK(128, NumberMask.SHORT);
+ assertReadAndWriteSizeOK(256, NumberMask.SHORT);
+ assertReadAndWriteSizeOK(1 << 7, NumberMask.SHORT);
+ assertReadAndWriteSizeOK((1 << 15) - 1, NumberMask.SHORT);
+ assertReadAndWriteSizeError((1 << 15) + 1, NumberMask.SHORT);
+ assertReadAndWriteSizeError(1 << 16, NumberMask.SHORT);
+ assertReadAndWriteSizeError(Integer.MIN_VALUE, NumberMask.SHORT);
+ assertReadAndWriteSizeError(Integer.MAX_VALUE, NumberMask.SHORT);
+
+ assertReadAndWriteSizeOK(0, NumberMask.NORMAL);
+ assertReadAndWriteSizeOK(255, NumberMask.NORMAL);
+ assertReadAndWriteSizeOK(1, NumberMask.NORMAL);
+ assertReadAndWriteSizeOK(128, NumberMask.NORMAL);
+ assertReadAndWriteSizeOK(256, NumberMask.NORMAL);
+ assertReadAndWriteSizeOK(1 << 7, NumberMask.NORMAL);
+ assertReadAndWriteSizeOK((1 << 15) - 1, NumberMask.NORMAL);
+ assertReadAndWriteSizeOK((1 << 15) + 1, NumberMask.NORMAL);
+ assertReadAndWriteSizeOK(1 << 16, NumberMask.NORMAL);
+ assertReadAndWriteSizeOK(Short.MAX_VALUE, NumberMask.NORMAL);
+ assertReadAndWriteSizeOK((1 << 16) - 1, NumberMask.NORMAL);
+ assertReadAndWriteSizeOK(1 << 24, NumberMask.NORMAL);
+ assertReadAndWriteSizeOK((1 << 24) - 1, NumberMask.NORMAL);
+ assertReadAndWriteSizeOK((1 << 30) - 1, NumberMask.NORMAL);
+ assertReadAndWriteSizeError(1 << 30, NumberMask.NORMAL);
+ assertReadAndWriteSizeError(Integer.MIN_VALUE, NumberMask.NORMAL);
+ assertReadAndWriteSizeError(Integer.MAX_VALUE, NumberMask.NORMAL);
+ }
+
+ private void assertReadAndWriteSizeError(int size, NumberMask mask) {
+ Exception error = null;
+ try {
+ assertReadAndWriteSizeOK(size, mask);
+ } catch (Exception e) {
+ error = e;
+ }
+ assertNotNull(error);
+ }
+
+ private void assertReadAndWriteSizeOK(int size, NumberMask mask) {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ mask.writeMask(size, out);
+
+ byte[] sizebytes = out.toByteArray();
+
+ assertTrue(sizebytes.length <= mask.MAX_HEADER_LENGTH);
+ assertTrue(size <= mask.getBoundarySize(sizebytes.length));
+
+ ByteArrayInputStream in = new ByteArrayInputStream(sizebytes);
+ int sizeResolved = mask.resolveMaskedNumber(in);
+
+ assertEquals(size, sizeResolved);
+
+ assertTrue(in.available() == 0);
+ }
+
+}
diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/OpBlobTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/OpBlobTest.java
index 6ea6da45..365c737b 100644
--- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/OpBlobTest.java
+++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/OpBlobTest.java
@@ -1,83 +1,83 @@
-package test.com.jd.blockchain.ledger;
-//package test.com.jd.blockchain.ledger.data;
-//
-//import static org.junit.Assert.*;
-//
-//import java.io.IOException;
-//
-//import org.junit.Test;
-//
-//import com.jd.blockchain.ledger.StateOpType;
-//import com.jd.blockchain.ledger.Operation;
-//import com.jd.blockchain.ledger.OperationType;
-//import com.jd.blockchain.ledger.data.OpBlob;
-//
-//import my.utils.io.ByteArray;
-//import my.utils.io.BytesUtils;
-//import my.utils.security.RandomUtils;
-//
-//public class OpBlobTest {
-//
-// /**
-// * 验证无子操作的情形;
-// *
-// * @throws IOException
-// */
-// @Test
-// public void testSerializeNoSubOP() throws IOException {
-// OpBlob op = new OpBlob();
-// byte[] opArg = RandomUtils.generateRandomBytes(16);
-// op.setOperation(OperationType.REGISTER_USER.CODE, ByteArray.wrap(opArg));
-//
-// byte[] opBytes = BytesUtils.toBytes(op);
-//
-// assertEquals(OperationType.REGISTER_USER.CODE, opBytes[0]);
-//
-// OpBlob resolvedOP = new OpBlob();
-// resolvedOP.resolvFrom(ByteArray.wrap(opBytes).asInputStream());
-//
-// assertEquals(op.getCode(), resolvedOP.getCode());
-// assertEquals(op.getArgCount(), resolvedOP.getArgCount());
-// assertEquals(0, resolvedOP.getSubOperations().length);
-// assertEquals(op.getSubOperations().length, resolvedOP.getSubOperations().length);
-//
-// }
-//
-// /**
-// * 验证有子操作的情形;
-// *
-// * @throws IOException
-// */
-// @Test
-// public void testSerializeWithSubOP() throws IOException {
-// OpBlob op = new OpBlob();
-// byte[] opArg = RandomUtils.generateRandomBytes(16);
-// op.setOperation(OperationType.REGISTER_USER.CODE, ByteArray.wrap(opArg));
-//
-// byte[] subopArg = RandomUtils.generateRandomBytes(16);
-// op.addSubOperation(StateOpType.SET, ByteArray.wrap(subopArg));
-//
-// byte[] opBytes = BytesUtils.toBytes(op);
-//
-// assertEquals(OperationType.REGISTER_USER.CODE, opBytes[0]);
-//
-// OpBlob resolvedOP = new OpBlob();
-// resolvedOP.resolvFrom(ByteArray.wrap(opBytes).asInputStream());
-//
-// assertEquals(op.getCode(), resolvedOP.getCode());
-// assertEquals(op.getArgCount(), resolvedOP.getArgCount());
-//
-// Operation[] subOps = op.getSubOperations();
-// Operation[] resolvedSubOps = resolvedOP.getSubOperations();
-// assertEquals(1, subOps.length);
-// assertEquals(subOps.length, resolvedSubOps.length);
-//
-// for (int i = 0; i < resolvedSubOps.length; i++) {
-// assertEquals(subOps[i].getCode(), resolvedSubOps[i].getCode());
-// assertEquals(1, resolvedSubOps[i].getArgCount());
-// assertEquals(subOps[i].getArgCount(), resolvedSubOps[i].getArgCount());
-// assertEquals(subOps[i].getArg(0), resolvedSubOps[i].getArg(0));
-// }
-// }
-//
-//}
+package test.com.jd.blockchain.ledger;
+//package test.com.jd.blockchain.ledger.data;
+//
+//import static org.junit.Assert.*;
+//
+//import java.io.IOException;
+//
+//import org.junit.Test;
+//
+//import com.jd.blockchain.ledger.StateOpType;
+//import com.jd.blockchain.ledger.Operation;
+//import com.jd.blockchain.ledger.OperationType;
+//import com.jd.blockchain.ledger.data.OpBlob;
+//
+//import my.utils.io.ByteArray;
+//import my.utils.io.BytesUtils;
+//import my.utils.security.RandomUtils;
+//
+//public class OpBlobTest {
+//
+// /**
+// * 验证无子操作的情形;
+// *
+// * @throws IOException
+// */
+// @Test
+// public void testSerializeNoSubOP() throws IOException {
+// OpBlob op = new OpBlob();
+// byte[] opArg = RandomUtils.generateRandomBytes(16);
+// op.setOperation(OperationType.REGISTER_USER.CODE, ByteArray.wrap(opArg));
+//
+// byte[] opBytes = BytesUtils.toBytes(op);
+//
+// assertEquals(OperationType.REGISTER_USER.CODE, opBytes[0]);
+//
+// OpBlob resolvedOP = new OpBlob();
+// resolvedOP.resolvFrom(ByteArray.wrap(opBytes).asInputStream());
+//
+// assertEquals(op.getCode(), resolvedOP.getCode());
+// assertEquals(op.getArgCount(), resolvedOP.getArgCount());
+// assertEquals(0, resolvedOP.getSubOperations().length);
+// assertEquals(op.getSubOperations().length, resolvedOP.getSubOperations().length);
+//
+// }
+//
+// /**
+// * 验证有子操作的情形;
+// *
+// * @throws IOException
+// */
+// @Test
+// public void testSerializeWithSubOP() throws IOException {
+// OpBlob op = new OpBlob();
+// byte[] opArg = RandomUtils.generateRandomBytes(16);
+// op.setOperation(OperationType.REGISTER_USER.CODE, ByteArray.wrap(opArg));
+//
+// byte[] subopArg = RandomUtils.generateRandomBytes(16);
+// op.addSubOperation(StateOpType.SET, ByteArray.wrap(subopArg));
+//
+// byte[] opBytes = BytesUtils.toBytes(op);
+//
+// assertEquals(OperationType.REGISTER_USER.CODE, opBytes[0]);
+//
+// OpBlob resolvedOP = new OpBlob();
+// resolvedOP.resolvFrom(ByteArray.wrap(opBytes).asInputStream());
+//
+// assertEquals(op.getCode(), resolvedOP.getCode());
+// assertEquals(op.getArgCount(), resolvedOP.getArgCount());
+//
+// Operation[] subOps = op.getSubOperations();
+// Operation[] resolvedSubOps = resolvedOP.getSubOperations();
+// assertEquals(1, subOps.length);
+// assertEquals(subOps.length, resolvedSubOps.length);
+//
+// for (int i = 0; i < resolvedSubOps.length; i++) {
+// assertEquals(subOps[i].getCode(), resolvedSubOps[i].getCode());
+// assertEquals(1, resolvedSubOps[i].getArgCount());
+// assertEquals(subOps[i].getArgCount(), resolvedSubOps[i].getArgCount());
+// assertEquals(subOps[i].getArg(0), resolvedSubOps[i].getArg(0));
+// }
+// }
+//
+//}
diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/SizeHeaderMaskTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/SizeHeaderMaskTest.java
index b8e7875c..148cf75d 100644
--- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/SizeHeaderMaskTest.java
+++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/SizeHeaderMaskTest.java
@@ -1,40 +1,40 @@
-package test.com.jd.blockchain.ledger;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import org.junit.Test;
-
-import com.jd.blockchain.utils.io.NumberMask;
-
-
-public class SizeHeaderMaskTest {
-
- @Test
- public void testSizeHeaderMask() {
- assertTrue(NumberMask.TINY.MAX_HEADER_LENGTH == 1);
- assertEquals(256, NumberMask.TINY.getBoundarySize(1));
-
- assertTrue(NumberMask.SHORT.MAX_HEADER_LENGTH == 2);
- assertEquals(128, NumberMask.SHORT.getBoundarySize(1));
- assertEquals(32768, NumberMask.SHORT.getBoundarySize(2));
-
- assertTrue(NumberMask.NORMAL.MAX_HEADER_LENGTH == 4);
- assertEquals(64, NumberMask.NORMAL.getBoundarySize(1));
- assertEquals(16384, NumberMask.NORMAL.getBoundarySize(2));
- assertEquals(4194304, NumberMask.NORMAL.getBoundarySize(3));
- assertEquals(1073741824, NumberMask.NORMAL.getBoundarySize(4));
-
- //不考虑 long 的情况;
-// assertTrue(SizeHeaderMask.LONG.MAX_HEADER_LENGTH == 8);
-// assertEquals(32L, SizeHeaderMask.LONG.getBoundarySize((byte)1));
-// assertEquals(8192L, SizeHeaderMask.LONG.getBoundarySize((byte)2));
-// assertEquals(2097152L, SizeHeaderMask.LONG.getBoundarySize((byte)3));
-// assertEquals(536870912L, SizeHeaderMask.LONG.getBoundarySize((byte)4));
-// assertEquals(137438953472L, SizeHeaderMask.LONG.getBoundarySize((byte)5));
-// assertEquals(35184372088832L, SizeHeaderMask.LONG.getBoundarySize((byte)6));
-// assertEquals(9007199254740992L, SizeHeaderMask.LONG.getBoundarySize((byte)7));
-// assertEquals(2305843009213693952L, SizeHeaderMask.LONG.getBoundarySize((byte)8));
- }
-
-}
+package test.com.jd.blockchain.ledger;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+import com.jd.blockchain.utils.io.NumberMask;
+
+
+public class SizeHeaderMaskTest {
+
+ @Test
+ public void testSizeHeaderMask() {
+ assertTrue(NumberMask.TINY.MAX_HEADER_LENGTH == 1);
+ assertEquals(256, NumberMask.TINY.getBoundarySize(1));
+
+ assertTrue(NumberMask.SHORT.MAX_HEADER_LENGTH == 2);
+ assertEquals(128, NumberMask.SHORT.getBoundarySize(1));
+ assertEquals(32768, NumberMask.SHORT.getBoundarySize(2));
+
+ assertTrue(NumberMask.NORMAL.MAX_HEADER_LENGTH == 4);
+ assertEquals(64, NumberMask.NORMAL.getBoundarySize(1));
+ assertEquals(16384, NumberMask.NORMAL.getBoundarySize(2));
+ assertEquals(4194304, NumberMask.NORMAL.getBoundarySize(3));
+ assertEquals(1073741824, NumberMask.NORMAL.getBoundarySize(4));
+
+ //不考虑 long 的情况;
+// assertTrue(SizeHeaderMask.LONG.MAX_HEADER_LENGTH == 8);
+// assertEquals(32L, SizeHeaderMask.LONG.getBoundarySize((byte)1));
+// assertEquals(8192L, SizeHeaderMask.LONG.getBoundarySize((byte)2));
+// assertEquals(2097152L, SizeHeaderMask.LONG.getBoundarySize((byte)3));
+// assertEquals(536870912L, SizeHeaderMask.LONG.getBoundarySize((byte)4));
+// assertEquals(137438953472L, SizeHeaderMask.LONG.getBoundarySize((byte)5));
+// assertEquals(35184372088832L, SizeHeaderMask.LONG.getBoundarySize((byte)6));
+// assertEquals(9007199254740992L, SizeHeaderMask.LONG.getBoundarySize((byte)7));
+// assertEquals(2305843009213693952L, SizeHeaderMask.LONG.getBoundarySize((byte)8));
+ }
+
+}
diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/TxContentBlobTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/TxContentBlobTest.java
index c8d8c313..c920db09 100644
--- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/TxContentBlobTest.java
+++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/TxContentBlobTest.java
@@ -1,116 +1,116 @@
-package test.com.jd.blockchain.ledger;
-
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-
-import java.io.IOException;
-import java.util.UUID;
-
-import org.junit.Before;
-import org.junit.Test;
-
-import com.jd.blockchain.binaryproto.BinaryProtocol;
-import com.jd.blockchain.binaryproto.DataContractRegistry;
-import com.jd.blockchain.crypto.Crypto;
-import com.jd.blockchain.crypto.HashDigest;
-import com.jd.blockchain.ledger.BlockchainKeyGenerator;
-import com.jd.blockchain.ledger.BlockchainKeypair;
-import com.jd.blockchain.ledger.DataAccountKVSetOperation;
-import com.jd.blockchain.ledger.HashObject;
-import com.jd.blockchain.ledger.Operation;
-import com.jd.blockchain.ledger.TransactionContent;
-import com.jd.blockchain.ledger.TransactionContentBody;
-import com.jd.blockchain.transaction.BlockchainOperationFactory;
-import com.jd.blockchain.transaction.TxContentBlob;
-
-public class TxContentBlobTest {
-
- private TxContentBlob contentBlob;
-
- @Before
- public void initTxContentBlob() throws Exception {
- DataContractRegistry.register(TransactionContentBody.class);
- DataContractRegistry.register(TransactionContent.class);
- DataContractRegistry.register(HashObject.class);
-
- BlockchainKeypair id = BlockchainKeyGenerator.getInstance().generate("ED25519");
-
- HashDigest ledgerHash = Crypto.getHashFunction("SHA256")
- .hash(UUID.randomUUID().toString().getBytes("UTF-8"));
-
- BlockchainOperationFactory opFactory = new BlockchainOperationFactory();
-
- contentBlob = new TxContentBlob(ledgerHash);
-
- HashDigest contentHash = Crypto.getHashFunction("SHA256")
- .hash("jd.com".getBytes());
- contentBlob.setHash(contentHash);
-
- DataAccountKVSetOperation kvsetOP = opFactory.dataAccount(id.getAddress())
- .setText("Name", "AAA", -1).getOperation();
- contentBlob.addOperation(kvsetOP);
- }
-
- @Test
- public void testSerialize_TransactionContentBody()
- throws IOException, InstantiationException, IllegalAccessException {
-
- byte[] bytesContent = BinaryProtocol.encode(contentBlob, TransactionContentBody.class);
- TransactionContentBody resolvedContentBlob = BinaryProtocol.decode(bytesContent);
-
- assertEquals(contentBlob.getLedgerHash(), resolvedContentBlob.getLedgerHash());
- // assertEquals(contentBlob.getSubjectAccount(),
- // resolvedContentBlob.getSubjectAccount());
- // assertEquals(contentBlob.getSequenceNumber(),
- // resolvedContentBlob.getSequenceNumber());
- assertEquals(contentBlob.getOperations().length, resolvedContentBlob.getOperations().length);
-
- assertEquals(contentBlob.getOperations().length, resolvedContentBlob.getOperations().length);
- Operation[] resolvedOperations = resolvedContentBlob.getOperations();
- Operation[] dataOperations = contentBlob.getOperations();
- for (int i = 0; i < dataOperations.length; i++) {
- DataAccountKVSetOperation resolvedOperation = (DataAccountKVSetOperation) resolvedOperations[i];
- DataAccountKVSetOperation dataOperation = (DataAccountKVSetOperation) dataOperations[i];
- assertEquals(dataOperation.getAccountAddress(), resolvedOperation.getAccountAddress());
- DataAccountKVSetOperation.KVWriteEntry[] dataKv = dataOperation.getWriteSet();
- DataAccountKVSetOperation.KVWriteEntry[] resolvedKv = resolvedOperation.getWriteSet();
- for (int j = 0; j < dataKv.length; j++) {
- assertEquals(dataKv[i].getKey(), resolvedKv[i].getKey());
- assertEquals(dataKv[i].getExpectedVersion(), resolvedKv[i].getExpectedVersion());
- assertArrayEquals(dataKv[i].getValue().getBytes().toBytes(),
- resolvedKv[i].getValue().getBytes().toBytes());
- }
- }
- }
-
- @Test
- public void testSerialize_TransactionContent() throws IOException, InstantiationException, IllegalAccessException {
-
- byte[] bytesContent = BinaryProtocol.encode(contentBlob, TransactionContent.class);
- TransactionContentBody resolvedContentBlob = BinaryProtocol.decode(bytesContent);
-
- assertEquals(contentBlob.getLedgerHash(), resolvedContentBlob.getLedgerHash());
- // assertEquals(contentBlob.getSubjectAccount(),
- // resolvedContentBlob.getSubjectAccount());
- // assertEquals(contentBlob.getSequenceNumber(),
- // resolvedContentBlob.getSequenceNumber());
- assertEquals(contentBlob.getOperations().length, resolvedContentBlob.getOperations().length);
-
- assertEquals(contentBlob.getOperations().length, resolvedContentBlob.getOperations().length);
- Operation[] resolvedOperations = resolvedContentBlob.getOperations();
- Operation[] dataOperations = contentBlob.getOperations();
- for (int i = 0; i < dataOperations.length; i++) {
- DataAccountKVSetOperation resolvedOperation = (DataAccountKVSetOperation) resolvedOperations[i];
- DataAccountKVSetOperation dataOperation = (DataAccountKVSetOperation) dataOperations[i];
- assertEquals(dataOperation.getAccountAddress(), resolvedOperation.getAccountAddress());
- DataAccountKVSetOperation.KVWriteEntry[] dataKv = dataOperation.getWriteSet();
- DataAccountKVSetOperation.KVWriteEntry[] resolvedKv = resolvedOperation.getWriteSet();
- for (int j = 0; j < dataKv.length; j++) {
- assertEquals(dataKv[i].getKey(), resolvedKv[i].getKey());
- assertEquals(dataKv[i].getExpectedVersion(), resolvedKv[i].getExpectedVersion());
- assertArrayEquals(dataKv[i].getValue().getBytes().toBytes(),
- resolvedKv[i].getValue().getBytes().toBytes());
- }
- }
- }
-}
+package test.com.jd.blockchain.ledger;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+
+import java.io.IOException;
+import java.util.UUID;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import com.jd.blockchain.binaryproto.BinaryProtocol;
+import com.jd.blockchain.binaryproto.DataContractRegistry;
+import com.jd.blockchain.crypto.Crypto;
+import com.jd.blockchain.crypto.HashDigest;
+import com.jd.blockchain.ledger.BlockchainKeyGenerator;
+import com.jd.blockchain.ledger.BlockchainKeypair;
+import com.jd.blockchain.ledger.DataAccountKVSetOperation;
+import com.jd.blockchain.ledger.HashObject;
+import com.jd.blockchain.ledger.Operation;
+import com.jd.blockchain.ledger.TransactionContent;
+import com.jd.blockchain.ledger.TransactionContentBody;
+import com.jd.blockchain.transaction.BlockchainOperationFactory;
+import com.jd.blockchain.transaction.TxContentBlob;
+
+public class TxContentBlobTest {
+
+ private TxContentBlob contentBlob;
+
+ @Before
+ public void initTxContentBlob() throws Exception {
+ DataContractRegistry.register(TransactionContentBody.class);
+ DataContractRegistry.register(TransactionContent.class);
+ DataContractRegistry.register(HashObject.class);
+
+ BlockchainKeypair id = BlockchainKeyGenerator.getInstance().generate("ED25519");
+
+ HashDigest ledgerHash = Crypto.getHashFunction("SHA256")
+ .hash(UUID.randomUUID().toString().getBytes("UTF-8"));
+
+ BlockchainOperationFactory opFactory = new BlockchainOperationFactory();
+
+ contentBlob = new TxContentBlob(ledgerHash);
+
+ HashDigest contentHash = Crypto.getHashFunction("SHA256")
+ .hash("jd.com".getBytes());
+ contentBlob.setHash(contentHash);
+
+ DataAccountKVSetOperation kvsetOP = opFactory.dataAccount(id.getAddress())
+ .setText("Name", "AAA", -1).getOperation();
+ contentBlob.addOperation(kvsetOP);
+ }
+
+ @Test
+ public void testSerialize_TransactionContentBody()
+ throws IOException, InstantiationException, IllegalAccessException {
+
+ byte[] bytesContent = BinaryProtocol.encode(contentBlob, TransactionContentBody.class);
+ TransactionContentBody resolvedContentBlob = BinaryProtocol.decode(bytesContent);
+
+ assertEquals(contentBlob.getLedgerHash(), resolvedContentBlob.getLedgerHash());
+ // assertEquals(contentBlob.getSubjectAccount(),
+ // resolvedContentBlob.getSubjectAccount());
+ // assertEquals(contentBlob.getSequenceNumber(),
+ // resolvedContentBlob.getSequenceNumber());
+ assertEquals(contentBlob.getOperations().length, resolvedContentBlob.getOperations().length);
+
+ assertEquals(contentBlob.getOperations().length, resolvedContentBlob.getOperations().length);
+ Operation[] resolvedOperations = resolvedContentBlob.getOperations();
+ Operation[] dataOperations = contentBlob.getOperations();
+ for (int i = 0; i < dataOperations.length; i++) {
+ DataAccountKVSetOperation resolvedOperation = (DataAccountKVSetOperation) resolvedOperations[i];
+ DataAccountKVSetOperation dataOperation = (DataAccountKVSetOperation) dataOperations[i];
+ assertEquals(dataOperation.getAccountAddress(), resolvedOperation.getAccountAddress());
+ DataAccountKVSetOperation.KVWriteEntry[] dataKv = dataOperation.getWriteSet();
+ DataAccountKVSetOperation.KVWriteEntry[] resolvedKv = resolvedOperation.getWriteSet();
+ for (int j = 0; j < dataKv.length; j++) {
+ assertEquals(dataKv[i].getKey(), resolvedKv[i].getKey());
+ assertEquals(dataKv[i].getExpectedVersion(), resolvedKv[i].getExpectedVersion());
+ assertArrayEquals(dataKv[i].getValue().getBytes().toBytes(),
+ resolvedKv[i].getValue().getBytes().toBytes());
+ }
+ }
+ }
+
+ @Test
+ public void testSerialize_TransactionContent() throws IOException, InstantiationException, IllegalAccessException {
+
+ byte[] bytesContent = BinaryProtocol.encode(contentBlob, TransactionContent.class);
+ TransactionContentBody resolvedContentBlob = BinaryProtocol.decode(bytesContent);
+
+ assertEquals(contentBlob.getLedgerHash(), resolvedContentBlob.getLedgerHash());
+ // assertEquals(contentBlob.getSubjectAccount(),
+ // resolvedContentBlob.getSubjectAccount());
+ // assertEquals(contentBlob.getSequenceNumber(),
+ // resolvedContentBlob.getSequenceNumber());
+ assertEquals(contentBlob.getOperations().length, resolvedContentBlob.getOperations().length);
+
+ assertEquals(contentBlob.getOperations().length, resolvedContentBlob.getOperations().length);
+ Operation[] resolvedOperations = resolvedContentBlob.getOperations();
+ Operation[] dataOperations = contentBlob.getOperations();
+ for (int i = 0; i < dataOperations.length; i++) {
+ DataAccountKVSetOperation resolvedOperation = (DataAccountKVSetOperation) resolvedOperations[i];
+ DataAccountKVSetOperation dataOperation = (DataAccountKVSetOperation) dataOperations[i];
+ assertEquals(dataOperation.getAccountAddress(), resolvedOperation.getAccountAddress());
+ DataAccountKVSetOperation.KVWriteEntry[] dataKv = dataOperation.getWriteSet();
+ DataAccountKVSetOperation.KVWriteEntry[] resolvedKv = resolvedOperation.getWriteSet();
+ for (int j = 0; j < dataKv.length; j++) {
+ assertEquals(dataKv[i].getKey(), resolvedKv[i].getKey());
+ assertEquals(dataKv[i].getExpectedVersion(), resolvedKv[i].getExpectedVersion());
+ assertArrayEquals(dataKv[i].getValue().getBytes().toBytes(),
+ resolvedKv[i].getValue().getBytes().toBytes());
+ }
+ }
+ }
+}
diff --git a/source/peer/config/hosts.config b/source/peer/config/hosts.config
index 8d5fdf76..d1775d3a 100644
--- a/source/peer/config/hosts.config
+++ b/source/peer/config/hosts.config
@@ -1,36 +1,36 @@
-# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# This file defines the replicas ids, IPs and ports.
-# It is used by the replicas and clients to find connection info
-# to the initial replicas.
-# The ports defined here are the ports used by clients to communicate
-# with the replicas. Additional connections are opened by replicas to
-# communicate with each other. This additional connection is opened in the
-# next port defined here. For an example, consider the line "0 127.0.0.1 11000".
-# That means that clients will open a communication channel to replica 0 in
-# IP 127.0.0.1 and port 11000. On startup, replicas with id different than 0
-# will open a communication channel to replica 0 in port 11001.
-# The same holds for replicas 1, 2, 3 ... N.
-
-#server id, address and port (the ids from 0 to n-1 are the service replicas)
-0 127.0.0.1 11000
-1 127.0.0.1 11010
-2 127.0.0.1 11020
-3 127.0.0.1 11030
-#4 192.168.151.33 11040
-#5 192.168.151.38 11050
-#6 127.0.0.1 11060
-#7 127.0.0.1 11070
-7001 127.0.0.1 11100
+# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# This file defines the replicas ids, IPs and ports.
+# It is used by the replicas and clients to find connection info
+# to the initial replicas.
+# The ports defined here are the ports used by clients to communicate
+# with the replicas. Additional connections are opened by replicas to
+# communicate with each other. This additional connection is opened in the
+# next port defined here. For an example, consider the line "0 127.0.0.1 11000".
+# That means that clients will open a communication channel to replica 0 in
+# IP 127.0.0.1 and port 11000. On startup, replicas with id different than 0
+# will open a communication channel to replica 0 in port 11001.
+# The same holds for replicas 1, 2, 3 ... N.
+
+#server id, address and port (the ids from 0 to n-1 are the service replicas)
+0 127.0.0.1 11000
+1 127.0.0.1 11010
+2 127.0.0.1 11020
+3 127.0.0.1 11030
+#4 192.168.151.33 11040
+#5 192.168.151.38 11050
+#6 127.0.0.1 11060
+#7 127.0.0.1 11070
+7001 127.0.0.1 11100
diff --git a/source/peer/config/system.config b/source/peer/config/system.config
index c5bb2fa4..3da6e093 100644
--- a/source/peer/config/system.config
+++ b/source/peer/config/system.config
@@ -1,121 +1,121 @@
-# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-############################################
-####### Communication Configurations #######
-############################################
-
-#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value)
-#This parameter is not currently being used being used
-#system.authentication.hmacAlgorithm = HmacSHA1
-
-#Specify if the communication system should use a thread to send data (true or false)
-system.communication.useSenderThread = true
-
-#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments
-#and benchmarks, but must not be used in production systems.
-system.communication.defaultkeys = true
-
-############################################
-### Replication Algorithm Configurations ###
-############################################
-
-#Number of servers in the group
-system.servers.num = 4
-
-#Maximum number of faulty replicas
-system.servers.f = 1
-
-#Timeout to asking for a client request
-system.totalordermulticast.timeout = 2000
-
-
-#Maximum batch size (in number of messages)
-system.totalordermulticast.maxbatchsize = 400
-
-#Number of nonces (for non-determinism actions) generated
-system.totalordermulticast.nonces = 10
-
-#if verification of leader-generated timestamps are increasing
-#it can only be used on systems in which the network clocks
-#are synchronized
-system.totalordermulticast.verifyTimestamps = false
-
-#Quantity of messages that can be stored in the receive queue of the communication system
-system.communication.inQueueSize = 500000
-
-# Quantity of messages that can be stored in the send queue of each replica
-system.communication.outQueueSize = 500000
-
-#Set to 1 if SMaRt should use signatures, set to 0 if otherwise
-system.communication.useSignatures = 0
-
-#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise
-system.communication.useMACs = 1
-
-#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise
-system.debug = 0
-
-#Print information about the replica when it is shutdown
-system.shutdownhook = true
-
-############################################
-###### State Transfer Configurations #######
-############################################
-
-#Activate the state transfer protocol ('true' to activate, 'false' to de-activate)
-system.totalordermulticast.state_transfer = true
-
-#Maximum ahead-of-time message not discarded
-system.totalordermulticast.highMark = 10000
-
-#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered)
-system.totalordermulticast.revival_highMark = 10
-
-#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs
-system.totalordermulticast.timeout_highMark = 200
-
-############################################
-###### Log and Checkpoint Configurations ###
-############################################
-
-system.totalordermulticast.log = true
-system.totalordermulticast.log_parallel = false
-system.totalordermulticast.log_to_disk = false
-system.totalordermulticast.sync_log = false
-
-#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol)
-system.totalordermulticast.checkpoint_period = 1000
-system.totalordermulticast.global_checkpoint_period = 120000
-
-system.totalordermulticast.checkpoint_to_disk = false
-system.totalordermulticast.sync_ckp = false
-
-
-############################################
-###### Reconfiguration Configurations ######
-############################################
-
-#Replicas ID for the initial view, separated by a comma.
-# The number of replicas in this parameter should be equal to that specified in 'system.servers.num'
-system.initial.view = 0,1,2,3
-
-#The ID of the trust third party (TTP)
-system.ttp.id = 7002
-
-#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults
-system.bft = true
-
-#Custom View Storage;
-#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage
+# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+############################################
+####### Communication Configurations #######
+############################################
+
+#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value)
+#This parameter is not currently being used being used
+#system.authentication.hmacAlgorithm = HmacSHA1
+
+#Specify if the communication system should use a thread to send data (true or false)
+system.communication.useSenderThread = true
+
+#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments
+#and benchmarks, but must not be used in production systems.
+system.communication.defaultkeys = true
+
+############################################
+### Replication Algorithm Configurations ###
+############################################
+
+#Number of servers in the group
+system.servers.num = 4
+
+#Maximum number of faulty replicas
+system.servers.f = 1
+
+#Timeout to asking for a client request
+system.totalordermulticast.timeout = 2000
+
+
+#Maximum batch size (in number of messages)
+system.totalordermulticast.maxbatchsize = 400
+
+#Number of nonces (for non-determinism actions) generated
+system.totalordermulticast.nonces = 10
+
+#if verification of leader-generated timestamps are increasing
+#it can only be used on systems in which the network clocks
+#are synchronized
+system.totalordermulticast.verifyTimestamps = false
+
+#Quantity of messages that can be stored in the receive queue of the communication system
+system.communication.inQueueSize = 500000
+
+# Quantity of messages that can be stored in the send queue of each replica
+system.communication.outQueueSize = 500000
+
+#Set to 1 if SMaRt should use signatures, set to 0 if otherwise
+system.communication.useSignatures = 0
+
+#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise
+system.communication.useMACs = 1
+
+#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise
+system.debug = 0
+
+#Print information about the replica when it is shutdown
+system.shutdownhook = true
+
+############################################
+###### State Transfer Configurations #######
+############################################
+
+#Activate the state transfer protocol ('true' to activate, 'false' to de-activate)
+system.totalordermulticast.state_transfer = true
+
+#Maximum ahead-of-time message not discarded
+system.totalordermulticast.highMark = 10000
+
+#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered)
+system.totalordermulticast.revival_highMark = 10
+
+#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs
+system.totalordermulticast.timeout_highMark = 200
+
+############################################
+###### Log and Checkpoint Configurations ###
+############################################
+
+system.totalordermulticast.log = true
+system.totalordermulticast.log_parallel = false
+system.totalordermulticast.log_to_disk = false
+system.totalordermulticast.sync_log = false
+
+#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol)
+system.totalordermulticast.checkpoint_period = 1000
+system.totalordermulticast.global_checkpoint_period = 120000
+
+system.totalordermulticast.checkpoint_to_disk = false
+system.totalordermulticast.sync_ckp = false
+
+
+############################################
+###### Reconfiguration Configurations ######
+############################################
+
+#Replicas ID for the initial view, separated by a comma.
+# The number of replicas in this parameter should be equal to that specified in 'system.servers.num'
+system.initial.view = 0,1,2,3
+
+#The ID of the trust third party (TTP)
+system.ttp.id = 7002
+
+#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults
+system.bft = true
+
+#Custom View Storage;
+#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage
diff --git a/source/peer/pom.xml b/source/peer/pom.xml
index 23a08185..bc0fcfb3 100644
--- a/source/peer/pom.xml
+++ b/source/peer/pom.xml
@@ -1,98 +1,98 @@
-
- 4.0.0
-
- com.jd.blockchain
- jdchain-root
- 1.1.2.RELEASE
-
- peer
-
-
- 2.10.0
- 1.7.25
-
-
-
-
- com.jd.blockchain
- consensus-framework
- ${project.version}
-
-
- com.jd.blockchain
- ledger-rpc
- ${project.version}
-
-
- com.jd.blockchain
- consensus-mq
- ${project.version}
-
-
- com.jd.blockchain
- consensus-bftsmart
- ${project.version}
-
-
- com.jd.blockchain
- ledger-core
- ${project.version}
-
-
- com.jd.blockchain
- tools-initializer
- ${project.version}
-
-
- com.jd.blockchain
- utils-web
- ${project.version}
-
-
-
- org.springframework.boot
- spring-boot-starter-web
-
-
- org.springframework.boot
- spring-boot-starter-logging
-
-
-
-
-
- org.springframework.boot
- spring-boot-starter-log4j2
-
-
-
- org.springframework.boot
- spring-boot-starter-security
-
-
-
- org.springframework.boot
- spring-boot-configuration-processor
- true
-
-
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-deploy-plugin
- 2.8.2
-
- true
-
-
-
-
-
+
+ 4.0.0
+
+ com.jd.blockchain
+ jdchain-root
+ 1.1.2.RELEASE
+
+ peer
+
+
+ 2.10.0
+ 1.7.25
+
+
+
+
+ com.jd.blockchain
+ consensus-framework
+ ${project.version}
+
+
+ com.jd.blockchain
+ ledger-rpc
+ ${project.version}
+
+
+ com.jd.blockchain
+ consensus-mq
+ ${project.version}
+
+
+ com.jd.blockchain
+ consensus-bftsmart
+ ${project.version}
+
+
+ com.jd.blockchain
+ ledger-core
+ ${project.version}
+
+
+ com.jd.blockchain
+ tools-initializer
+ ${project.version}
+
+
+ com.jd.blockchain
+ utils-web
+ ${project.version}
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+ org.springframework.boot
+ spring-boot-starter-logging
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-log4j2
+
+
+
+ org.springframework.boot
+ spring-boot-starter-security
+
+
+
+ org.springframework.boot
+ spring-boot-configuration-processor
+ true
+
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-deploy-plugin
+ 2.8.2
+
+ true
+
+
+
+
+
\ No newline at end of file
diff --git a/source/peer/src/main/java/com/jd/blockchain/peer/PeerConfiguration.java b/source/peer/src/main/java/com/jd/blockchain/peer/PeerConfiguration.java
index 86b169a4..b7dc9f2e 100644
--- a/source/peer/src/main/java/com/jd/blockchain/peer/PeerConfiguration.java
+++ b/source/peer/src/main/java/com/jd/blockchain/peer/PeerConfiguration.java
@@ -1,15 +1,15 @@
-package com.jd.blockchain.peer;
-
-import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
-import org.springframework.boot.autoconfigure.SpringBootApplication;
-import org.springframework.boot.context.properties.EnableConfigurationProperties;
-import org.springframework.context.annotation.ComponentScan;
-
-@SpringBootApplication
-@EnableAutoConfiguration
-@EnableConfigurationProperties
-@ComponentScan
-public class PeerConfiguration {
-
-}
-
+package com.jd.blockchain.peer;
+
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.ComponentScan;
+
+@SpringBootApplication
+@EnableAutoConfiguration
+@EnableConfigurationProperties
+@ComponentScan
+public class PeerConfiguration {
+
+}
+
diff --git a/source/peer/src/main/java/com/jd/blockchain/peer/consensus/BlockchainConsensusServiceImpl.java b/source/peer/src/main/java/com/jd/blockchain/peer/consensus/BlockchainConsensusServiceImpl.java
index 5f62888f..593a90f4 100644
--- a/source/peer/src/main/java/com/jd/blockchain/peer/consensus/BlockchainConsensusServiceImpl.java
+++ b/source/peer/src/main/java/com/jd/blockchain/peer/consensus/BlockchainConsensusServiceImpl.java
@@ -1,213 +1,213 @@
-//package com.jd.blockchain.peer.consensus;
-//
-//import com.jd.blockchain.binaryproto.BinaryEncodingUtils;
-//import com.jd.blockchain.consensus.BatchConsensusListener;
-//import com.jd.blockchain.consensus.action.ActionRequest;
-//import com.jd.blockchain.consensus.action.ActionRequestData;
-//import com.jd.blockchain.consensus.bft.*;
-//import com.jd.blockchain.crypto.CryptoAlgorithm;
-//import com.jd.blockchain.crypto.CryptoUtils;
-//import com.jd.blockchain.ledger.*;
-//import com.jd.blockchain.ledger.data.TxContentBlob;
-//import com.jd.blockchain.ledger.data.TxRequestMessage;
-//import my.utils.io.BytesEncoding;
-//import my.utils.io.NumberMask;
-//import org.slf4j.Logger;
-//import org.slf4j.LoggerFactory;
-//import org.springframework.beans.factory.annotation.Autowired;
-//import org.springframework.stereotype.Service;
-//
-//import com.jd.blockchain.crypto.hash.HashDigest;
-//import com.jd.blockchain.ledger.core.TransactionBatchProcess;
-//import com.jd.blockchain.ledger.core.TransactionBatchResultHandle;
-//import com.jd.blockchain.ledger.core.TransactionEngine;
-//import com.jd.blockchain.sdk.bftsmart.ConsensusTransactionService;
-//
-//import java.io.ByteArrayOutputStream;
-//import java.util.concurrent.*;
-//import java.util.concurrent.atomic.AtomicBoolean;
-//import java.util.concurrent.atomic.AtomicLong;
-//
-///**
-// * @author huanghaiquan
-// *
-// */
-//@Service
-//public class BlockchainConsensusServiceImpl implements ConsensusTransactionService, BatchConsensusListener {
-//
-// private static final Logger LOGGER = LoggerFactory.getLogger(BlockchainConsensusServiceImpl.class);
-//
-// private final ExecutorService sendExecutorService = Executors.newFixedThreadPool(10);
-//
-// private final ScheduledExecutorService timerEexecutorService = new ScheduledThreadPoolExecutor(1);
-// //结块之前接收的消息数
-// private int receiveCounts = 0;
-// //区块提交之后,后续第一个交易到达的时间
-// private long initTimeStamp = 0;
-// //达到一定的交易数后发送结块共识消息
-// private int TransactionCount = 100;
-// //两秒内没有收到新的共识消息,发送结块共识消息,把不足TransactionCount的消息结块入帐本,单位毫秒
-// private long TimeOut = 2000;
-//
-// private final AtomicLong blockIndex = new AtomicLong();
-//
-// private long currBlockIndex = 0L;
-//
-// private final AtomicBoolean blockFlag = new AtomicBoolean(false);
-//
-//
-// @Autowired
-// private TransactionEngine txEngine;
-//
-// //0.5 version implement
-//// @Override
-//// public void beforeBatch(byte[] groupId) {
-//// // 以“账本哈希”为共识分组ID;
-//// HashDigest ledgerHash = new HashDigest(groupId);
-//// txEngine.createNextBatch(ledgerHash);
-////
-//// LOGGER.info("Create new block to process transaction batch! --[LedgerHash=" + ledgerHash.toBase58() + "]");
-//// }
-//
-// //0.6 version implement, not used
-// @Override
-// public void beforeBatch(byte[] groupId) {
-//// // 以“账本哈希”为共识分组ID;
-//// HashDigest ledgerHash = new HashDigest(groupId);
-//// txEngine.createNextBatch(ledgerHash);
-////
-//// LOGGER.info("Create new block to process transaction batch! --[LedgerHash=" + ledgerHash.toBase58() + "]");
-// }
-//
-// /**
-// * 处理收到的交易消息,并返回结果;
-// */
-// //0.5 version implement
-//// @Override
-//// public TransactionResponse process(TransactionRequest txRequest) {
-//// TransactionBatchProcess txBatchProcess = txEngine.getBatch(txRequest.getTransactionContent().getLedgerHash());
-//// return txBatchProcess.schedule(txRequest);
-//// }
-//
-// //由Leader Peer发送结块通知消息,需要PEER对此消息进行共识,达到共识结点结块的一致性
-// public void notifyCommit(final long currBlockIndex, HashDigest ledgerHash, BftsmartConsensusSetting bftsmartConsensusSetting, BftsmartTopology bftsmartTopology) {
-// //if peer is leader, send commit block consensus request
-// System.out.println(Thread.currentThread().getId() + " leader run notifyCommit = " + receiveCounts + " TransactionCount = " + TransactionCount);
-// if (receiveCounts >= TransactionCount) {
-// System.out.println(Thread.currentThread().getId() + "this.blockIndex = " + this.blockIndex.get() + ", currBlockIndex=" + currBlockIndex);
-// boolean isAdd = this.blockIndex.compareAndSet(currBlockIndex, currBlockIndex + 1);
-// System.out.println(Thread.currentThread().getId() + " leader run isadd = " + isAdd);
-// if (isAdd) {
-// sendExecutorService.execute(sendBlockMessage(ledgerHash, bftsmartConsensusSetting, bftsmartTopology));
-// }
-// }
-// }
-//
-// private Runnable sendBlockMessage(HashDigest ledgerHash, BftsmartConsensusSetting bftsmartConsensusSetting, BftsmartTopology bftsmartTopology) {
-// Runnable runnable = () -> sendCommitBlockMessage(ledgerHash, bftsmartConsensusSetting, bftsmartTopology);
-// return runnable;
-// }
-// //发送结块通知消息
-// private void sendCommitBlockMessage(HashDigest ledgerHash, BftsmartConsensusSetting bftsmartConsensusSetting, BftsmartTopology bftsmartTopology) {
-//
-//// ActionRequestData request = new ActionRequestData();
-//// request.setGroupId(ledgerHash.toBytes());
-//// request.setHandleType("com.jd.blockchain.sdk.bftsmart.ConsensusTransactionService");
-//// request.setHandleMethod("public abstract com.jd.blockchain.ledger.TransactionResponse com.jd.blockchain.sdk.bftsmart.ConsensusTransactionService.process(com.jd.blockchain.ledger.TransactionRequest)");
-//// request.setTransactionType("COMMITBLOCK");
-////
-//// BlockchainKeyPair userKeyPeer = BlockchainKeyGenerator.getInstance().generate();
-////
-//// TxContentBlob txContentBlob = new TxContentBlob(ledgerHash);
-////
-//// byte[] reqBytes = BinaryEncodingUtils.encode(txContentBlob, TransactionContent.class);
-//// HashDigest reqHash = CryptoUtils.hash(CryptoAlgorithm.SHA256).hash(reqBytes);
-//// txContentBlob.setHash(reqHash);
-////
-//// TxRequestMessage transactionRequest = new TxRequestMessage(txContentBlob);
-////
-//// byte[] encodeBytes = BinaryEncodingUtils.encode(transactionRequest, TransactionRequest.class);
-////
-//// ByteArrayOutputStream out = new ByteArrayOutputStream();
-//// BytesEncoding.write(encodeBytes, NumberMask.NORMAL, out);
-////
-//// request.setMessageBody(out.toByteArray());
-//// byte[] commandReq = BinaryEncodingUtils.encode(request, ActionRequest.class);
-////
-//// BftsmartConsensusClient bftsmartConsensusClient = new BftsmartConsensusClient(0, bftsmartConsensusSetting, bftsmartTopology);
-//// bftsmartConsensusClient.invokeOrdered(commandReq);
-////
-//// LOGGER.info(String.format("Send notify commit block msg success!"));
-// }
-//
-// //0.6 version implement
-// @Override
-// public TransactionResponse process(TransactionRequest txRequest) {
-//// System.out.println("peer process thread = " + Thread.currentThread().getId());
-//// System.out.println("peer process object = " + this);
-// HashDigest ledgerHash = txRequest.getTransactionContent().getLedgerHash();
-// TransactionBatchProcess txBatchProcess = txEngine.getBatch(ledgerHash);
-//
-// boolean isLeader = BftsmartConsensusUtils.getLeader();
-// BftsmartConsensusSetting bftsmartConsensusSetting =BftsmartConsensusUtils.getSetting();
-// BftsmartTopology bftsmartTopology = BftsmartConsensusUtils.getTopology();
-//
-// if (txBatchProcess == null) {
-// txBatchProcess = txEngine.createNextBatch(ledgerHash);
-// currBlockIndex = txBatchProcess.blockHeight();
-// this.blockIndex.set(currBlockIndex);
-// receiveCounts = 0;
-//
-// if (isLeader) {
-// long timerStart = System.currentTimeMillis();
-// System.out.println("first message time = "+timerStart);
-// timerEexecutorService.schedule(timeTask(currBlockIndex, ledgerHash, bftsmartConsensusSetting, bftsmartTopology), 500L, TimeUnit.MILLISECONDS);
-// }
-// }
-// receiveCounts++;
-// if (isLeader) {
-// notifyCommit(currBlockIndex, ledgerHash, bftsmartConsensusSetting, bftsmartTopology);
-// }
-// return txBatchProcess.schedule(txRequest);
-// }
-//
-// @Override
-// public void afterBatch(byte[] groupId, Exception error) {
-// HashDigest ledgerHash = new HashDigest(groupId);
-// TransactionBatchProcess txBatchProcess = txEngine.getBatch(ledgerHash);
-//
-// if (error != null) {
-// txBatchProcess.cancel(TransactionState.SYSTEM_ERROR);
-// LOGGER.error("Error occurred on executing batch transactions, so the new block is canceled! --" + error.getMessage(), error);
-// return;
-// }
-//
-// //生成区块;
-// TransactionBatchResultHandle batchResultHandle = txBatchProcess.prepare();
-//
-// LedgerBlock newBlock = batchResultHandle.getBlock();
-// // TODO: 对新区块进行最后的共识;
-// HashDigest blockHash = newBlock.getHash();
-//
-// LOGGER.info(String.format(
-// "Create new block success! --[LedgerHash=%s][BlockHash=%s][BlockHeigth=%s]",
-// ledgerHash.toBase58(), blockHash.toBase58(), newBlock.getHeight()));
-//
-// // 提交新区块;
-// batchResultHandle.commit();
-//
-// }
-//
-// private Runnable timeTask(final long currBlockIndex, HashDigest ledgerHash, BftsmartConsensusSetting bftsmartConsensusSetting, BftsmartTopology bftsmartTopology) {
-// Runnable task = () -> {
-// // todo
-// boolean isAdd = this.blockIndex.compareAndSet(currBlockIndex, currBlockIndex + 1);
-// if (isAdd) {
-// System.out.println(Thread.currentThread().getId() + " leader run isadd = " + isAdd + " timer send commitblock message ! curren time = " + System.currentTimeMillis());
-// sendCommitBlockMessage(ledgerHash, bftsmartConsensusSetting, bftsmartTopology);
-// }
-// };
-// return task;
-// }
-//
-// }
+//package com.jd.blockchain.peer.consensus;
+//
+//import com.jd.blockchain.binaryproto.BinaryEncodingUtils;
+//import com.jd.blockchain.consensus.BatchConsensusListener;
+//import com.jd.blockchain.consensus.action.ActionRequest;
+//import com.jd.blockchain.consensus.action.ActionRequestData;
+//import com.jd.blockchain.consensus.bft.*;
+//import com.jd.blockchain.crypto.CryptoAlgorithm;
+//import com.jd.blockchain.crypto.CryptoUtils;
+//import com.jd.blockchain.ledger.*;
+//import com.jd.blockchain.ledger.data.TxContentBlob;
+//import com.jd.blockchain.ledger.data.TxRequestMessage;
+//import my.utils.io.BytesEncoding;
+//import my.utils.io.NumberMask;
+//import org.slf4j.Logger;
+//import org.slf4j.LoggerFactory;
+//import org.springframework.beans.factory.annotation.Autowired;
+//import org.springframework.stereotype.Service;
+//
+//import com.jd.blockchain.crypto.hash.HashDigest;
+//import com.jd.blockchain.ledger.core.TransactionBatchProcess;
+//import com.jd.blockchain.ledger.core.TransactionBatchResultHandle;
+//import com.jd.blockchain.ledger.core.TransactionEngine;
+//import com.jd.blockchain.sdk.bftsmart.ConsensusTransactionService;
+//
+//import java.io.ByteArrayOutputStream;
+//import java.util.concurrent.*;
+//import java.util.concurrent.atomic.AtomicBoolean;
+//import java.util.concurrent.atomic.AtomicLong;
+//
+///**
+// * @author huanghaiquan
+// *
+// */
+//@Service
+//public class BlockchainConsensusServiceImpl implements ConsensusTransactionService, BatchConsensusListener {
+//
+// private static final Logger LOGGER = LoggerFactory.getLogger(BlockchainConsensusServiceImpl.class);
+//
+// private final ExecutorService sendExecutorService = Executors.newFixedThreadPool(10);
+//
+// private final ScheduledExecutorService timerEexecutorService = new ScheduledThreadPoolExecutor(1);
+// //结块之前接收的消息数
+// private int receiveCounts = 0;
+// //区块提交之后,后续第一个交易到达的时间
+// private long initTimeStamp = 0;
+// //达到一定的交易数后发送结块共识消息
+// private int TransactionCount = 100;
+// //两秒内没有收到新的共识消息,发送结块共识消息,把不足TransactionCount的消息结块入帐本,单位毫秒
+// private long TimeOut = 2000;
+//
+// private final AtomicLong blockIndex = new AtomicLong();
+//
+// private long currBlockIndex = 0L;
+//
+// private final AtomicBoolean blockFlag = new AtomicBoolean(false);
+//
+//
+// @Autowired
+// private TransactionEngine txEngine;
+//
+// //0.5 version implement
+//// @Override
+//// public void beforeBatch(byte[] groupId) {
+//// // 以“账本哈希”为共识分组ID;
+//// HashDigest ledgerHash = new HashDigest(groupId);
+//// txEngine.createNextBatch(ledgerHash);
+////
+//// LOGGER.info("Create new block to process transaction batch! --[LedgerHash=" + ledgerHash.toBase58() + "]");
+//// }
+//
+// //0.6 version implement, not used
+// @Override
+// public void beforeBatch(byte[] groupId) {
+//// // 以“账本哈希”为共识分组ID;
+//// HashDigest ledgerHash = new HashDigest(groupId);
+//// txEngine.createNextBatch(ledgerHash);
+////
+//// LOGGER.info("Create new block to process transaction batch! --[LedgerHash=" + ledgerHash.toBase58() + "]");
+// }
+//
+// /**
+// * 处理收到的交易消息,并返回结果;
+// */
+// //0.5 version implement
+//// @Override
+//// public TransactionResponse process(TransactionRequest txRequest) {
+//// TransactionBatchProcess txBatchProcess = txEngine.getBatch(txRequest.getTransactionContent().getLedgerHash());
+//// return txBatchProcess.schedule(txRequest);
+//// }
+//
+// //由Leader Peer发送结块通知消息,需要PEER对此消息进行共识,达到共识结点结块的一致性
+// public void notifyCommit(final long currBlockIndex, HashDigest ledgerHash, BftsmartConsensusSetting bftsmartConsensusSetting, BftsmartTopology bftsmartTopology) {
+// //if peer is leader, send commit block consensus request
+// System.out.println(Thread.currentThread().getId() + " leader run notifyCommit = " + receiveCounts + " TransactionCount = " + TransactionCount);
+// if (receiveCounts >= TransactionCount) {
+// System.out.println(Thread.currentThread().getId() + "this.blockIndex = " + this.blockIndex.get() + ", currBlockIndex=" + currBlockIndex);
+// boolean isAdd = this.blockIndex.compareAndSet(currBlockIndex, currBlockIndex + 1);
+// System.out.println(Thread.currentThread().getId() + " leader run isadd = " + isAdd);
+// if (isAdd) {
+// sendExecutorService.execute(sendBlockMessage(ledgerHash, bftsmartConsensusSetting, bftsmartTopology));
+// }
+// }
+// }
+//
+// private Runnable sendBlockMessage(HashDigest ledgerHash, BftsmartConsensusSetting bftsmartConsensusSetting, BftsmartTopology bftsmartTopology) {
+// Runnable runnable = () -> sendCommitBlockMessage(ledgerHash, bftsmartConsensusSetting, bftsmartTopology);
+// return runnable;
+// }
+// //发送结块通知消息
+// private void sendCommitBlockMessage(HashDigest ledgerHash, BftsmartConsensusSetting bftsmartConsensusSetting, BftsmartTopology bftsmartTopology) {
+//
+//// ActionRequestData request = new ActionRequestData();
+//// request.setGroupId(ledgerHash.toBytes());
+//// request.setHandleType("com.jd.blockchain.sdk.bftsmart.ConsensusTransactionService");
+//// request.setHandleMethod("public abstract com.jd.blockchain.ledger.TransactionResponse com.jd.blockchain.sdk.bftsmart.ConsensusTransactionService.process(com.jd.blockchain.ledger.TransactionRequest)");
+//// request.setTransactionType("COMMITBLOCK");
+////
+//// BlockchainKeyPair userKeyPeer = BlockchainKeyGenerator.getInstance().generate();
+////
+//// TxContentBlob txContentBlob = new TxContentBlob(ledgerHash);
+////
+//// byte[] reqBytes = BinaryEncodingUtils.encode(txContentBlob, TransactionContent.class);
+//// HashDigest reqHash = CryptoUtils.hash(CryptoAlgorithm.SHA256).hash(reqBytes);
+//// txContentBlob.setHash(reqHash);
+////
+//// TxRequestMessage transactionRequest = new TxRequestMessage(txContentBlob);
+////
+//// byte[] encodeBytes = BinaryEncodingUtils.encode(transactionRequest, TransactionRequest.class);
+////
+//// ByteArrayOutputStream out = new ByteArrayOutputStream();
+//// BytesEncoding.write(encodeBytes, NumberMask.NORMAL, out);
+////
+//// request.setMessageBody(out.toByteArray());
+//// byte[] commandReq = BinaryEncodingUtils.encode(request, ActionRequest.class);
+////
+//// BftsmartConsensusClient bftsmartConsensusClient = new BftsmartConsensusClient(0, bftsmartConsensusSetting, bftsmartTopology);
+//// bftsmartConsensusClient.invokeOrdered(commandReq);
+////
+//// LOGGER.info(String.format("Send notify commit block msg success!"));
+// }
+//
+// //0.6 version implement
+// @Override
+// public TransactionResponse process(TransactionRequest txRequest) {
+//// System.out.println("peer process thread = " + Thread.currentThread().getId());
+//// System.out.println("peer process object = " + this);
+// HashDigest ledgerHash = txRequest.getTransactionContent().getLedgerHash();
+// TransactionBatchProcess txBatchProcess = txEngine.getBatch(ledgerHash);
+//
+// boolean isLeader = BftsmartConsensusUtils.getLeader();
+// BftsmartConsensusSetting bftsmartConsensusSetting =BftsmartConsensusUtils.getSetting();
+// BftsmartTopology bftsmartTopology = BftsmartConsensusUtils.getTopology();
+//
+// if (txBatchProcess == null) {
+// txBatchProcess = txEngine.createNextBatch(ledgerHash);
+// currBlockIndex = txBatchProcess.blockHeight();
+// this.blockIndex.set(currBlockIndex);
+// receiveCounts = 0;
+//
+// if (isLeader) {
+// long timerStart = System.currentTimeMillis();
+// System.out.println("first message time = "+timerStart);
+// timerEexecutorService.schedule(timeTask(currBlockIndex, ledgerHash, bftsmartConsensusSetting, bftsmartTopology), 500L, TimeUnit.MILLISECONDS);
+// }
+// }
+// receiveCounts++;
+// if (isLeader) {
+// notifyCommit(currBlockIndex, ledgerHash, bftsmartConsensusSetting, bftsmartTopology);
+// }
+// return txBatchProcess.schedule(txRequest);
+// }
+//
+// @Override
+// public void afterBatch(byte[] groupId, Exception error) {
+// HashDigest ledgerHash = new HashDigest(groupId);
+// TransactionBatchProcess txBatchProcess = txEngine.getBatch(ledgerHash);
+//
+// if (error != null) {
+// txBatchProcess.cancel(TransactionState.SYSTEM_ERROR);
+// LOGGER.error("Error occurred on executing batch transactions, so the new block is canceled! --" + error.getMessage(), error);
+// return;
+// }
+//
+// //生成区块;
+// TransactionBatchResultHandle batchResultHandle = txBatchProcess.prepare();
+//
+// LedgerBlock newBlock = batchResultHandle.getBlock();
+// // TODO: 对新区块进行最后的共识;
+// HashDigest blockHash = newBlock.getHash();
+//
+// LOGGER.info(String.format(
+// "Create new block success! --[LedgerHash=%s][BlockHash=%s][BlockHeigth=%s]",
+// ledgerHash.toBase58(), blockHash.toBase58(), newBlock.getHeight()));
+//
+// // 提交新区块;
+// batchResultHandle.commit();
+//
+// }
+//
+// private Runnable timeTask(final long currBlockIndex, HashDigest ledgerHash, BftsmartConsensusSetting bftsmartConsensusSetting, BftsmartTopology bftsmartTopology) {
+// Runnable task = () -> {
+// // todo
+// boolean isAdd = this.blockIndex.compareAndSet(currBlockIndex, currBlockIndex + 1);
+// if (isAdd) {
+// System.out.println(Thread.currentThread().getId() + " leader run isadd = " + isAdd + " timer send commitblock message ! curren time = " + System.currentTimeMillis());
+// sendCommitBlockMessage(ledgerHash, bftsmartConsensusSetting, bftsmartTopology);
+// }
+// };
+// return task;
+// }
+//
+// }
diff --git a/source/peer/src/main/java/com/jd/blockchain/peer/consensus/ConsensusViewDefinition.java b/source/peer/src/main/java/com/jd/blockchain/peer/consensus/ConsensusViewDefinition.java
index a56e5ed4..d19a93af 100644
--- a/source/peer/src/main/java/com/jd/blockchain/peer/consensus/ConsensusViewDefinition.java
+++ b/source/peer/src/main/java/com/jd/blockchain/peer/consensus/ConsensusViewDefinition.java
@@ -1,93 +1,93 @@
-package com.jd.blockchain.peer.consensus;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-
-import com.jd.blockchain.utils.net.NetworkAddress;
-
-public class ConsensusViewDefinition implements Serializable {
-
- private static final long serialVersionUID = -201642288565436003L;
-
- private static int[] EMPTY_IDS = {};
-
- private ArrayList nodes = new ArrayList<>();
-
- public int getF() {
- return (int) ((getNodeCount() - 1) / 3);
- }
-
- /**
- * 法定的数量;
- *
- * @return
- */
- public int getN() {
- return 3 * getF() + 1;
- }
-
- /**
- * 实际的节点数量;
- *
- * @return
- */
- public int getNodeCount() {
- return nodes.size();
- }
-
- /**
- * 返回法定数量的初始节点的 ID 列表;
- *
- * @return
- */
- public int[] getQuorumIDs() {
- if (getNodeCount() == 0) {
- return EMPTY_IDS;
- }
- int[] ids = new int[getN()];
- for (int i = 0; i < ids.length; i++) {
- ids[i] = nodes.get(i).getId();
- }
- return ids;
- }
-
- /**
- * 加入节点信息;
- *
- * @param networkAddress
- * @return 返回分配给新节点的 ID (ID >= 0);如果节点数量以达到 (3f+1) 的数量;
- */
- public synchronized int addNode(NetworkAddress networkAddress) {
- for (NodeInfo ninf : nodes) {
- if (ninf.getNetworkAddress().equals(networkAddress)) {
- throw new IllegalArgumentException("Add node[" + networkAddress.toString() + "] reaptly!");
- }
- }
- NodeInfo nodeInfo = new NodeInfo(nodes.size(), networkAddress);
- nodes.add(nodeInfo);
- return nodeInfo.getId();
- }
-
- public static class NodeInfo implements Serializable {
-
- private static final long serialVersionUID = -9178639061945239622L;
-
- private int id;
-
- private NetworkAddress networkAddress;
-
- public NodeInfo(int id, NetworkAddress networkAddress) {
- this.id = id;
- this.networkAddress = networkAddress;
- }
-
- public int getId() {
- return id;
- }
-
- public NetworkAddress getNetworkAddress() {
- return networkAddress;
- }
- }
-
-}
+package com.jd.blockchain.peer.consensus;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+
+import com.jd.blockchain.utils.net.NetworkAddress;
+
+public class ConsensusViewDefinition implements Serializable {
+
+ private static final long serialVersionUID = -201642288565436003L;
+
+ private static int[] EMPTY_IDS = {};
+
+ private ArrayList nodes = new ArrayList<>();
+
+ public int getF() {
+ return (int) ((getNodeCount() - 1) / 3);
+ }
+
+ /**
+ * 法定的数量;
+ *
+ * @return
+ */
+ public int getN() {
+ return 3 * getF() + 1;
+ }
+
+ /**
+ * 实际的节点数量;
+ *
+ * @return
+ */
+ public int getNodeCount() {
+ return nodes.size();
+ }
+
+ /**
+ * 返回法定数量的初始节点的 ID 列表;
+ *
+ * @return
+ */
+ public int[] getQuorumIDs() {
+ if (getNodeCount() == 0) {
+ return EMPTY_IDS;
+ }
+ int[] ids = new int[getN()];
+ for (int i = 0; i < ids.length; i++) {
+ ids[i] = nodes.get(i).getId();
+ }
+ return ids;
+ }
+
+ /**
+ * 加入节点信息;
+ *
+ * @param networkAddress
+ * @return 返回分配给新节点的 ID (ID >= 0);如果节点数量以达到 (3f+1) 的数量;
+ */
+ public synchronized int addNode(NetworkAddress networkAddress) {
+ for (NodeInfo ninf : nodes) {
+ if (ninf.getNetworkAddress().equals(networkAddress)) {
+ throw new IllegalArgumentException("Add node[" + networkAddress.toString() + "] reaptly!");
+ }
+ }
+ NodeInfo nodeInfo = new NodeInfo(nodes.size(), networkAddress);
+ nodes.add(nodeInfo);
+ return nodeInfo.getId();
+ }
+
+ public static class NodeInfo implements Serializable {
+
+ private static final long serialVersionUID = -9178639061945239622L;
+
+ private int id;
+
+ private NetworkAddress networkAddress;
+
+ public NodeInfo(int id, NetworkAddress networkAddress) {
+ this.id = id;
+ this.networkAddress = networkAddress;
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ public NetworkAddress getNetworkAddress() {
+ return networkAddress;
+ }
+ }
+
+}
diff --git a/source/peer/src/main/java/com/jd/blockchain/peer/web/PeerWebSecurityConfiguration.java b/source/peer/src/main/java/com/jd/blockchain/peer/web/PeerWebSecurityConfiguration.java
index 1b285b0a..3cccf09f 100644
--- a/source/peer/src/main/java/com/jd/blockchain/peer/web/PeerWebSecurityConfiguration.java
+++ b/source/peer/src/main/java/com/jd/blockchain/peer/web/PeerWebSecurityConfiguration.java
@@ -1,20 +1,20 @@
-package com.jd.blockchain.peer.web;
-
-import org.springframework.context.annotation.Configuration;
-import org.springframework.core.annotation.Order;
-import org.springframework.security.config.annotation.web.builders.HttpSecurity;
-import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
-import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
-
-@Configuration
-@EnableWebSecurity
-public class PeerWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
-
-
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.authorizeRequests().anyRequest().permitAll();
- http.csrf().disable();
- }
-
-}
+package com.jd.blockchain.peer.web;
+
+import org.springframework.context.annotation.Configuration;
+import org.springframework.core.annotation.Order;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+
+@Configuration
+@EnableWebSecurity
+public class PeerWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
+
+
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http.authorizeRequests().anyRequest().permitAll();
+ http.csrf().disable();
+ }
+
+}
diff --git a/source/peer/src/main/java/com/jd/blockchain/peer/web/PeerWebServerConfigurer.java b/source/peer/src/main/java/com/jd/blockchain/peer/web/PeerWebServerConfigurer.java
index f0d52ac5..71f0ac83 100644
--- a/source/peer/src/main/java/com/jd/blockchain/peer/web/PeerWebServerConfigurer.java
+++ b/source/peer/src/main/java/com/jd/blockchain/peer/web/PeerWebServerConfigurer.java
@@ -1,51 +1,51 @@
-package com.jd.blockchain.peer.web;
-
-import java.util.List;
-
-import com.jd.blockchain.web.converters.BinaryMessageConverter;
-import com.jd.blockchain.web.converters.HashDigestInputConverter;
-
-import com.jd.blockchain.web.serializes.ByteArrayObjectUtil;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.format.FormatterRegistry;
-import org.springframework.http.converter.HttpMessageConverter;
-import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
-import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
-
-import com.jd.blockchain.utils.io.ByteArray;
-import com.jd.blockchain.utils.serialize.json.JSONSerializeUtils;
-import com.jd.blockchain.utils.web.model.JsonWebResponseMessageConverter;
-
-@Configuration
-public class PeerWebServerConfigurer implements WebMvcConfigurer {
-
- static {
- JSONSerializeUtils.disableCircularReferenceDetect();
- JSONSerializeUtils.configStringSerializer(ByteArray.class);
- }
-
- @Override
- public void extendMessageConverters(List> converters) {
- int index = converters.size();
- for (int i = 0; i < converters.size(); i++) {
- if (converters.get(i) instanceof MappingJackson2HttpMessageConverter) {
- index = i;
- break;
- }
- }
- converters.add(index, new JsonWebResponseMessageConverter());
-
- converters.add(0, new BinaryMessageConverter());
-
- initByteArrayJsonSerialize();
- }
-
- @Override
- public void addFormatters(FormatterRegistry registry) {
- registry.addConverter(new HashDigestInputConverter());
- }
-
- private void initByteArrayJsonSerialize() {
- ByteArrayObjectUtil.init();
- }
-}
+package com.jd.blockchain.peer.web;
+
+import java.util.List;
+
+import com.jd.blockchain.web.converters.BinaryMessageConverter;
+import com.jd.blockchain.web.converters.HashDigestInputConverter;
+
+import com.jd.blockchain.web.serializes.ByteArrayObjectUtil;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.format.FormatterRegistry;
+import org.springframework.http.converter.HttpMessageConverter;
+import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
+
+import com.jd.blockchain.utils.io.ByteArray;
+import com.jd.blockchain.utils.serialize.json.JSONSerializeUtils;
+import com.jd.blockchain.utils.web.model.JsonWebResponseMessageConverter;
+
+@Configuration
+public class PeerWebServerConfigurer implements WebMvcConfigurer {
+
+ static {
+ JSONSerializeUtils.disableCircularReferenceDetect();
+ JSONSerializeUtils.configStringSerializer(ByteArray.class);
+ }
+
+ @Override
+ public void extendMessageConverters(List> converters) {
+ int index = converters.size();
+ for (int i = 0; i < converters.size(); i++) {
+ if (converters.get(i) instanceof MappingJackson2HttpMessageConverter) {
+ index = i;
+ break;
+ }
+ }
+ converters.add(index, new JsonWebResponseMessageConverter());
+
+ converters.add(0, new BinaryMessageConverter());
+
+ initByteArrayJsonSerialize();
+ }
+
+ @Override
+ public void addFormatters(FormatterRegistry registry) {
+ registry.addConverter(new HashDigestInputConverter());
+ }
+
+ private void initByteArrayJsonSerialize() {
+ ByteArrayObjectUtil.init();
+ }
+}
diff --git a/source/peer/src/test/java/test/com/jd/blockchain/peer/service/ConsensusViewDefinitionTest.java b/source/peer/src/test/java/test/com/jd/blockchain/peer/service/ConsensusViewDefinitionTest.java
index 545a0223..451a6f32 100644
--- a/source/peer/src/test/java/test/com/jd/blockchain/peer/service/ConsensusViewDefinitionTest.java
+++ b/source/peer/src/test/java/test/com/jd/blockchain/peer/service/ConsensusViewDefinitionTest.java
@@ -1,47 +1,47 @@
-package test.com.jd.blockchain.peer.service;
-
-import static org.junit.Assert.assertEquals;
-
-import org.junit.Test;
-
-import com.jd.blockchain.peer.consensus.ConsensusViewDefinition;
-import com.jd.blockchain.utils.net.NetworkAddress;
-
-public class ConsensusViewDefinitionTest {
-
- @Test
- public void test() {
- ConsensusViewDefinition viewDef = new ConsensusViewDefinition();
-
- assertEquals(0, viewDef.getNodeCount());
- assertEquals(1, viewDef.getN());
- assertEquals(0, viewDef.getF());
-
- viewDef.addNode(new NetworkAddress("localhost", 10001));
- assertEquals(1, viewDef.getNodeCount());
- assertEquals(1, viewDef.getN());
- assertEquals(0, viewDef.getF());
-
- viewDef.addNode(new NetworkAddress("localhost", 10002));
- assertEquals(2, viewDef.getNodeCount());
- assertEquals(1, viewDef.getN());
- assertEquals(0, viewDef.getF());
-
- viewDef.addNode(new NetworkAddress("localhost", 10003));
- assertEquals(3, viewDef.getNodeCount());
- assertEquals(1, viewDef.getN());
- assertEquals(0, viewDef.getF());
-
- viewDef.addNode(new NetworkAddress("localhost", 10004));
- assertEquals(4, viewDef.getNodeCount());
- assertEquals(4, viewDef.getN());
- assertEquals(1, viewDef.getF());
-
- viewDef.addNode(new NetworkAddress("localhost", 10005));
- assertEquals(5, viewDef.getNodeCount());
- assertEquals(4, viewDef.getN());
- assertEquals(1, viewDef.getF());
-
- }
-
-}
+package test.com.jd.blockchain.peer.service;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+import com.jd.blockchain.peer.consensus.ConsensusViewDefinition;
+import com.jd.blockchain.utils.net.NetworkAddress;
+
+public class ConsensusViewDefinitionTest {
+
+ @Test
+ public void test() {
+ ConsensusViewDefinition viewDef = new ConsensusViewDefinition();
+
+ assertEquals(0, viewDef.getNodeCount());
+ assertEquals(1, viewDef.getN());
+ assertEquals(0, viewDef.getF());
+
+ viewDef.addNode(new NetworkAddress("localhost", 10001));
+ assertEquals(1, viewDef.getNodeCount());
+ assertEquals(1, viewDef.getN());
+ assertEquals(0, viewDef.getF());
+
+ viewDef.addNode(new NetworkAddress("localhost", 10002));
+ assertEquals(2, viewDef.getNodeCount());
+ assertEquals(1, viewDef.getN());
+ assertEquals(0, viewDef.getF());
+
+ viewDef.addNode(new NetworkAddress("localhost", 10003));
+ assertEquals(3, viewDef.getNodeCount());
+ assertEquals(1, viewDef.getN());
+ assertEquals(0, viewDef.getF());
+
+ viewDef.addNode(new NetworkAddress("localhost", 10004));
+ assertEquals(4, viewDef.getNodeCount());
+ assertEquals(4, viewDef.getN());
+ assertEquals(1, viewDef.getF());
+
+ viewDef.addNode(new NetworkAddress("localhost", 10005));
+ assertEquals(5, viewDef.getNodeCount());
+ assertEquals(4, viewDef.getN());
+ assertEquals(1, viewDef.getF());
+
+ }
+
+}
diff --git a/source/peer/src/test/java/test/com/jd/blockchain/peer/service/LedgerInitCordinatorTest.java b/source/peer/src/test/java/test/com/jd/blockchain/peer/service/LedgerInitCordinatorTest.java
index e45b661b..30534b52 100644
--- a/source/peer/src/test/java/test/com/jd/blockchain/peer/service/LedgerInitCordinatorTest.java
+++ b/source/peer/src/test/java/test/com/jd/blockchain/peer/service/LedgerInitCordinatorTest.java
@@ -1,151 +1,151 @@
-//package test.com.jd.blockchain.peer.service;
-//
-//import com.jd.blockchain.ledger.*;
-//import com.jd.blockchain.ledger.service.LedgerService;
-//import com.jd.blockchain.ledger.service.impl.LedgerServiceImpl;
-//import com.jd.blockchain.peer.service.LedgerInitCordinator;
-//import com.jd.blockchain.storage.service.KeyValueStorageService;
-//import com.jd.blockchain.storage.service.impl.hashmap.HashMapStorageService;
-//import my.utils.net.NetworkAddress;
-//import org.junit.After;
-//import org.junit.Before;
-//import org.junit.Test;
-//
-//import java.util.ArrayList;
-//import java.util.Arrays;
-//import java.util.Collections;
-//import java.util.List;
-//
-//import static org.junit.Assert.*;
-//
-//public class LedgerInitCordinatorTest {
-//
-// private LedgerService ledgerService;
-// private NetworkAddress localpeer = new NetworkAddress("127.0.0.1", 9000);
-//
-// @Before
-// public void setup() {
-// KeyValueStorageService storageService = new HashMapStorageService();
-// ledgerService = new LedgerServiceImpl(storageService);
-// }
-//
-// @After
-// public void teardown() {
-// ledgerService = null;
-// }
-//
-// @Test
-// public void testStart() {
-// BlockchainKeyPair genesisAccount = BlockchainKeyGenerator.getInstance().generate();
-// LedgerInitCordinator cordinator = new LedgerInitCordinator(ledgerService, localpeer, genesisAccount.getIdentity());
-// cordinator.start();
-//
-// assertEquals(cordinator.getLedgerBuilder().getGenesisSeed(), cordinator.getLedgerDefinition().getGenesisKey());
-// assertEquals(cordinator.getLedgerDefinition().isConfigReady(), false);
-// assertEquals(cordinator.getLedgerDefinition().genesisAccountNum(), 1);
-// assertEquals(cordinator.getLedgerDefinition().getInitializingOperations().length, 0);
-// }
-//
-// @Test
-// public void testJoinLedger() {
-// BlockchainKeyPair genesisAccount = BlockchainKeyGenerator.getInstance().generate();
-// LedgerInitCordinator cordinator = new LedgerInitCordinator(ledgerService, localpeer, genesisAccount.getIdentity());
-// cordinator.start();
-//
-// NetworkAddress remotepeer1 = new NetworkAddress("127.0.0.1", 9001);
-// BlockchainKeyPair remoteAccount1 = BlockchainKeyGenerator.getInstance().generate();
-// BlockchainIdentity[] remoteIdentities1 = new BlockchainIdentity[1];
-// remoteIdentities1[0] = remoteAccount1.getIdentity();
-//
-// NetworkAddress remotepeer2 = new NetworkAddress("127.0.0.1", 9002);
-// BlockchainKeyPair remoteAccount2 = BlockchainKeyGenerator.getInstance().generate();
-// BlockchainIdentity[] remoteIdentities2 = new BlockchainIdentity[1];
-// remoteIdentities2[0] = remoteAccount2.getIdentity();
-//
-// cordinator.joinLedger(cordinator.getLedgerDefinition().getDefinitionId(), remotepeer1, remoteIdentities1, new BlockchainOperation[0]);
-// cordinator.joinLedger(cordinator.getLedgerDefinition().getDefinitionId(), remotepeer2, remoteIdentities2, new BlockchainOperation[0]);
-//
-// assertEquals(cordinator.getLedgerDefinition().genesisAccountNum(), 3);
-// assertEquals(cordinator.getLedgerDefinition().getInitializingOperations().length, 0);
-// }
-//
-// @Test
-// public void testPrepare() {
-// BlockchainKeyPair genesisAccount = BlockchainKeyGenerator.getInstance().generate();
-// LedgerInitCordinator cordinator = new LedgerInitCordinator(ledgerService, localpeer, genesisAccount.getIdentity());
-// cordinator.start();
-// TransactionContent content = cordinator.prepare(cordinator.getLedgerDefinition().getDefinitionId());
-//
-// assertEquals(cordinator.getLedgerDefinition().isConfigReady(), true);
-// assertEquals(content.getOperations().length, 1);
-// }
-//
-// @Test
-// public void testSign() {
-// BlockchainKeyPair genesisAccount = BlockchainKeyGenerator.getInstance().generate();
-// LedgerInitCordinator cordinator = new LedgerInitCordinator(ledgerService, localpeer, genesisAccount.getIdentity());
-// cordinator.start();
-//
-// NetworkAddress remotepeer1 = new NetworkAddress("127.0.0.1", 9001);
-// BlockchainKeyPair remoteAccount1 = BlockchainKeyGenerator.getInstance().generate();
-// BlockchainIdentity[] remoteIdentities1 = new BlockchainIdentity[1];
-// remoteIdentities1[0] = remoteAccount1.getIdentity();
-//
-// NetworkAddress remotepeer2 = new NetworkAddress("127.0.0.1", 9002);
-// BlockchainKeyPair remoteAccount2 = BlockchainKeyGenerator.getInstance().generate();
-// BlockchainIdentity[] remoteIdentities2 = new BlockchainIdentity[1];
-// remoteIdentities2[0] = remoteAccount2.getIdentity();
-//
-// cordinator.joinLedger(cordinator.getLedgerDefinition().getDefinitionId(), remotepeer1, remoteIdentities1, new BlockchainOperation[0]);
-// cordinator.joinLedger(cordinator.getLedgerDefinition().getDefinitionId(), remotepeer2, remoteIdentities2, new BlockchainOperation[0]);
-//
-// TransactionContent content = cordinator.prepare(cordinator.getLedgerDefinition().getDefinitionId());
-//
-// DigitalSignature genesisSign = cordinator.sign(genesisAccount);
-// DigitalSignature remoteSign1 = cordinator.sign(remoteAccount1);
-// DigitalSignature remoteSign2 = cordinator.sign(remoteAccount2);
-//
-// List signatures = Arrays.asList(cordinator.getLedgerDefinition().genesisSignatures());
-//
-// assertEquals(cordinator.getLedgerDefinition().genesisSignatures().length, 3);
-// assertEquals(signatures.contains(genesisSign), true);
-// assertEquals(signatures.contains(remoteSign1), true);
-// assertEquals(signatures.contains(remoteSign2), true);
-// assertEquals(cordinator.getLedgerDefinition().isSignatureReady(), true);
-// }
-//
-// @Test
-// public void testConsistent() {
-// BlockchainKeyPair genesisAccount = BlockchainKeyGenerator.getInstance().generate();
-// LedgerInitCordinator cordinator = new LedgerInitCordinator(ledgerService, localpeer, genesisAccount.getIdentity());
-// cordinator.start();
-//
-// NetworkAddress remotepeer1 = new NetworkAddress("127.0.0.1", 9001);
-// BlockchainKeyPair remoteAccount1 = BlockchainKeyGenerator.getInstance().generate();
-// BlockchainIdentity[] remoteIdentities1 = new BlockchainIdentity[1];
-// remoteIdentities1[0] = remoteAccount1.getIdentity();
-//
-// NetworkAddress remotepeer2 = new NetworkAddress("127.0.0.1", 9002);
-// BlockchainKeyPair remoteAccount2 = BlockchainKeyGenerator.getInstance().generate();
-// BlockchainIdentity[] remoteIdentities2 = new BlockchainIdentity[1];
-// remoteIdentities2[0] = remoteAccount2.getIdentity();
-//
-// cordinator.joinLedger(cordinator.getLedgerDefinition().getDefinitionId(), remotepeer1, remoteIdentities1, new BlockchainOperation[0]);
-// cordinator.joinLedger(cordinator.getLedgerDefinition().getDefinitionId(), remotepeer2, remoteIdentities2, new BlockchainOperation[0]);
-//
-// TransactionContent content = cordinator.prepare(cordinator.getLedgerDefinition().getDefinitionId());
-//
-// cordinator.sign(genesisAccount);
-// cordinator.sign(remoteAccount1);
-// cordinator.sign(remoteAccount2);
-// cordinator.preGenerateLedger();
-//
-// cordinator.addConsensusLedgerHash(cordinator.getLedgerDefinition().getDefinitionId(), genesisAccount.getAddress(), cordinator.getLedgerBuilder().getLedger().getBlockHash());
-//
-// cordinator.addConsensusLedgerHash(cordinator.getLedgerDefinition().getDefinitionId(), remoteAccount1.getAddress(), cordinator.getLedgerBuilder().getLedger().getBlockHash());
-//
-// cordinator.addConsensusLedgerHash(cordinator.getLedgerDefinition().getDefinitionId(), remoteAccount2.getAddress(), cordinator.getLedgerBuilder().getLedger().getBlockHash());
-//
-// assertEquals(cordinator.isLedgerConsistent(), true);
-// }
+//package test.com.jd.blockchain.peer.service;
+//
+//import com.jd.blockchain.ledger.*;
+//import com.jd.blockchain.ledger.service.LedgerService;
+//import com.jd.blockchain.ledger.service.impl.LedgerServiceImpl;
+//import com.jd.blockchain.peer.service.LedgerInitCordinator;
+//import com.jd.blockchain.storage.service.KeyValueStorageService;
+//import com.jd.blockchain.storage.service.impl.hashmap.HashMapStorageService;
+//import my.utils.net.NetworkAddress;
+//import org.junit.After;
+//import org.junit.Before;
+//import org.junit.Test;
+//
+//import java.util.ArrayList;
+//import java.util.Arrays;
+//import java.util.Collections;
+//import java.util.List;
+//
+//import static org.junit.Assert.*;
+//
+//public class LedgerInitCordinatorTest {
+//
+// private LedgerService ledgerService;
+// private NetworkAddress localpeer = new NetworkAddress("127.0.0.1", 9000);
+//
+// @Before
+// public void setup() {
+// KeyValueStorageService storageService = new HashMapStorageService();
+// ledgerService = new LedgerServiceImpl(storageService);
+// }
+//
+// @After
+// public void teardown() {
+// ledgerService = null;
+// }
+//
+// @Test
+// public void testStart() {
+// BlockchainKeyPair genesisAccount = BlockchainKeyGenerator.getInstance().generate();
+// LedgerInitCordinator cordinator = new LedgerInitCordinator(ledgerService, localpeer, genesisAccount.getIdentity());
+// cordinator.start();
+//
+// assertEquals(cordinator.getLedgerBuilder().getGenesisSeed(), cordinator.getLedgerDefinition().getGenesisKey());
+// assertEquals(cordinator.getLedgerDefinition().isConfigReady(), false);
+// assertEquals(cordinator.getLedgerDefinition().genesisAccountNum(), 1);
+// assertEquals(cordinator.getLedgerDefinition().getInitializingOperations().length, 0);
+// }
+//
+// @Test
+// public void testJoinLedger() {
+// BlockchainKeyPair genesisAccount = BlockchainKeyGenerator.getInstance().generate();
+// LedgerInitCordinator cordinator = new LedgerInitCordinator(ledgerService, localpeer, genesisAccount.getIdentity());
+// cordinator.start();
+//
+// NetworkAddress remotepeer1 = new NetworkAddress("127.0.0.1", 9001);
+// BlockchainKeyPair remoteAccount1 = BlockchainKeyGenerator.getInstance().generate();
+// BlockchainIdentity[] remoteIdentities1 = new BlockchainIdentity[1];
+// remoteIdentities1[0] = remoteAccount1.getIdentity();
+//
+// NetworkAddress remotepeer2 = new NetworkAddress("127.0.0.1", 9002);
+// BlockchainKeyPair remoteAccount2 = BlockchainKeyGenerator.getInstance().generate();
+// BlockchainIdentity[] remoteIdentities2 = new BlockchainIdentity[1];
+// remoteIdentities2[0] = remoteAccount2.getIdentity();
+//
+// cordinator.joinLedger(cordinator.getLedgerDefinition().getDefinitionId(), remotepeer1, remoteIdentities1, new BlockchainOperation[0]);
+// cordinator.joinLedger(cordinator.getLedgerDefinition().getDefinitionId(), remotepeer2, remoteIdentities2, new BlockchainOperation[0]);
+//
+// assertEquals(cordinator.getLedgerDefinition().genesisAccountNum(), 3);
+// assertEquals(cordinator.getLedgerDefinition().getInitializingOperations().length, 0);
+// }
+//
+// @Test
+// public void testPrepare() {
+// BlockchainKeyPair genesisAccount = BlockchainKeyGenerator.getInstance().generate();
+// LedgerInitCordinator cordinator = new LedgerInitCordinator(ledgerService, localpeer, genesisAccount.getIdentity());
+// cordinator.start();
+// TransactionContent content = cordinator.prepare(cordinator.getLedgerDefinition().getDefinitionId());
+//
+// assertEquals(cordinator.getLedgerDefinition().isConfigReady(), true);
+// assertEquals(content.getOperations().length, 1);
+// }
+//
+// @Test
+// public void testSign() {
+// BlockchainKeyPair genesisAccount = BlockchainKeyGenerator.getInstance().generate();
+// LedgerInitCordinator cordinator = new LedgerInitCordinator(ledgerService, localpeer, genesisAccount.getIdentity());
+// cordinator.start();
+//
+// NetworkAddress remotepeer1 = new NetworkAddress("127.0.0.1", 9001);
+// BlockchainKeyPair remoteAccount1 = BlockchainKeyGenerator.getInstance().generate();
+// BlockchainIdentity[] remoteIdentities1 = new BlockchainIdentity[1];
+// remoteIdentities1[0] = remoteAccount1.getIdentity();
+//
+// NetworkAddress remotepeer2 = new NetworkAddress("127.0.0.1", 9002);
+// BlockchainKeyPair remoteAccount2 = BlockchainKeyGenerator.getInstance().generate();
+// BlockchainIdentity[] remoteIdentities2 = new BlockchainIdentity[1];
+// remoteIdentities2[0] = remoteAccount2.getIdentity();
+//
+// cordinator.joinLedger(cordinator.getLedgerDefinition().getDefinitionId(), remotepeer1, remoteIdentities1, new BlockchainOperation[0]);
+// cordinator.joinLedger(cordinator.getLedgerDefinition().getDefinitionId(), remotepeer2, remoteIdentities2, new BlockchainOperation[0]);
+//
+// TransactionContent content = cordinator.prepare(cordinator.getLedgerDefinition().getDefinitionId());
+//
+// DigitalSignature genesisSign = cordinator.sign(genesisAccount);
+// DigitalSignature remoteSign1 = cordinator.sign(remoteAccount1);
+// DigitalSignature remoteSign2 = cordinator.sign(remoteAccount2);
+//
+// List signatures = Arrays.asList(cordinator.getLedgerDefinition().genesisSignatures());
+//
+// assertEquals(cordinator.getLedgerDefinition().genesisSignatures().length, 3);
+// assertEquals(signatures.contains(genesisSign), true);
+// assertEquals(signatures.contains(remoteSign1), true);
+// assertEquals(signatures.contains(remoteSign2), true);
+// assertEquals(cordinator.getLedgerDefinition().isSignatureReady(), true);
+// }
+//
+// @Test
+// public void testConsistent() {
+// BlockchainKeyPair genesisAccount = BlockchainKeyGenerator.getInstance().generate();
+// LedgerInitCordinator cordinator = new LedgerInitCordinator(ledgerService, localpeer, genesisAccount.getIdentity());
+// cordinator.start();
+//
+// NetworkAddress remotepeer1 = new NetworkAddress("127.0.0.1", 9001);
+// BlockchainKeyPair remoteAccount1 = BlockchainKeyGenerator.getInstance().generate();
+// BlockchainIdentity[] remoteIdentities1 = new BlockchainIdentity[1];
+// remoteIdentities1[0] = remoteAccount1.getIdentity();
+//
+// NetworkAddress remotepeer2 = new NetworkAddress("127.0.0.1", 9002);
+// BlockchainKeyPair remoteAccount2 = BlockchainKeyGenerator.getInstance().generate();
+// BlockchainIdentity[] remoteIdentities2 = new BlockchainIdentity[1];
+// remoteIdentities2[0] = remoteAccount2.getIdentity();
+//
+// cordinator.joinLedger(cordinator.getLedgerDefinition().getDefinitionId(), remotepeer1, remoteIdentities1, new BlockchainOperation[0]);
+// cordinator.joinLedger(cordinator.getLedgerDefinition().getDefinitionId(), remotepeer2, remoteIdentities2, new BlockchainOperation[0]);
+//
+// TransactionContent content = cordinator.prepare(cordinator.getLedgerDefinition().getDefinitionId());
+//
+// cordinator.sign(genesisAccount);
+// cordinator.sign(remoteAccount1);
+// cordinator.sign(remoteAccount2);
+// cordinator.preGenerateLedger();
+//
+// cordinator.addConsensusLedgerHash(cordinator.getLedgerDefinition().getDefinitionId(), genesisAccount.getAddress(), cordinator.getLedgerBuilder().getLedger().getBlockHash());
+//
+// cordinator.addConsensusLedgerHash(cordinator.getLedgerDefinition().getDefinitionId(), remoteAccount1.getAddress(), cordinator.getLedgerBuilder().getLedger().getBlockHash());
+//
+// cordinator.addConsensusLedgerHash(cordinator.getLedgerDefinition().getDefinitionId(), remoteAccount2.getAddress(), cordinator.getLedgerBuilder().getLedger().getBlockHash());
+//
+// assertEquals(cordinator.isLedgerConsistent(), true);
+// }
//}
\ No newline at end of file
diff --git a/source/peer/src/test/java/test/com/jd/blockchain/peer/web/ControllerTestConfiguration.java b/source/peer/src/test/java/test/com/jd/blockchain/peer/web/ControllerTestConfiguration.java
index 46dad9bc..12fb0710 100644
--- a/source/peer/src/test/java/test/com/jd/blockchain/peer/web/ControllerTestConfiguration.java
+++ b/source/peer/src/test/java/test/com/jd/blockchain/peer/web/ControllerTestConfiguration.java
@@ -1,37 +1,37 @@
-//package test.com.jd.blockchain.peer.web;
-//
-//import org.springframework.boot.test.mocker.mockito.MockBean;
-//import org.springframework.context.annotation.Bean;
-//import org.springframework.context.annotation.Configuration;
-//
-//import com.jd.blockchain.peer.PeerSettings;
-//import com.jd.blockchain.peer.service.MessageBroadcaster;
-//import com.jd.blockchain.peer.service.PeerKeyStorageService;
-//
-//@Configuration
-//public class ControllerTestConfiguration {
-//
-// @Bean
-// public PeerKeyStorageService peerKeyStorageService() {
-// return new PeerKeyStorageServiceImpl();
-// }
-//
-//// @MockBean
-//// private LedgerService ledgerService;
-//
-// @MockBean
-// private MessageBroadcaster msgBroadcaster; // 用于向客户端进行消息通知;
-//
-//
-// @Bean
-// public PeerSettings peerSettring() {
-// PeerSettings setting = new PeerSettings();
-// PeerSettings.ConsensusSetting consensusSetting = new PeerSettings.ConsensusSetting();
-// consensusSetting.setIp("127.0.0.1");
-// consensusSetting.setPort(9000);
-// setting.setConsensus(consensusSetting);
-//
-// return setting;
-// }
-//
-//}
+//package test.com.jd.blockchain.peer.web;
+//
+//import org.springframework.boot.test.mocker.mockito.MockBean;
+//import org.springframework.context.annotation.Bean;
+//import org.springframework.context.annotation.Configuration;
+//
+//import com.jd.blockchain.peer.PeerSettings;
+//import com.jd.blockchain.peer.service.MessageBroadcaster;
+//import com.jd.blockchain.peer.service.PeerKeyStorageService;
+//
+//@Configuration
+//public class ControllerTestConfiguration {
+//
+// @Bean
+// public PeerKeyStorageService peerKeyStorageService() {
+// return new PeerKeyStorageServiceImpl();
+// }
+//
+//// @MockBean
+//// private LedgerService ledgerService;
+//
+// @MockBean
+// private MessageBroadcaster msgBroadcaster; // 用于向客户端进行消息通知;
+//
+//
+// @Bean
+// public PeerSettings peerSettring() {
+// PeerSettings setting = new PeerSettings();
+// PeerSettings.ConsensusSetting consensusSetting = new PeerSettings.ConsensusSetting();
+// consensusSetting.setIp("127.0.0.1");
+// consensusSetting.setPort(9000);
+// setting.setConsensus(consensusSetting);
+//
+// return setting;
+// }
+//
+//}
diff --git a/source/peer/src/test/java/test/com/jd/blockchain/peer/web/LedgerInitializingControllerTest.java b/source/peer/src/test/java/test/com/jd/blockchain/peer/web/LedgerInitializingControllerTest.java
index c1736b31..d48952da 100644
--- a/source/peer/src/test/java/test/com/jd/blockchain/peer/web/LedgerInitializingControllerTest.java
+++ b/source/peer/src/test/java/test/com/jd/blockchain/peer/web/LedgerInitializingControllerTest.java
@@ -1,245 +1,245 @@
-//package test.com.jd.blockchain.peer.web;
-//
-//import static org.junit.Assert.assertEquals;
-//import static org.mockito.Matchers.any;
-//
-//import java.util.Arrays;
-//import java.util.List;
-//
-//import com.jd.blockchain.ledger.service.impl.LedgerServiceImpl;
-//import org.junit.*;
-//import org.junit.runner.RunWith;
-//import org.junit.runners.MethodSorters;
-//import org.springframework.beans.factory.annotation.Autowired;
-//import org.springframework.boot.test.context.SpringBootTest;
-//import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-//import org.springframework.util.Base64Utils;
-//
-//import com.jd.blockchain.binaryproto.BinaryEncodingUtils;
-//import com.jd.blockchain.ledger.AccountRegisterOperation;
-//import com.jd.blockchain.ledger.AccountStateOperation;
-//import com.jd.blockchain.ledger.AccountStateType;
-//import com.jd.blockchain.ledger.BlockchainIdentity;
-//import com.jd.blockchain.ledger.BlockchainKeyGenerator;
-//import com.jd.blockchain.ledger.BlockchainKeyPair;
-//import com.jd.blockchain.ledger.BlockchainOperation;
-//import com.jd.blockchain.ledger.DigitalSignature;
-//import com.jd.blockchain.ledger.Ledger;
-//import com.jd.blockchain.ledger.TransactionContent;
-//import com.jd.blockchain.ledger.data.BlockchainOperationFactory;
-//import com.jd.blockchain.ledger.data.SignatureEncoding;
-//import com.jd.blockchain.ledger.service.LedgerBuilder;
-//import com.jd.blockchain.ledger.service.LedgerService;
-//import com.jd.blockchain.peer.PeerSettings;
-//import com.jd.blockchain.peer.service.LedgerDefinition;
-//import com.jd.blockchain.peer.service.MessageBroadcaster;
-//import com.jd.blockchain.peer.service.PeerKeyStorageService;
-//import com.jd.blockchain.peer.web.JoinLedgerParameter;
-//import com.jd.blockchain.peer.web.LedgerInitializationContext;
-//import com.jd.blockchain.peer.web.LedgerInitializingController;
-//import com.jd.blockchain.storage.service.impl.hashmap.HashMapStorageService;
-//
-//import my.utils.io.ByteArray;
-//import my.utils.net.NetworkAddress;
-//import my.utils.serialize.binary.BinarySerializeUtils;
-//import my.utils.serialize.json.JSONSerializeUtils;
-//
-//@Ignore
-//@RunWith(SpringJUnit4ClassRunner.class)
-//@SpringBootTest(classes = {ControllerTestConfiguration.class})
-//@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-//public class LedgerInitializingControllerTest {
-//
-// @Autowired
-// private PeerKeyStorageService keystoreService;
-//
-// @Autowired
-// private LedgerService ledgerService;
-//
-// @Autowired
-// private PeerSettings peerSettings;
-//
-// @Autowired
-// private MessageBroadcaster msgBroadcaster; // 用于向客户端进行消息通知;
-//
-// private LedgerInitializingController controller;
-//
-// @BeforeClass
-// public static void setUpBeforeClass() throws Exception {
-// }
-//
-// @AfterClass
-// public static void tearDownAfterClass() throws Exception {
-// }
-//
-// private BlockchainKeyPair keyOfP1 = BlockchainKeyGenerator.getInstance().generate();
-//
-// @Before
-// public void setup() {
-// ledgerService = new LedgerServiceImpl(new HashMapStorageService());
-// controller = new LedgerInitializingController(peerSettings, keystoreService, ledgerService, msgBroadcaster);
-//
-// //when(ledgerService.newLedger()).thenReturn(new LedgerBuilderImpl(ByteArray.wrap("genesisKey".getBytes()), ledgerService));
-// //when(ledgerService.newLedger(ByteArray.wrap("genesisKey".getBytes()))).thenReturn(new LedgerBuilderImpl(ByteArray.wrap("genesisKey".getBytes()), ledgerService));
-// }
-//
-// @After
-// public void after() {
-// controller = null;
-// }
-//
-// @Test
-// public void testStartNewLedger() {
-// LedgerInitializationContext context = controller.startNewLedger("TestParticipantName", PeerKeyStorageServiceImpl.keyOfP1.getAddress());
-//
-// assertEquals(context.getLocalAccount(), keystoreService.getBlockchainKey(PeerKeyStorageServiceImpl.keyOfP1.getAddress()).getIdentity());
-// assertEquals(context.getLocalConsensusAddress(), new NetworkAddress(peerSettings.getConsensus().getIp(), peerSettings.getConsensus().getPort()));
-// assertEquals(context.getLedgerDefinition().genesisAccountNum(), 1);
-// assertEquals(context.getLedgerDefinition().isConfigReady(), false);
-// assertEquals(context.getLedgerDefinition().getInitializingOperations().length, 2);
-//
-// JSONSerializeUtils.disableCircularReferenceDetect();
-// JSONSerializeUtils.configStringSerializer(ByteArray.class);
-// System.out.println(JSONSerializeUtils.serializeToJSON(context));
-// }
-//
-// @Test
-// public void testStartJoiningLedger() {
-// LedgerInitializationContext context = controller.startNewLedger("TestParticipantName", PeerKeyStorageServiceImpl.keyOfP1.getAddress());
-//
-// JoinLedgerParameter parameter = new JoinLedgerParameter();
-// BlockchainKeyPair identity = BlockchainKeyGenerator.getInstance().generate();
-// parameter.setGenesisAccounts(new BlockchainIdentity[]{identity.getIdentity()});
-//
-// AccountRegisterOperation regGenesisAccountOP = BlockchainOperationFactory.getInstance().register(identity.getIdentity(),
-// AccountStateType.MAP);
-// AccountStateOperation initGenesisAccountInfoOP = BlockchainOperationFactory.getInstance()
-// .updateState(identity.getAddress());
-// initGenesisAccountInfoOP.putString("NAME", "joinLedger");
-// initGenesisAccountInfoOP.putString("DESCRIPTION", "");
-//
-// parameter.setOperations(new BlockchainOperation[]{regGenesisAccountOP, initGenesisAccountInfoOP});
-// parameter.setNetworkAddress(new NetworkAddress("127.0.0.1", 9001));
-//
-// LedgerDefinition definition = decodeObject(controller.joinLedger(context.getLedgerDefinition().getDefinitionId(), encodeObject(parameter)), LedgerDefinition.class);
-//
-// assertEquals(definition.genesisAccountNum(), 2);
-// assertEquals(definition.getInitializingOperations().length, 4);
-// assertEquals(definition.isConfigReady(), false);
-// }
-//
-// @Test
-// public void testPrepare() {
-// LedgerInitializationContext context = controller.startNewLedger("TestParticipantName",PeerKeyStorageServiceImpl.keyOfP1.getAddress());
-//
-// JoinLedgerParameter parameter = new JoinLedgerParameter();
-// BlockchainIdentity identity = keystoreService.generateNewKey("identity").getIdentity();
-//
-// parameter.setGenesisAccounts(new BlockchainIdentity[]{identity});
-//
-// AccountRegisterOperation regGenesisAccountOP = BlockchainOperationFactory.getInstance().register(identity, AccountStateType.MAP);
-// AccountStateOperation initGenesisAccountInfoOP = BlockchainOperationFactory.getInstance()
-// .updateState(identity.getAddress());
-// initGenesisAccountInfoOP.putString("NAME", "joinLedger");
-// initGenesisAccountInfoOP.putString("DESCRIPTION", "");
-//
-// parameter.setOperations(new BlockchainOperation[]{regGenesisAccountOP, initGenesisAccountInfoOP});
-// parameter.setNetworkAddress(new NetworkAddress("127.0.0.1", 9001));
-//
-// controller.joinLedger(context.getLedgerDefinition().getDefinitionId(), encodeObject(parameter));
-// context = controller.prepareAndSign();
-//
-// assertEquals(context.getLedgerDefinition().isConfigReady(), true);
-// }
-//
-// @Test
-// public void testAttachSignature() {
-// LedgerInitializationContext context = controller.startNewLedger("TestParticipantName", PeerKeyStorageServiceImpl.keyOfP1.getAddress());
-// JoinLedgerParameter parameter = new JoinLedgerParameter();
-// BlockchainIdentity identity = keystoreService.generateNewKey("identity").getIdentity();
-//
-// parameter.setGenesisAccounts(new BlockchainIdentity[]{identity});
-// parameter.setOperations(new BlockchainOperation[]{});
-// parameter.setNetworkAddress(new NetworkAddress("127.0.0.1", 9001));
-//
-// controller.joinLedger(context.getLedgerDefinition().getDefinitionId(), encodeObject(parameter));
-// context = controller.prepareAndSign();
-//
-// LedgerBuilder ledgerBuilder = ledgerService.newLedger(context.getLedgerDefinition().getGenesisKey());
-// ledgerBuilder.addLedgerKeys(context.getLedgerDefinition().genesisIdentites());
-// ledgerBuilder.addInitializeOperations(context.getLedgerDefinition().getInitializingOperations());
-//
-// TransactionContent txContent = ledgerBuilder.prepare();
-// context.setTransaction(txContent);
-//
-// byte[] txContentBytes = BinaryEncodingUtils.encode(txContent, TransactionContent.class);
-// DigitalSignature signature = keystoreService.sign(txContentBytes, identity.getAddress());
-// ledgerBuilder.attachSignature(signature);
-//
-// String base64Signature = SignatureEncoding.encodeToBase64(signature);
-// controller.attachSignature(context.getLedgerDefinition().getDefinitionId(), base64Signature);
-//
-// List signatures = Arrays.asList(context.getLedgerDefinition().genesisSignatures());
-//
-// assertEquals(context.getLedgerDefinition().genesisSignatures().length, 2);
-// assertEquals(signatures.contains(signature), true);
-// assertEquals(context.getLedgerDefinition().isSignatureReady(), true);
-// }
-//
-// @Test
-// public void testconsensusLedger() {
-// LedgerInitializationContext context = controller.startNewLedger("TestParticipantName", PeerKeyStorageServiceImpl.keyOfP1.getAddress());
-//
-// BlockchainIdentity identity = PeerKeyStorageServiceImpl.keyOfP2.getIdentity();
-// JoinLedgerParameter parameter = new JoinLedgerParameter();
-// parameter.setGenesisAccounts(new BlockchainIdentity[]{identity});
-// parameter.setOperations(new BlockchainOperation[]{});
-// parameter.setNetworkAddress(new NetworkAddress("127.0.0.1", 9001));
-//
-// controller.joinLedger(context.getLedgerDefinition().getDefinitionId(), encodeObject(parameter));
-// context = controller.prepareAndSign();
-//
-// // other peer
-// LedgerBuilder builder = ledgerService.newLedger(context.getLedgerDefinition().getGenesisKey());
-// builder.addLedgerKeys(context.getLedgerDefinition().genesisIdentites());
-// builder.addInitializeOperations(context.getLedgerDefinition().getInitializingOperations());
-//
-// builder.prepare();
-// String base64Signature = SignatureEncoding.encodeToBase64(builder.sign(PeerKeyStorageServiceImpl.keyOfP2));
-// controller.attachSignature(context.getLedgerDefinition().getDefinitionId(), base64Signature);
-//
-// // 附加全部的签名列表到本地,生成创世区块,建立账本,并提交账本hash到协调节点进行共识;
-// context = controller.getLedgerInitContext();
-// for (DigitalSignature signature1 : context.getLedgerDefinition().genesisSignatures()) {
-// builder.attachSignature(signature1);
-// }
-//
-// builder.preCommit();
-// Ledger ledger = builder.getLedger();
-//
-// // 向协调节点发送账本hash进行共识;
-// controller.consensusLedger(context.getLedgerDefinition().getDefinitionId(), identity.getAddress(), ledger.getLedgerHash().toBase64());
-//
-// assertEquals(true, controller.getLedgerInitContext().isConsistent());
-// }
-//
-// private String encodeObject(Object obj) {
-// byte[] bts = BinarySerializeUtils.serialize(obj);
-// return Base64Utils.encodeToString(bts);
-// }
-//
-// @SuppressWarnings("unchecked")
-// private T decodeObject(String base64Str, Class clazz) {
-// byte[] bts = Base64Utils.decodeFromString(base64Str);
-// // if (BytesReader.class.isAssignableFrom(clazz)) {
-// // BytesReader instance = (BytesReader) BeanUtils.instantiate(clazz);
-// // try {
-// // instance.resolvFrom(new ByteArrayInputStream(bts));
-// // } catch (IOException e) {
-// // throw new IORuntimeException(e.getMessage(), e);
-// // }
-// // return (T) instance;
-// // }
-// return (T) BinarySerializeUtils.deserialize(bts);
-// }
-//}
+//package test.com.jd.blockchain.peer.web;
+//
+//import static org.junit.Assert.assertEquals;
+//import static org.mockito.Matchers.any;
+//
+//import java.util.Arrays;
+//import java.util.List;
+//
+//import com.jd.blockchain.ledger.service.impl.LedgerServiceImpl;
+//import org.junit.*;
+//import org.junit.runner.RunWith;
+//import org.junit.runners.MethodSorters;
+//import org.springframework.beans.factory.annotation.Autowired;
+//import org.springframework.boot.test.context.SpringBootTest;
+//import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+//import org.springframework.util.Base64Utils;
+//
+//import com.jd.blockchain.binaryproto.BinaryEncodingUtils;
+//import com.jd.blockchain.ledger.AccountRegisterOperation;
+//import com.jd.blockchain.ledger.AccountStateOperation;
+//import com.jd.blockchain.ledger.AccountStateType;
+//import com.jd.blockchain.ledger.BlockchainIdentity;
+//import com.jd.blockchain.ledger.BlockchainKeyGenerator;
+//import com.jd.blockchain.ledger.BlockchainKeyPair;
+//import com.jd.blockchain.ledger.BlockchainOperation;
+//import com.jd.blockchain.ledger.DigitalSignature;
+//import com.jd.blockchain.ledger.Ledger;
+//import com.jd.blockchain.ledger.TransactionContent;
+//import com.jd.blockchain.ledger.data.BlockchainOperationFactory;
+//import com.jd.blockchain.ledger.data.SignatureEncoding;
+//import com.jd.blockchain.ledger.service.LedgerBuilder;
+//import com.jd.blockchain.ledger.service.LedgerService;
+//import com.jd.blockchain.peer.PeerSettings;
+//import com.jd.blockchain.peer.service.LedgerDefinition;
+//import com.jd.blockchain.peer.service.MessageBroadcaster;
+//import com.jd.blockchain.peer.service.PeerKeyStorageService;
+//import com.jd.blockchain.peer.web.JoinLedgerParameter;
+//import com.jd.blockchain.peer.web.LedgerInitializationContext;
+//import com.jd.blockchain.peer.web.LedgerInitializingController;
+//import com.jd.blockchain.storage.service.impl.hashmap.HashMapStorageService;
+//
+//import my.utils.io.ByteArray;
+//import my.utils.net.NetworkAddress;
+//import my.utils.serialize.binary.BinarySerializeUtils;
+//import my.utils.serialize.json.JSONSerializeUtils;
+//
+//@Ignore
+//@RunWith(SpringJUnit4ClassRunner.class)
+//@SpringBootTest(classes = {ControllerTestConfiguration.class})
+//@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+//public class LedgerInitializingControllerTest {
+//
+// @Autowired
+// private PeerKeyStorageService keystoreService;
+//
+// @Autowired
+// private LedgerService ledgerService;
+//
+// @Autowired
+// private PeerSettings peerSettings;
+//
+// @Autowired
+// private MessageBroadcaster msgBroadcaster; // 用于向客户端进行消息通知;
+//
+// private LedgerInitializingController controller;
+//
+// @BeforeClass
+// public static void setUpBeforeClass() throws Exception {
+// }
+//
+// @AfterClass
+// public static void tearDownAfterClass() throws Exception {
+// }
+//
+// private BlockchainKeyPair keyOfP1 = BlockchainKeyGenerator.getInstance().generate();
+//
+// @Before
+// public void setup() {
+// ledgerService = new LedgerServiceImpl(new HashMapStorageService());
+// controller = new LedgerInitializingController(peerSettings, keystoreService, ledgerService, msgBroadcaster);
+//
+// //when(ledgerService.newLedger()).thenReturn(new LedgerBuilderImpl(ByteArray.wrap("genesisKey".getBytes()), ledgerService));
+// //when(ledgerService.newLedger(ByteArray.wrap("genesisKey".getBytes()))).thenReturn(new LedgerBuilderImpl(ByteArray.wrap("genesisKey".getBytes()), ledgerService));
+// }
+//
+// @After
+// public void after() {
+// controller = null;
+// }
+//
+// @Test
+// public void testStartNewLedger() {
+// LedgerInitializationContext context = controller.startNewLedger("TestParticipantName", PeerKeyStorageServiceImpl.keyOfP1.getAddress());
+//
+// assertEquals(context.getLocalAccount(), keystoreService.getBlockchainKey(PeerKeyStorageServiceImpl.keyOfP1.getAddress()).getIdentity());
+// assertEquals(context.getLocalConsensusAddress(), new NetworkAddress(peerSettings.getConsensus().getIp(), peerSettings.getConsensus().getPort()));
+// assertEquals(context.getLedgerDefinition().genesisAccountNum(), 1);
+// assertEquals(context.getLedgerDefinition().isConfigReady(), false);
+// assertEquals(context.getLedgerDefinition().getInitializingOperations().length, 2);
+//
+// JSONSerializeUtils.disableCircularReferenceDetect();
+// JSONSerializeUtils.configStringSerializer(ByteArray.class);
+// System.out.println(JSONSerializeUtils.serializeToJSON(context));
+// }
+//
+// @Test
+// public void testStartJoiningLedger() {
+// LedgerInitializationContext context = controller.startNewLedger("TestParticipantName", PeerKeyStorageServiceImpl.keyOfP1.getAddress());
+//
+// JoinLedgerParameter parameter = new JoinLedgerParameter();
+// BlockchainKeyPair identity = BlockchainKeyGenerator.getInstance().generate();
+// parameter.setGenesisAccounts(new BlockchainIdentity[]{identity.getIdentity()});
+//
+// AccountRegisterOperation regGenesisAccountOP = BlockchainOperationFactory.getInstance().register(identity.getIdentity(),
+// AccountStateType.MAP);
+// AccountStateOperation initGenesisAccountInfoOP = BlockchainOperationFactory.getInstance()
+// .updateState(identity.getAddress());
+// initGenesisAccountInfoOP.putString("NAME", "joinLedger");
+// initGenesisAccountInfoOP.putString("DESCRIPTION", "");
+//
+// parameter.setOperations(new BlockchainOperation[]{regGenesisAccountOP, initGenesisAccountInfoOP});
+// parameter.setNetworkAddress(new NetworkAddress("127.0.0.1", 9001));
+//
+// LedgerDefinition definition = decodeObject(controller.joinLedger(context.getLedgerDefinition().getDefinitionId(), encodeObject(parameter)), LedgerDefinition.class);
+//
+// assertEquals(definition.genesisAccountNum(), 2);
+// assertEquals(definition.getInitializingOperations().length, 4);
+// assertEquals(definition.isConfigReady(), false);
+// }
+//
+// @Test
+// public void testPrepare() {
+// LedgerInitializationContext context = controller.startNewLedger("TestParticipantName",PeerKeyStorageServiceImpl.keyOfP1.getAddress());
+//
+// JoinLedgerParameter parameter = new JoinLedgerParameter();
+// BlockchainIdentity identity = keystoreService.generateNewKey("identity").getIdentity();
+//
+// parameter.setGenesisAccounts(new BlockchainIdentity[]{identity});
+//
+// AccountRegisterOperation regGenesisAccountOP = BlockchainOperationFactory.getInstance().register(identity, AccountStateType.MAP);
+// AccountStateOperation initGenesisAccountInfoOP = BlockchainOperationFactory.getInstance()
+// .updateState(identity.getAddress());
+// initGenesisAccountInfoOP.putString("NAME", "joinLedger");
+// initGenesisAccountInfoOP.putString("DESCRIPTION", "");
+//
+// parameter.setOperations(new BlockchainOperation[]{regGenesisAccountOP, initGenesisAccountInfoOP});
+// parameter.setNetworkAddress(new NetworkAddress("127.0.0.1", 9001));
+//
+// controller.joinLedger(context.getLedgerDefinition().getDefinitionId(), encodeObject(parameter));
+// context = controller.prepareAndSign();
+//
+// assertEquals(context.getLedgerDefinition().isConfigReady(), true);
+// }
+//
+// @Test
+// public void testAttachSignature() {
+// LedgerInitializationContext context = controller.startNewLedger("TestParticipantName", PeerKeyStorageServiceImpl.keyOfP1.getAddress());
+// JoinLedgerParameter parameter = new JoinLedgerParameter();
+// BlockchainIdentity identity = keystoreService.generateNewKey("identity").getIdentity();
+//
+// parameter.setGenesisAccounts(new BlockchainIdentity[]{identity});
+// parameter.setOperations(new BlockchainOperation[]{});
+// parameter.setNetworkAddress(new NetworkAddress("127.0.0.1", 9001));
+//
+// controller.joinLedger(context.getLedgerDefinition().getDefinitionId(), encodeObject(parameter));
+// context = controller.prepareAndSign();
+//
+// LedgerBuilder ledgerBuilder = ledgerService.newLedger(context.getLedgerDefinition().getGenesisKey());
+// ledgerBuilder.addLedgerKeys(context.getLedgerDefinition().genesisIdentites());
+// ledgerBuilder.addInitializeOperations(context.getLedgerDefinition().getInitializingOperations());
+//
+// TransactionContent txContent = ledgerBuilder.prepare();
+// context.setTransaction(txContent);
+//
+// byte[] txContentBytes = BinaryEncodingUtils.encode(txContent, TransactionContent.class);
+// DigitalSignature signature = keystoreService.sign(txContentBytes, identity.getAddress());
+// ledgerBuilder.attachSignature(signature);
+//
+// String base64Signature = SignatureEncoding.encodeToBase64(signature);
+// controller.attachSignature(context.getLedgerDefinition().getDefinitionId(), base64Signature);
+//
+// List signatures = Arrays.asList(context.getLedgerDefinition().genesisSignatures());
+//
+// assertEquals(context.getLedgerDefinition().genesisSignatures().length, 2);
+// assertEquals(signatures.contains(signature), true);
+// assertEquals(context.getLedgerDefinition().isSignatureReady(), true);
+// }
+//
+// @Test
+// public void testconsensusLedger() {
+// LedgerInitializationContext context = controller.startNewLedger("TestParticipantName", PeerKeyStorageServiceImpl.keyOfP1.getAddress());
+//
+// BlockchainIdentity identity = PeerKeyStorageServiceImpl.keyOfP2.getIdentity();
+// JoinLedgerParameter parameter = new JoinLedgerParameter();
+// parameter.setGenesisAccounts(new BlockchainIdentity[]{identity});
+// parameter.setOperations(new BlockchainOperation[]{});
+// parameter.setNetworkAddress(new NetworkAddress("127.0.0.1", 9001));
+//
+// controller.joinLedger(context.getLedgerDefinition().getDefinitionId(), encodeObject(parameter));
+// context = controller.prepareAndSign();
+//
+// // other peer
+// LedgerBuilder builder = ledgerService.newLedger(context.getLedgerDefinition().getGenesisKey());
+// builder.addLedgerKeys(context.getLedgerDefinition().genesisIdentites());
+// builder.addInitializeOperations(context.getLedgerDefinition().getInitializingOperations());
+//
+// builder.prepare();
+// String base64Signature = SignatureEncoding.encodeToBase64(builder.sign(PeerKeyStorageServiceImpl.keyOfP2));
+// controller.attachSignature(context.getLedgerDefinition().getDefinitionId(), base64Signature);
+//
+// // 附加全部的签名列表到本地,生成创世区块,建立账本,并提交账本hash到协调节点进行共识;
+// context = controller.getLedgerInitContext();
+// for (DigitalSignature signature1 : context.getLedgerDefinition().genesisSignatures()) {
+// builder.attachSignature(signature1);
+// }
+//
+// builder.preCommit();
+// Ledger ledger = builder.getLedger();
+//
+// // 向协调节点发送账本hash进行共识;
+// controller.consensusLedger(context.getLedgerDefinition().getDefinitionId(), identity.getAddress(), ledger.getLedgerHash().toBase64());
+//
+// assertEquals(true, controller.getLedgerInitContext().isConsistent());
+// }
+//
+// private String encodeObject(Object obj) {
+// byte[] bts = BinarySerializeUtils.serialize(obj);
+// return Base64Utils.encodeToString(bts);
+// }
+//
+// @SuppressWarnings("unchecked")
+// private T decodeObject(String base64Str, Class clazz) {
+// byte[] bts = Base64Utils.decodeFromString(base64Str);
+// // if (BytesReader.class.isAssignableFrom(clazz)) {
+// // BytesReader instance = (BytesReader) BeanUtils.instantiate(clazz);
+// // try {
+// // instance.resolvFrom(new ByteArrayInputStream(bts));
+// // } catch (IOException e) {
+// // throw new IORuntimeException(e.getMessage(), e);
+// // }
+// // return (T) instance;
+// // }
+// return (T) BinarySerializeUtils.deserialize(bts);
+// }
+//}
diff --git a/source/peer/src/test/java/test/com/jd/blockchain/peer/web/LedgerInitializingTest.java b/source/peer/src/test/java/test/com/jd/blockchain/peer/web/LedgerInitializingTest.java
index 0595ced1..68550bd7 100644
--- a/source/peer/src/test/java/test/com/jd/blockchain/peer/web/LedgerInitializingTest.java
+++ b/source/peer/src/test/java/test/com/jd/blockchain/peer/web/LedgerInitializingTest.java
@@ -1,252 +1,252 @@
-//package test.com.jd.blockchain.peer.web;
-//
-//import static org.mockito.Matchers.any;
-//import static org.mockito.Matchers.anyInt;
-//import static org.mockito.Mockito.mocker;
-//import static org.mockito.Mockito.spy;
-//import static org.mockito.Mockito.when;
-//
-//import org.junit.After;
-//import org.junit.AfterClass;
-//import org.junit.Before;
-//import org.junit.BeforeClass;
-//import org.junit.FixMethodOrder;
-//import org.junit.Ignore;
-//import org.junit.Test;
-//import org.junit.runner.RunWith;
-//import org.junit.runners.MethodSorters;
-//import org.mockito.invocation.InvocationOnMock;
-//import org.mockito.stubbing.Answer;
-//import org.springframework.beans.factory.annotation.Autowired;
-//import org.springframework.boot.test.context.SpringBootTest;
-//import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-//
-//import com.jd.blockchain.ledger.BlockchainIdentity;
-//import com.jd.blockchain.ledger.BlockchainKeyPair;
-//import com.jd.blockchain.ledger.DigitalSignature;
-//import com.jd.blockchain.ledger.data.SignatureUtils;
-//import com.jd.blockchain.ledger.service.LedgerService;
-//import com.jd.blockchain.ledger.service.impl.LedgerServiceImpl;
-//import com.jd.blockchain.peer.PeerSettings;
-//import com.jd.blockchain.peer.service.BlockchainKeyInfo;
-//import com.jd.blockchain.peer.service.MessageBroadcaster;
-//import com.jd.blockchain.peer.service.PeerKeyStorageService;
-//import com.jd.blockchain.peer.web.LedgerInitializationContext;
-//import com.jd.blockchain.peer.web.LedgerInitializingController;
-//import com.jd.blockchain.peer.web.LedgerInitializingHttpService;
-//import com.jd.blockchain.storage.service.impl.redis.RedisStorageService;
-//
-//import my.utils.io.ByteArray;
-//import redis.clients.jedis.Jedis;
-//
-//@Ignore
-//@RunWith(SpringJUnit4ClassRunner.class)
-//@SpringBootTest(classes = { ControllerTestConfiguration.class})
-//@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-//public class LedgerInitializingTest {
-//
-// @Autowired
-// private PeerKeyStorageService keyStorageService;
-//
-// @BeforeClass
-// public static void setUpBeforeClass() throws Exception {
-// }
-//
-// @AfterClass
-// public static void tearDownAfterClass() throws Exception {
-// }
-//
-// @Before
-// public void setup() {
-// }
-//
-// @After
-// public void after() {
-// }
-//
-// @Test
-// public void testStartNewLedger() {
-// // 准备上下文;
-// ServerContext cordinator = new ServerContext("cordinator", 0, 9000, keyStorageService);
-//
-// ServerContext participant1 = new ServerContext("participant1", 1, 9001, keyStorageService);
-// participant1.setLedgerInitHttpServiceProxy(cordinator.getController());
-//
-// ServerContext participant2 = new ServerContext("participant2", 2, 9002, keyStorageService);
-// participant2.setLedgerInitHttpServiceProxy(cordinator.getController());
-//
-// ServerContext participant3 = new ServerContext("participant3", 3, 9003, keyStorageService);
-// participant3.setLedgerInitHttpServiceProxy(cordinator.getController());
-//
-// // 协调节点开始新建账本;
-// LedgerInitializationContext ctx = cordinator.controller.startNewLedger(cordinator.keyInfo.getName(),
-// cordinator.keyInfo.getIdentity().getAddress());
-// String defId = ctx.getLedgerDefinition().getDefinitionId();
-//
-// // 参与者加入账本;
-// participant1.controller.startJoiningLedger(defId, "localhost", 9000, participant1.keyInfo.getName(),
-// participant1.keyInfo.getIdentity().getAddress());
-// participant2.controller.startJoiningLedger(defId, "localhost", 9000, participant2.keyInfo.getName(),
-// participant2.keyInfo.getIdentity().getAddress());
-// participant3.controller.startJoiningLedger(defId, "localhost", 9000, participant3.keyInfo.getName(),
-// participant3.keyInfo.getIdentity().getAddress());
-//
-// // TODO:断言协调节点已经收到了参与者的请求;
-//
-//
-// // 协调节点签署账本;
-// cordinator.controller.prepareAndSign();
-//
-// // 等待各个参与节点完成签署和生成块;
-// try {
-// Thread.sleep(5000);
-// } catch (InterruptedException e) {
-// // Swallow InterruptedException;
-// }
-//
-// LedgerInitializationContext cordCtx = cordinator.controller.getLedgerInitContext();
-// LedgerInitializationContext part1Ctx = participant1.controller.getLedgerInitContext();
-// LedgerInitializationContext part2Ctx = participant2.controller.getLedgerInitContext();
-// LedgerInitializationContext part3Ctx = participant3.controller.getLedgerInitContext();
-//
-// // 断言各个参与节点都达到了块一致的状态;
-// //ssertTrue(cordCtx.isConsistent());
-//
-// // 等待各个参与节点完成签署和生成块;
-// try {
-// Thread.sleep(5000);
-// } catch (InterruptedException e) {
-// // Swallow InterruptedException;
-// }
-// //assertTrue(part1Ctx.isConsistent());
-// //assertTrue(part2Ctx.isConsistent());
-// //assertTrue(part3Ctx.isConsistent());
-//
-// // 断言各个参与节点的块都是真正地一致;
-// //assertEquals(cordCtx.getLedger().getLedgerHash(), part1Ctx.getLedger().getLedgerHash());
-// //assertEquals(cordCtx.getLedger().getLedgerHash(), part2Ctx.getLedger().getLedgerHash());
-// //assertEquals(cordCtx.getLedger().getLedgerHash(), part3Ctx.getLedger().getLedgerHash());
-//
-// // 协调节点提交;
-// cordinator.controller.commitLedger();
-//
-// // 等待各个参与节点完成提交;
-// try {
-// Thread.sleep(5000);
-// } catch (InterruptedException e) {
-// // Swallow InterruptedException;
-// }
-//
-// // 断言各个参与节点的状态都被重置了;
-// cordCtx = cordinator.controller.getLedgerInitContext();
-// part1Ctx = participant1.controller.getLedgerInitContext();
-// part2Ctx = participant2.controller.getLedgerInitContext();
-// part3Ctx = participant3.controller.getLedgerInitContext();
-//
-// //assertFalse(cordCtx.isJoined());
-// //assertFalse(part1Ctx.isJoined());
-// //assertFalse(part2Ctx.isJoined());
-// //assertFalse(part3Ctx.isJoined());
-//
-// //assertNull(cordCtx.getLedgerDefinition());
-// //assertNull(part1Ctx.getLedgerDefinition());
-// //assertNull(part2Ctx.getLedgerDefinition());
-// //assertNull(part3Ctx.getLedgerDefinition());
-// }
-//
-// public static class ServerContext {
-//
-// private PeerKeyStorageService keystoreService;
-//
-// private LedgerService ledgerService;
-//
-// private PeerSettings peerSettings;
-//
-// private MessageBroadcaster msgBroadcaster; // 用于向客户端进行消息通知;
-//
-// private LedgerInitializingController controller;
-//
-// //private final BlockchainKeyPair key;
-//
-// private final BlockchainIdentity identity;
-//
-// private final BlockchainKeyInfo keyInfo;
-//
-// private LedgerInitializingHttpService ledgerInitHttpServiceProxy;
-//
-// public ServerContext(String name, int idx, int port, PeerKeyStorageService keystoreService) {
-// Jedis jedis = new Jedis("192.168.151.33", 6379);
-// jedis.select(idx);
-// jedis.connect();
-//
-// this.ledgerService = new LedgerServiceImpl(new RedisStorageService(jedis));
-// this.peerSettings = peerSetting(port);
-// this.keystoreService = keystoreService;
-//
-// this.keyInfo = this.keystoreService.generateNewKey(name);
-// this.identity = this.keyInfo.getIdentity();
-//
-// //this.key = BlockchainKeyGenerator.getInstance().generate(KeyType.ED25519);
-// //this.keyInfo = new BlockchainKeyInfo();
-// //this.keyInfo.setName(name);
-// //this.keyInfo.setIdentity(key.getIdentity());
-//
-// initTestContext();
-// }
-//
-//
-// private PeerSettings peerSetting(int port) {
-// PeerSettings setting = new PeerSettings();
-// PeerSettings.ConsensusSetting consensusSetting = new PeerSettings.ConsensusSetting();
-// consensusSetting.setIp("127.0.0.1");
-// consensusSetting.setPort(port);
-// setting.setConsensus(consensusSetting);
-//
-// return setting;
-// }
-//
-//
-// private void initTestContext() {
-// //keystoreService = spy(PeerKeyStorageServiceImpl.class);
-// //when(keystoreService.getBlockchainKey(key.getAddress())).thenReturn(keyInfo);
-// //when(keystoreService.sign(any(), key.getAddress())).then(answerSignature(key));
-//
-// msgBroadcaster = mocker(MessageBroadcaster.class);
-//
-// LedgerInitializingController ctrl = new LedgerInitializingController(peerSettings, keystoreService,
-// ledgerService, msgBroadcaster);
-// this.controller = spy(ctrl);
-//
-// when(controller.getLedgerInitHttpService(any(), anyInt())).then(new Answer() {
-// @Override
-// public LedgerInitializingHttpService answer(InvocationOnMock invocationOnMock) throws Throwable {
-// return ledgerInitHttpServiceProxy;
-// }
-// });
-// }
-//
-// private Answer answerSignature(BlockchainKeyPair keyPair) {
-// return new Answer() {
-// @Override
-// public DigitalSignature answer(InvocationOnMock invocation) throws Throwable {
-// Object[] args = invocation.getArguments();
-// ByteArray data = (ByteArray) args[0];
-// return SignatureUtils.sign(data, keyPair);
-// }
-// };
-// }
-//
-// public LedgerInitializingController getController() {
-// return controller;
-// }
-//
-// public LedgerInitializingHttpService getLedgerInitHttpServiceProxy() {
-// return ledgerInitHttpServiceProxy;
-// }
-//
-// public void setLedgerInitHttpServiceProxy(LedgerInitializingHttpService ledgerInitHttpServiceProxy) {
-// this.ledgerInitHttpServiceProxy = ledgerInitHttpServiceProxy;
-// }
-//
-// }
-//}
+//package test.com.jd.blockchain.peer.web;
+//
+//import static org.mockito.Matchers.any;
+//import static org.mockito.Matchers.anyInt;
+//import static org.mockito.Mockito.mocker;
+//import static org.mockito.Mockito.spy;
+//import static org.mockito.Mockito.when;
+//
+//import org.junit.After;
+//import org.junit.AfterClass;
+//import org.junit.Before;
+//import org.junit.BeforeClass;
+//import org.junit.FixMethodOrder;
+//import org.junit.Ignore;
+//import org.junit.Test;
+//import org.junit.runner.RunWith;
+//import org.junit.runners.MethodSorters;
+//import org.mockito.invocation.InvocationOnMock;
+//import org.mockito.stubbing.Answer;
+//import org.springframework.beans.factory.annotation.Autowired;
+//import org.springframework.boot.test.context.SpringBootTest;
+//import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+//
+//import com.jd.blockchain.ledger.BlockchainIdentity;
+//import com.jd.blockchain.ledger.BlockchainKeyPair;
+//import com.jd.blockchain.ledger.DigitalSignature;
+//import com.jd.blockchain.ledger.data.SignatureUtils;
+//import com.jd.blockchain.ledger.service.LedgerService;
+//import com.jd.blockchain.ledger.service.impl.LedgerServiceImpl;
+//import com.jd.blockchain.peer.PeerSettings;
+//import com.jd.blockchain.peer.service.BlockchainKeyInfo;
+//import com.jd.blockchain.peer.service.MessageBroadcaster;
+//import com.jd.blockchain.peer.service.PeerKeyStorageService;
+//import com.jd.blockchain.peer.web.LedgerInitializationContext;
+//import com.jd.blockchain.peer.web.LedgerInitializingController;
+//import com.jd.blockchain.peer.web.LedgerInitializingHttpService;
+//import com.jd.blockchain.storage.service.impl.redis.RedisStorageService;
+//
+//import my.utils.io.ByteArray;
+//import redis.clients.jedis.Jedis;
+//
+//@Ignore
+//@RunWith(SpringJUnit4ClassRunner.class)
+//@SpringBootTest(classes = { ControllerTestConfiguration.class})
+//@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+//public class LedgerInitializingTest {
+//
+// @Autowired
+// private PeerKeyStorageService keyStorageService;
+//
+// @BeforeClass
+// public static void setUpBeforeClass() throws Exception {
+// }
+//
+// @AfterClass
+// public static void tearDownAfterClass() throws Exception {
+// }
+//
+// @Before
+// public void setup() {
+// }
+//
+// @After
+// public void after() {
+// }
+//
+// @Test
+// public void testStartNewLedger() {
+// // 准备上下文;
+// ServerContext cordinator = new ServerContext("cordinator", 0, 9000, keyStorageService);
+//
+// ServerContext participant1 = new ServerContext("participant1", 1, 9001, keyStorageService);
+// participant1.setLedgerInitHttpServiceProxy(cordinator.getController());
+//
+// ServerContext participant2 = new ServerContext("participant2", 2, 9002, keyStorageService);
+// participant2.setLedgerInitHttpServiceProxy(cordinator.getController());
+//
+// ServerContext participant3 = new ServerContext("participant3", 3, 9003, keyStorageService);
+// participant3.setLedgerInitHttpServiceProxy(cordinator.getController());
+//
+// // 协调节点开始新建账本;
+// LedgerInitializationContext ctx = cordinator.controller.startNewLedger(cordinator.keyInfo.getName(),
+// cordinator.keyInfo.getIdentity().getAddress());
+// String defId = ctx.getLedgerDefinition().getDefinitionId();
+//
+// // 参与者加入账本;
+// participant1.controller.startJoiningLedger(defId, "localhost", 9000, participant1.keyInfo.getName(),
+// participant1.keyInfo.getIdentity().getAddress());
+// participant2.controller.startJoiningLedger(defId, "localhost", 9000, participant2.keyInfo.getName(),
+// participant2.keyInfo.getIdentity().getAddress());
+// participant3.controller.startJoiningLedger(defId, "localhost", 9000, participant3.keyInfo.getName(),
+// participant3.keyInfo.getIdentity().getAddress());
+//
+// // TODO:断言协调节点已经收到了参与者的请求;
+//
+//
+// // 协调节点签署账本;
+// cordinator.controller.prepareAndSign();
+//
+// // 等待各个参与节点完成签署和生成块;
+// try {
+// Thread.sleep(5000);
+// } catch (InterruptedException e) {
+// // Swallow InterruptedException;
+// }
+//
+// LedgerInitializationContext cordCtx = cordinator.controller.getLedgerInitContext();
+// LedgerInitializationContext part1Ctx = participant1.controller.getLedgerInitContext();
+// LedgerInitializationContext part2Ctx = participant2.controller.getLedgerInitContext();
+// LedgerInitializationContext part3Ctx = participant3.controller.getLedgerInitContext();
+//
+// // 断言各个参与节点都达到了块一致的状态;
+// //ssertTrue(cordCtx.isConsistent());
+//
+// // 等待各个参与节点完成签署和生成块;
+// try {
+// Thread.sleep(5000);
+// } catch (InterruptedException e) {
+// // Swallow InterruptedException;
+// }
+// //assertTrue(part1Ctx.isConsistent());
+// //assertTrue(part2Ctx.isConsistent());
+// //assertTrue(part3Ctx.isConsistent());
+//
+// // 断言各个参与节点的块都是真正地一致;
+// //assertEquals(cordCtx.getLedger().getLedgerHash(), part1Ctx.getLedger().getLedgerHash());
+// //assertEquals(cordCtx.getLedger().getLedgerHash(), part2Ctx.getLedger().getLedgerHash());
+// //assertEquals(cordCtx.getLedger().getLedgerHash(), part3Ctx.getLedger().getLedgerHash());
+//
+// // 协调节点提交;
+// cordinator.controller.commitLedger();
+//
+// // 等待各个参与节点完成提交;
+// try {
+// Thread.sleep(5000);
+// } catch (InterruptedException e) {
+// // Swallow InterruptedException;
+// }
+//
+// // 断言各个参与节点的状态都被重置了;
+// cordCtx = cordinator.controller.getLedgerInitContext();
+// part1Ctx = participant1.controller.getLedgerInitContext();
+// part2Ctx = participant2.controller.getLedgerInitContext();
+// part3Ctx = participant3.controller.getLedgerInitContext();
+//
+// //assertFalse(cordCtx.isJoined());
+// //assertFalse(part1Ctx.isJoined());
+// //assertFalse(part2Ctx.isJoined());
+// //assertFalse(part3Ctx.isJoined());
+//
+// //assertNull(cordCtx.getLedgerDefinition());
+// //assertNull(part1Ctx.getLedgerDefinition());
+// //assertNull(part2Ctx.getLedgerDefinition());
+// //assertNull(part3Ctx.getLedgerDefinition());
+// }
+//
+// public static class ServerContext {
+//
+// private PeerKeyStorageService keystoreService;
+//
+// private LedgerService ledgerService;
+//
+// private PeerSettings peerSettings;
+//
+// private MessageBroadcaster msgBroadcaster; // 用于向客户端进行消息通知;
+//
+// private LedgerInitializingController controller;
+//
+// //private final BlockchainKeyPair key;
+//
+// private final BlockchainIdentity identity;
+//
+// private final BlockchainKeyInfo keyInfo;
+//
+// private LedgerInitializingHttpService ledgerInitHttpServiceProxy;
+//
+// public ServerContext(String name, int idx, int port, PeerKeyStorageService keystoreService) {
+// Jedis jedis = new Jedis("192.168.151.33", 6379);
+// jedis.select(idx);
+// jedis.connect();
+//
+// this.ledgerService = new LedgerServiceImpl(new RedisStorageService(jedis));
+// this.peerSettings = peerSetting(port);
+// this.keystoreService = keystoreService;
+//
+// this.keyInfo = this.keystoreService.generateNewKey(name);
+// this.identity = this.keyInfo.getIdentity();
+//
+// //this.key = BlockchainKeyGenerator.getInstance().generate(KeyType.ED25519);
+// //this.keyInfo = new BlockchainKeyInfo();
+// //this.keyInfo.setName(name);
+// //this.keyInfo.setIdentity(key.getIdentity());
+//
+// initTestContext();
+// }
+//
+//
+// private PeerSettings peerSetting(int port) {
+// PeerSettings setting = new PeerSettings();
+// PeerSettings.ConsensusSetting consensusSetting = new PeerSettings.ConsensusSetting();
+// consensusSetting.setIp("127.0.0.1");
+// consensusSetting.setPort(port);
+// setting.setConsensus(consensusSetting);
+//
+// return setting;
+// }
+//
+//
+// private void initTestContext() {
+// //keystoreService = spy(PeerKeyStorageServiceImpl.class);
+// //when(keystoreService.getBlockchainKey(key.getAddress())).thenReturn(keyInfo);
+// //when(keystoreService.sign(any(), key.getAddress())).then(answerSignature(key));
+//
+// msgBroadcaster = mocker(MessageBroadcaster.class);
+//
+// LedgerInitializingController ctrl = new LedgerInitializingController(peerSettings, keystoreService,
+// ledgerService, msgBroadcaster);
+// this.controller = spy(ctrl);
+//
+// when(controller.getLedgerInitHttpService(any(), anyInt())).then(new Answer() {
+// @Override
+// public LedgerInitializingHttpService answer(InvocationOnMock invocationOnMock) throws Throwable {
+// return ledgerInitHttpServiceProxy;
+// }
+// });
+// }
+//
+// private Answer answerSignature(BlockchainKeyPair keyPair) {
+// return new Answer() {
+// @Override
+// public DigitalSignature answer(InvocationOnMock invocation) throws Throwable {
+// Object[] args = invocation.getArguments();
+// ByteArray data = (ByteArray) args[0];
+// return SignatureUtils.sign(data, keyPair);
+// }
+// };
+// }
+//
+// public LedgerInitializingController getController() {
+// return controller;
+// }
+//
+// public LedgerInitializingHttpService getLedgerInitHttpServiceProxy() {
+// return ledgerInitHttpServiceProxy;
+// }
+//
+// public void setLedgerInitHttpServiceProxy(LedgerInitializingHttpService ledgerInitHttpServiceProxy) {
+// this.ledgerInitHttpServiceProxy = ledgerInitHttpServiceProxy;
+// }
+//
+// }
+//}
diff --git a/source/peer/src/test/java/test/com/jd/blockchain/peer/web/PeerKeyStorageServiceImpl.java b/source/peer/src/test/java/test/com/jd/blockchain/peer/web/PeerKeyStorageServiceImpl.java
index 5491b2f5..02c54d8a 100644
--- a/source/peer/src/test/java/test/com/jd/blockchain/peer/web/PeerKeyStorageServiceImpl.java
+++ b/source/peer/src/test/java/test/com/jd/blockchain/peer/web/PeerKeyStorageServiceImpl.java
@@ -1,140 +1,140 @@
-//package test.com.jd.blockchain.peer.web;
-//
-//import java.util.Arrays;
-//import java.util.Comparator;
-//import java.util.Map;
-//import java.util.concurrent.ConcurrentHashMap;
-//
-//import javax.annotation.PostConstruct;
-//
-//import com.jd.blockchain.crypto.CryptoAlgorithm;
-//import com.jd.blockchain.crypto.asymmetric.PrivKey;
-//import com.jd.blockchain.crypto.asymmetric.PubKey;
-//import org.springframework.beans.factory.annotation.Autowired;
-//import org.springframework.stereotype.Service;
-//
-//import com.jd.blockchain.ledger.BlockchainIdentity;
-//import com.jd.blockchain.ledger.BlockchainKeyGenerator;
-//import com.jd.blockchain.ledger.BlockchainKeyPair;
-//import com.jd.blockchain.ledger.DigitalSignature;
-//import com.jd.blockchain.ledger.data.CryptoKeyEncoding;
-//import com.jd.blockchain.ledger.data.SignatureUtils;
-//import com.jd.blockchain.peer.PeerSettings;
-//import com.jd.blockchain.peer.service.BlockchainKeyInfo;
-//import com.jd.blockchain.peer.service.PeerKeyStorageService;
-//
-//import my.utils.io.ByteArray;
-//
-//@Service
-//public class PeerKeyStorageServiceImpl implements PeerKeyStorageService {
-//
-// @Autowired
-// private PeerSettings settings;
-//
-// public static BlockchainKeyPair keyOfP1 = BlockchainKeyGenerator.getInstance().generate();
-// public static BlockchainKeyPair keyOfP2 = BlockchainKeyGenerator.getInstance().generate();
-//
-// private Map keyStores = new ConcurrentHashMap<>();
-//
-// private static String[] encodeToStringLines(BlockchainKeyStore keyStore) {
-// return new String[] { keyStore.getKeyInfo().getName(), keyStore.getKeyPair().getAddress(),
-// keyStore.getKeyPair().getPubKey().toString(), keyStore.getKeyPair().getPrivKey().toString() };
-// }
-//
-// private static BlockchainKeyStore decodeFromStringLines(String[] lines) {
-// String name = lines[0];
-// String address = lines[1];
-// PubKey pubKey = (PubKey) CryptoKeyEncoding.fromBase58(lines[2]);
-// PrivKey privKey = (PrivKey) CryptoKeyEncoding.fromBase58(lines[3]);
-// return new BlockchainKeyStore(name, address, pubKey, privKey);
-// }
-//
-// @PostConstruct
-// private void init() {
-// keyStores.put(keyOfP1.getAddress(), new BlockchainKeyStore("a", keyOfP1));
-// keyStores.put(keyOfP1.getAddress(), new BlockchainKeyStore("b", keyOfP1));
-// }
-//
-// @Override
-// public BlockchainKeyInfo generateNewKey(String name) {
-// BlockchainKeyPair keypair = BlockchainKeyGenerator.getInstance().generate(CryptoAlgorithm.ED25519);
-// BlockchainKeyStore keystore = new BlockchainKeyStore(name, keypair);
-//
-// keyStores.put(keypair.getAddress(), keystore);
-// return keystore.getKeyInfo();
-// }
-//
-// @Override
-// public DigitalSignature sign(ByteArray data, String address) {
-// BlockchainKeyStore keystore = keyStores.get(address);
-// if (keystore == null) {
-// throw new IllegalArgumentException("Key not exist!");
-// }
-// return SignatureUtils.sign(data, keystore.getKeyPair());
-// }
-//
-// @Override
-// public DigitalSignature sign(byte[] data, String address) {
-// BlockchainKeyStore keystore = keyStores.get(address);
-// if (keystore == null) {
-// throw new IllegalArgumentException("Key not exist!");
-// }
-// return SignatureUtils.sign(data, keystore.getKeyPair());
-// }
-//
-// @Override
-// public BlockchainKeyInfo getBlockchainKey(String address) {
-// BlockchainKeyStore keystore = keyStores.get(address);
-// if (keystore == null) {
-// throw new IllegalArgumentException("Key not exist!");
-// }
-// return keystore.getKeyInfo();
-// }
-//
-// @Override
-// public BlockchainKeyInfo[] getBlockchainKeys() {
-// BlockchainKeyInfo[] keys = new BlockchainKeyInfo[keyStores.size()];
-// int i = 0;
-// for (BlockchainKeyStore keystore : keyStores.values()) {
-// keys[i] = keystore.getKeyInfo();
-// i++;
-// }
-// Arrays.sort(keys, new Comparator() {
-// @Override
-// public int compare(BlockchainKeyInfo o1, BlockchainKeyInfo o2) {
-// return o1.getName().compareTo(o2.getName());
-// }
-// });
-// return keys;
-// }
-//
-// private static class BlockchainKeyStore {
-// private BlockchainKeyInfo keyInfo;
-//
-// private BlockchainKeyPair keyPair;
-//
-// public BlockchainKeyStore(String name, String address, PubKey pubKey, PrivKey privKey) {
-// keyInfo = new BlockchainKeyInfo();
-// keyInfo.setName(name);
-// keyInfo.setIdentity(new BlockchainIdentity(address, pubKey));
-// keyPair = new BlockchainKeyPair(address, pubKey, privKey);
-// }
-//
-// public BlockchainKeyStore(String name, BlockchainKeyPair keypair) {
-// keyInfo = new BlockchainKeyInfo();
-// keyInfo.setName(name);
-// keyInfo.setIdentity(keypair.getIdentity());
-// this.keyPair = keypair;
-// }
-//
-// public BlockchainKeyInfo getKeyInfo() {
-// return keyInfo;
-// }
-//
-// public BlockchainKeyPair getKeyPair() {
-// return keyPair;
-// }
-//
-// }
-//
-//}
+//package test.com.jd.blockchain.peer.web;
+//
+//import java.util.Arrays;
+//import java.util.Comparator;
+//import java.util.Map;
+//import java.util.concurrent.ConcurrentHashMap;
+//
+//import javax.annotation.PostConstruct;
+//
+//import com.jd.blockchain.crypto.CryptoAlgorithm;
+//import com.jd.blockchain.crypto.asymmetric.PrivKey;
+//import com.jd.blockchain.crypto.asymmetric.PubKey;
+//import org.springframework.beans.factory.annotation.Autowired;
+//import org.springframework.stereotype.Service;
+//
+//import com.jd.blockchain.ledger.BlockchainIdentity;
+//import com.jd.blockchain.ledger.BlockchainKeyGenerator;
+//import com.jd.blockchain.ledger.BlockchainKeyPair;
+//import com.jd.blockchain.ledger.DigitalSignature;
+//import com.jd.blockchain.ledger.data.CryptoKeyEncoding;
+//import com.jd.blockchain.ledger.data.SignatureUtils;
+//import com.jd.blockchain.peer.PeerSettings;
+//import com.jd.blockchain.peer.service.BlockchainKeyInfo;
+//import com.jd.blockchain.peer.service.PeerKeyStorageService;
+//
+//import my.utils.io.ByteArray;
+//
+//@Service
+//public class PeerKeyStorageServiceImpl implements PeerKeyStorageService {
+//
+// @Autowired
+// private PeerSettings settings;
+//
+// public static BlockchainKeyPair keyOfP1 = BlockchainKeyGenerator.getInstance().generate();
+// public static BlockchainKeyPair keyOfP2 = BlockchainKeyGenerator.getInstance().generate();
+//
+// private Map keyStores = new ConcurrentHashMap<>();
+//
+// private static String[] encodeToStringLines(BlockchainKeyStore keyStore) {
+// return new String[] { keyStore.getKeyInfo().getName(), keyStore.getKeyPair().getAddress(),
+// keyStore.getKeyPair().getPubKey().toString(), keyStore.getKeyPair().getPrivKey().toString() };
+// }
+//
+// private static BlockchainKeyStore decodeFromStringLines(String[] lines) {
+// String name = lines[0];
+// String address = lines[1];
+// PubKey pubKey = (PubKey) CryptoKeyEncoding.fromBase58(lines[2]);
+// PrivKey privKey = (PrivKey) CryptoKeyEncoding.fromBase58(lines[3]);
+// return new BlockchainKeyStore(name, address, pubKey, privKey);
+// }
+//
+// @PostConstruct
+// private void init() {
+// keyStores.put(keyOfP1.getAddress(), new BlockchainKeyStore("a", keyOfP1));
+// keyStores.put(keyOfP1.getAddress(), new BlockchainKeyStore("b", keyOfP1));
+// }
+//
+// @Override
+// public BlockchainKeyInfo generateNewKey(String name) {
+// BlockchainKeyPair keypair = BlockchainKeyGenerator.getInstance().generate(CryptoAlgorithm.ED25519);
+// BlockchainKeyStore keystore = new BlockchainKeyStore(name, keypair);
+//
+// keyStores.put(keypair.getAddress(), keystore);
+// return keystore.getKeyInfo();
+// }
+//
+// @Override
+// public DigitalSignature sign(ByteArray data, String address) {
+// BlockchainKeyStore keystore = keyStores.get(address);
+// if (keystore == null) {
+// throw new IllegalArgumentException("Key not exist!");
+// }
+// return SignatureUtils.sign(data, keystore.getKeyPair());
+// }
+//
+// @Override
+// public DigitalSignature sign(byte[] data, String address) {
+// BlockchainKeyStore keystore = keyStores.get(address);
+// if (keystore == null) {
+// throw new IllegalArgumentException("Key not exist!");
+// }
+// return SignatureUtils.sign(data, keystore.getKeyPair());
+// }
+//
+// @Override
+// public BlockchainKeyInfo getBlockchainKey(String address) {
+// BlockchainKeyStore keystore = keyStores.get(address);
+// if (keystore == null) {
+// throw new IllegalArgumentException("Key not exist!");
+// }
+// return keystore.getKeyInfo();
+// }
+//
+// @Override
+// public BlockchainKeyInfo[] getBlockchainKeys() {
+// BlockchainKeyInfo[] keys = new BlockchainKeyInfo[keyStores.size()];
+// int i = 0;
+// for (BlockchainKeyStore keystore : keyStores.values()) {
+// keys[i] = keystore.getKeyInfo();
+// i++;
+// }
+// Arrays.sort(keys, new Comparator() {
+// @Override
+// public int compare(BlockchainKeyInfo o1, BlockchainKeyInfo o2) {
+// return o1.getName().compareTo(o2.getName());
+// }
+// });
+// return keys;
+// }
+//
+// private static class BlockchainKeyStore {
+// private BlockchainKeyInfo keyInfo;
+//
+// private BlockchainKeyPair keyPair;
+//
+// public BlockchainKeyStore(String name, String address, PubKey pubKey, PrivKey privKey) {
+// keyInfo = new BlockchainKeyInfo();
+// keyInfo.setName(name);
+// keyInfo.setIdentity(new BlockchainIdentity(address, pubKey));
+// keyPair = new BlockchainKeyPair(address, pubKey, privKey);
+// }
+//
+// public BlockchainKeyStore(String name, BlockchainKeyPair keypair) {
+// keyInfo = new BlockchainKeyInfo();
+// keyInfo.setName(name);
+// keyInfo.setIdentity(keypair.getIdentity());
+// this.keyPair = keypair;
+// }
+//
+// public BlockchainKeyInfo getKeyInfo() {
+// return keyInfo;
+// }
+//
+// public BlockchainKeyPair getKeyPair() {
+// return keyPair;
+// }
+//
+// }
+//
+//}
diff --git a/source/sdk/pom.xml b/source/sdk/pom.xml
index c4037224..fb570108 100644
--- a/source/sdk/pom.xml
+++ b/source/sdk/pom.xml
@@ -1,20 +1,20 @@
-
- 4.0.0
-
- com.jd.blockchain
- jdchain-root
- 1.1.2.RELEASE
-
- sdk
- pom
-
-
- sdk-base
-
- sdk-client
- sdk-samples
-
-
-
+
+ 4.0.0
+
+ com.jd.blockchain
+ jdchain-root
+ 1.1.2.RELEASE
+
+ sdk
+ pom
+
+
+ sdk-base
+
+ sdk-client
+ sdk-samples
+
+
+
\ No newline at end of file
diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/AbstractBlockchainServiceFactory.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/AbstractBlockchainServiceFactory.java
index e7293cc6..37125469 100644
--- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/AbstractBlockchainServiceFactory.java
+++ b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/AbstractBlockchainServiceFactory.java
@@ -1,51 +1,51 @@
-//package com.jd.blockchain.sdk;
-//
-//import java.io.Closeable;
-//
-//import com.jd.blockchain.ledger.CryptoSetting;
-//import com.jd.blockchain.ledger.data.TransactionService;
-//import com.jd.blockchain.sdk.proxy.BlockchainServiceProxy;
-//
-///**
-// *
-// * @author huanghaiquan
-// *
-// */
-//public abstract class AbstractBlockchainServiceFactory implements Closeable {
-//
-// private final Object mutex = new Object();
-//
-// private volatile BlockchainService blockchainService;
-//
-//// protected ServiceSetting setting;
-//
-// private CryptoSetting cryptoSetting;
-//
-// public AbstractBlockchainServiceFactory() {
-// }
-//
-// public BlockchainService getBlockchainService() {
-// if (blockchainService == null) {
-// synchronized (mutex) {
-// if (blockchainService == null) {
-// BlockchainQueryService queryService = getQueryService(setting);
-// TransactionService consensusService = getConsensusService(setting);
-// blockchainService = createBlockchainService(setting, consensusService, queryService);
-// }
-// }
-// }
-// return blockchainService;
-// }
-//
-// protected BlockchainService createBlockchainService(ServiceSetting setting, TransactionService consensusService, BlockchainQueryService queryService) {
-// return new BlockchainServiceProxy(consensusService, queryService);
-// }
-//
-// protected abstract BlockchainQueryService getQueryService(ServiceSetting setting);
-//
-// protected abstract TransactionService getConsensusService(ServiceSetting setting);
-//
-// @Override
-// public abstract void close();
-//
-//}
+//package com.jd.blockchain.sdk;
+//
+//import java.io.Closeable;
+//
+//import com.jd.blockchain.ledger.CryptoSetting;
+//import com.jd.blockchain.ledger.data.TransactionService;
+//import com.jd.blockchain.sdk.proxy.BlockchainServiceProxy;
+//
+///**
+// *
+// * @author huanghaiquan
+// *
+// */
+//public abstract class AbstractBlockchainServiceFactory implements Closeable {
+//
+// private final Object mutex = new Object();
+//
+// private volatile BlockchainService blockchainService;
+//
+//// protected ServiceSetting setting;
+//
+// private CryptoSetting cryptoSetting;
+//
+// public AbstractBlockchainServiceFactory() {
+// }
+//
+// public BlockchainService getBlockchainService() {
+// if (blockchainService == null) {
+// synchronized (mutex) {
+// if (blockchainService == null) {
+// BlockchainQueryService queryService = getQueryService(setting);
+// TransactionService consensusService = getConsensusService(setting);
+// blockchainService = createBlockchainService(setting, consensusService, queryService);
+// }
+// }
+// }
+// return blockchainService;
+// }
+//
+// protected BlockchainService createBlockchainService(ServiceSetting setting, TransactionService consensusService, BlockchainQueryService queryService) {
+// return new BlockchainServiceProxy(consensusService, queryService);
+// }
+//
+// protected abstract BlockchainQueryService getQueryService(ServiceSetting setting);
+//
+// protected abstract TransactionService getConsensusService(ServiceSetting setting);
+//
+// @Override
+// public abstract void close();
+//
+//}
diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainEventHandle.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainEventHandle.java
index 383a72c4..e1af4b42 100644
--- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainEventHandle.java
+++ b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainEventHandle.java
@@ -1,45 +1,45 @@
-package com.jd.blockchain.sdk;
-
-/**
- * BlockchainEventHandle 维护了一个具体的事件监听实例的状态,提供了在不需要继续监听时进行取消的方法
- * {@link #cancel()};
- *
- * @author huanghaiquan
- *
- */
-public interface BlockchainEventHandle {
-
- /**
- * 要监听的事件类型;
- *
- * @return
- */
- int getFilteredEventTypes();
-
- /**
- * 要监听的交易;如果为 null,则不进行交易过滤;
- *
- * @return
- */
- String getFilteredTxHash();
-
- /**
- * 要监听的账户地址;如果为 null,这不进行账户地址过滤;
- *
- * @return
- */
- String getFilteredAccountAddress();
-
- /**
- * 监听器实例;
- *
- * @return
- */
- BlockchainEventListener getListener();
-
- /**
- * 取消监听;
- */
- void cancel();
-
-}
+package com.jd.blockchain.sdk;
+
+/**
+ * BlockchainEventHandle 维护了一个具体的事件监听实例的状态,提供了在不需要继续监听时进行取消的方法
+ * {@link #cancel()};
+ *
+ * @author huanghaiquan
+ *
+ */
+public interface BlockchainEventHandle {
+
+ /**
+ * 要监听的事件类型;
+ *
+ * @return
+ */
+ int getFilteredEventTypes();
+
+ /**
+ * 要监听的交易;如果为 null,则不进行交易过滤;
+ *
+ * @return
+ */
+ String getFilteredTxHash();
+
+ /**
+ * 要监听的账户地址;如果为 null,这不进行账户地址过滤;
+ *
+ * @return
+ */
+ String getFilteredAccountAddress();
+
+ /**
+ * 监听器实例;
+ *
+ * @return
+ */
+ BlockchainEventListener getListener();
+
+ /**
+ * 取消监听;
+ */
+ void cancel();
+
+}
diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainEventListener.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainEventListener.java
index 6b87a9cf..9afe806c 100644
--- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainEventListener.java
+++ b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainEventListener.java
@@ -1,7 +1,7 @@
-package com.jd.blockchain.sdk;
-
-public interface BlockchainEventListener {
-
- public void onEvent(BlockchainEventMessage eventMessage, BlockchainEventHandle eventHandle);
-
-}
+package com.jd.blockchain.sdk;
+
+public interface BlockchainEventListener {
+
+ public void onEvent(BlockchainEventMessage eventMessage, BlockchainEventHandle eventHandle);
+
+}
diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainEventMessage.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainEventMessage.java
index 8a1a442d..ec2067ec 100644
--- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainEventMessage.java
+++ b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainEventMessage.java
@@ -1,45 +1,45 @@
-package com.jd.blockchain.sdk;
-
-import java.util.BitSet;
-
-import com.jd.blockchain.ledger.BlockchainEventType;
-
-public interface BlockchainEventMessage {
-
- /**
- * 事件代码;
- *
- * 事件代码是本次事件的所有类型事件码的按位或的结果;
- *
- * 可以按以下方法检查是否包含某个特定事件:
- *
- *
- * ({@link BlockchainEventType#PAYLOAD_UPDATED} & {@link #getEventCode()}) == {@link BlockchainEventType#PAYLOAD_UPDATED}
- *
- *
- * @return
- */
- int getEventCode();
-
- /**
- * 区块高度;
- *
- * @return
- */
- long getLedgerNumber();
-
- /**
- * 包含本次事件中的所有成功交易的布隆过滤器(BloomFilter)的值;
- *
- * @return
- */
- BitSet getBloomFilterOfTxs();
-
- /**
- * 包含本次事件中的所有变更账户的布隆过滤器(BloomFilter)的值;
- *
- * @return
- */
- BitSet getBloomFilterOfAccounts();
-
-}
+package com.jd.blockchain.sdk;
+
+import java.util.BitSet;
+
+import com.jd.blockchain.ledger.BlockchainEventType;
+
+public interface BlockchainEventMessage {
+
+ /**
+ * 事件代码;
+ *
+ * 事件代码是本次事件的所有类型事件码的按位或的结果;
+ *
+ * 可以按以下方法检查是否包含某个特定事件:
+ *
+ *
+ * ({@link BlockchainEventType#PAYLOAD_UPDATED} & {@link #getEventCode()}) == {@link BlockchainEventType#PAYLOAD_UPDATED}
+ *
+ *
+ * @return
+ */
+ int getEventCode();
+
+ /**
+ * 区块高度;
+ *
+ * @return
+ */
+ long getLedgerNumber();
+
+ /**
+ * 包含本次事件中的所有成功交易的布隆过滤器(BloomFilter)的值;
+ *
+ * @return
+ */
+ BitSet getBloomFilterOfTxs();
+
+ /**
+ * 包含本次事件中的所有变更账户的布隆过滤器(BloomFilter)的值;
+ *
+ * @return
+ */
+ BitSet getBloomFilterOfAccounts();
+
+}
diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainEventService.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainEventService.java
index 34f47d38..04341813 100644
--- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainEventService.java
+++ b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainEventService.java
@@ -1,20 +1,20 @@
-package com.jd.blockchain.sdk;
-
-public interface BlockchainEventService {
-
- /**
- * 注册区块链事件监听器;
- *
- * @param filteredEventTypes
- * 要监听的事件类型;
- * @param filteredTxHash
- * 要监听的交易;如果为 null,则不进行交易过滤;
- * @param filteredAccountAddress
- * 要监听的账户地址;如果为 null,这不进行账户地址过滤;
- * @param listener
- * 监听器实例;
- */
- BlockchainEventHandle addBlockchainEventListener(int filteredEventTypes, String filteredTxHash,
- String filteredAccountAddress, BlockchainEventListener listener);
-
+package com.jd.blockchain.sdk;
+
+public interface BlockchainEventService {
+
+ /**
+ * 注册区块链事件监听器;
+ *
+ * @param filteredEventTypes
+ * 要监听的事件类型;
+ * @param filteredTxHash
+ * 要监听的交易;如果为 null,则不进行交易过滤;
+ * @param filteredAccountAddress
+ * 要监听的账户地址;如果为 null,这不进行账户地址过滤;
+ * @param listener
+ * 监听器实例;
+ */
+ BlockchainEventHandle addBlockchainEventListener(int filteredEventTypes, String filteredTxHash,
+ String filteredAccountAddress, BlockchainEventListener listener);
+
}
\ No newline at end of file
diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainService.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainService.java
index e24f8a80..d9d57cfd 100644
--- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainService.java
+++ b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainService.java
@@ -1,16 +1,16 @@
-package com.jd.blockchain.sdk;
-
-import com.jd.blockchain.transaction.BlockchainQueryService;
-
-/**
- * 区块链服务;
- *
- *
- * 这是一个门面服务(facade);
- *
- * @author huanghaiquan
- *
- */
-public interface BlockchainService extends BlockchainQueryService, BlockchainTransactionService, BlockchainEventService {
-
-}
+package com.jd.blockchain.sdk;
+
+import com.jd.blockchain.transaction.BlockchainQueryService;
+
+/**
+ * 区块链服务;
+ *
+ *
+ * 这是一个门面服务(facade);
+ *
+ * @author huanghaiquan
+ *
+ */
+public interface BlockchainService extends BlockchainQueryService, BlockchainTransactionService, BlockchainEventService {
+
+}
diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainTransactionService.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainTransactionService.java
index f30dee7c..eff792a3 100644
--- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainTransactionService.java
+++ b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/BlockchainTransactionService.java
@@ -1,26 +1,26 @@
-package com.jd.blockchain.sdk;
-
-import com.jd.blockchain.crypto.HashDigest;
-import com.jd.blockchain.ledger.TransactionTemplate;
-
-public interface BlockchainTransactionService {
-
- /**
- * 发起新交易;
- *
- * @return
- */
- TransactionTemplate newTransaction(HashDigest ledgerHash);
-
-// /**
-// * 以指定的科目和流水号发起新交易;
-// *
-// * @param subjectAccount
-// * 交易的科目账户地址;
-// * @param sequenceNumber
-// * 交易的流水号;
-// * @return
-// */
-// TransactionTemplate newTransaction(ByteArray ledgerHash, String subjectAccount, long sequenceNumber);
-
+package com.jd.blockchain.sdk;
+
+import com.jd.blockchain.crypto.HashDigest;
+import com.jd.blockchain.ledger.TransactionTemplate;
+
+public interface BlockchainTransactionService {
+
+ /**
+ * 发起新交易;
+ *
+ * @return
+ */
+ TransactionTemplate newTransaction(HashDigest ledgerHash);
+
+// /**
+// * 以指定的科目和流水号发起新交易;
+// *
+// * @param subjectAccount
+// * 交易的科目账户地址;
+// * @param sequenceNumber
+// * 交易的流水号;
+// * @return
+// */
+// TransactionTemplate newTransaction(ByteArray ledgerHash, String subjectAccount, long sequenceNumber);
+
}
\ No newline at end of file
diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/ManagementHttpService.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/ManagementHttpService.java
index f4bd68be..a2e12891 100644
--- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/ManagementHttpService.java
+++ b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/ManagementHttpService.java
@@ -1,20 +1,20 @@
-package com.jd.blockchain.sdk;
-
-import com.jd.blockchain.consensus.ClientIdentifications;
-import com.jd.blockchain.sdk.converters.BinarySerializeRequestConverter;
-import com.jd.blockchain.sdk.converters.BinarySerializeResponseConverter;
-import com.jd.blockchain.setting.GatewayIncomingSetting;
-import com.jd.blockchain.utils.http.HttpAction;
-import com.jd.blockchain.utils.http.HttpMethod;
-import com.jd.blockchain.utils.http.HttpService;
-import com.jd.blockchain.utils.http.RequestBody;
-import com.jd.blockchain.utils.web.client.WebResponseConverterFactory;
-
-
-@HttpService(path="/management", defaultRequestBodyConverter = BinarySerializeRequestConverter.class, responseConverterFactory=WebResponseConverterFactory.class)
-public interface ManagementHttpService {
-
- @HttpAction(method=HttpMethod.POST, path="/gateway/auth", contentType = BinarySerializeRequestConverter.CONTENT_TYPE_VALUE)
- public GatewayIncomingSetting authenticateGateway(@RequestBody ClientIdentifications clientIdentifications) ;
-
-}
+package com.jd.blockchain.sdk;
+
+import com.jd.blockchain.consensus.ClientIdentifications;
+import com.jd.blockchain.sdk.converters.BinarySerializeRequestConverter;
+import com.jd.blockchain.sdk.converters.BinarySerializeResponseConverter;
+import com.jd.blockchain.setting.GatewayIncomingSetting;
+import com.jd.blockchain.utils.http.HttpAction;
+import com.jd.blockchain.utils.http.HttpMethod;
+import com.jd.blockchain.utils.http.HttpService;
+import com.jd.blockchain.utils.http.RequestBody;
+import com.jd.blockchain.utils.web.client.WebResponseConverterFactory;
+
+
+@HttpService(path="/management", defaultRequestBodyConverter = BinarySerializeRequestConverter.class, responseConverterFactory=WebResponseConverterFactory.class)
+public interface ManagementHttpService {
+
+ @HttpAction(method=HttpMethod.POST, path="/gateway/auth", contentType = BinarySerializeRequestConverter.CONTENT_TYPE_VALUE)
+ public GatewayIncomingSetting authenticateGateway(@RequestBody ClientIdentifications clientIdentifications) ;
+
+}
diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/PrivilegeSetting.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/PrivilegeSetting.java
index deafc113..a1f1f05f 100644
--- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/PrivilegeSetting.java
+++ b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/PrivilegeSetting.java
@@ -1,21 +1,21 @@
-package com.jd.blockchain.sdk;
-
-import com.jd.blockchain.ledger.PermissionType;
-
-/**
- * 权限设置;
- *
- *
- *
- * @author huanghaiquan
- *
- */
-public interface PrivilegeSetting {
-
- String[] getSigners();
-
- long getMask(String address);
-
- boolean isEnable(String address, PermissionType privilege);
-
-}
+package com.jd.blockchain.sdk;
+
+import com.jd.blockchain.ledger.PermissionType;
+
+/**
+ * 权限设置;
+ *
+ *
+ *
+ * @author huanghaiquan
+ *
+ */
+public interface PrivilegeSetting {
+
+ String[] getSigners();
+
+ long getMask(String address);
+
+ boolean isEnable(String address, PermissionType privilege);
+
+}
diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/TxCommiter.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/TxCommiter.java
index 94963e19..09d2de7b 100644
--- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/TxCommiter.java
+++ b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/TxCommiter.java
@@ -1,11 +1,11 @@
-//package com.jd.blockchain.sdk;
-//
-//import com.jd.blockchain.ledger.DigitalSignature;
-//import com.jd.blockchain.ledger.TransactionContent;
-//import com.jd.blockchain.ledger.TransactionResponse;
-//
-//public interface TxCommiter {
-//
-// public TransactionResponse commitTx(TransactionContent txContent, DigitalSignature[] signatures);
-//
-//}
+//package com.jd.blockchain.sdk;
+//
+//import com.jd.blockchain.ledger.DigitalSignature;
+//import com.jd.blockchain.ledger.TransactionContent;
+//import com.jd.blockchain.ledger.TransactionResponse;
+//
+//public interface TxCommiter {
+//
+// public TransactionResponse commitTx(TransactionContent txContent, DigitalSignature[] signatures);
+//
+//}
diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/proxy/CodeDeployOperationBuilder.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/proxy/CodeDeployOperationBuilder.java
index 7a524131..6e73b08b 100644
--- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/proxy/CodeDeployOperationBuilder.java
+++ b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/proxy/CodeDeployOperationBuilder.java
@@ -1,74 +1,74 @@
-//package com.jd.blockchain.sdk.proxy;
-//
-//import com.jd.blockchain.ledger.*;
-//import com.jd.blockchain.ledger.data.BlockchainOperationFactory;
-//import com.jd.blockchain.ledger.data.OpBlob;
-//import com.jd.blockchain.ledger.data.PrivilegeSettingOperationBuilder;
-//import my.utils.io.ByteArray;
-//
-//public class CodeDeployOperationBuilder implements CodeDeployOperation {
-//
-// private TxTemplate txTemp;
-//
-// public CodeDeployOperationBuilder(TxTemplate txTemp) {
-// this.txTemp = txTemp;
-// }
-//
-// /**
-// * 修改脚本;
-// *
-// * @param id
-// * @param code 合约代码;
-// * @param codeVersion
-// */
-// @Override
-// public void set(BlockchainIdentity id, String code, long codeVersion) {
-// ContractDeployingOperation codeOperation = BlockchainOperationFactory.getInstance().deploy(id, ByteArray.wrap(code.getBytes()));
-//
-// txTemp.addOperation((OpBlob) codeOperation.getOperation());
-// }
-//
-// /**
-// * 配置特权操作;
-// *
-// * @param accountAddress 账户地址;
-// * @return
-// */
-// @Override
-// public PrivilegeSettingOperationBuilder configPrivilege(String accountAddress) {
-// return null;
-// }
-//
-// /**
-// * 执行针对负载类型 {@link AccountStateType}为 {@link AccountStateType#MAP} 的账户操作;
-// *
-// * @param accountAddress 要操作的账户地址;
-// * @return
-// */
-// @Override
-// public MapStateOperationBuilder updateState(String accountAddress) {
-// return null;
-// }
-//
-// /**
-// * 执行定义账户的合约脚本的操作;
-// *
-// * @param accountAddress 要操作的账户地址;
-// * @return
-// */
-// @Override
-// public CodeDeployOperation defineScript(String accountAddress) {
-// return null;
-// }
-//
-// /**
-// * 执行调用账户的合约脚本的方法的操作;
-// *
-// * @param accountAddress 要操作的账户地址;
-// * @return
-// */
-// @Override
-// public ScriptInvokingOperation executeScript(String accountAddress) {
-// return null;
-// }
-//}
+//package com.jd.blockchain.sdk.proxy;
+//
+//import com.jd.blockchain.ledger.*;
+//import com.jd.blockchain.ledger.data.BlockchainOperationFactory;
+//import com.jd.blockchain.ledger.data.OpBlob;
+//import com.jd.blockchain.ledger.data.PrivilegeSettingOperationBuilder;
+//import my.utils.io.ByteArray;
+//
+//public class CodeDeployOperationBuilder implements CodeDeployOperation {
+//
+// private TxTemplate txTemp;
+//
+// public CodeDeployOperationBuilder(TxTemplate txTemp) {
+// this.txTemp = txTemp;
+// }
+//
+// /**
+// * 修改脚本;
+// *
+// * @param id
+// * @param code 合约代码;
+// * @param codeVersion
+// */
+// @Override
+// public void set(BlockchainIdentity id, String code, long codeVersion) {
+// ContractDeployingOperation codeOperation = BlockchainOperationFactory.getInstance().deploy(id, ByteArray.wrap(code.getBytes()));
+//
+// txTemp.addOperation((OpBlob) codeOperation.getOperation());
+// }
+//
+// /**
+// * 配置特权操作;
+// *
+// * @param accountAddress 账户地址;
+// * @return
+// */
+// @Override
+// public PrivilegeSettingOperationBuilder configPrivilege(String accountAddress) {
+// return null;
+// }
+//
+// /**
+// * 执行针对负载类型 {@link AccountStateType}为 {@link AccountStateType#MAP} 的账户操作;
+// *
+// * @param accountAddress 要操作的账户地址;
+// * @return
+// */
+// @Override
+// public MapStateOperationBuilder updateState(String accountAddress) {
+// return null;
+// }
+//
+// /**
+// * 执行定义账户的合约脚本的操作;
+// *
+// * @param accountAddress 要操作的账户地址;
+// * @return
+// */
+// @Override
+// public CodeDeployOperation defineScript(String accountAddress) {
+// return null;
+// }
+//
+// /**
+// * 执行调用账户的合约脚本的方法的操作;
+// *
+// * @param accountAddress 要操作的账户地址;
+// * @return
+// */
+// @Override
+// public ScriptInvokingOperation executeScript(String accountAddress) {
+// return null;
+// }
+//}
diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/proxy/CodeInvokeOperationBuilder.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/proxy/CodeInvokeOperationBuilder.java
index 8e5958c7..a925fc15 100644
--- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/proxy/CodeInvokeOperationBuilder.java
+++ b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/proxy/CodeInvokeOperationBuilder.java
@@ -1,73 +1,73 @@
-//package com.jd.blockchain.sdk.proxy;
-//
-//import com.jd.blockchain.ledger.CodeDeployOperation;
-//import com.jd.blockchain.ledger.ContractEventOperation;
-//import com.jd.blockchain.ledger.MapStateOperationBuilder;
-//import com.jd.blockchain.ledger.ScriptInvokingOperation;
-//import com.jd.blockchain.ledger.data.BlockchainOperationFactory;
-//import com.jd.blockchain.ledger.data.OpBlob;
-//import com.jd.blockchain.ledger.data.PrivilegeSettingOperationBuilder;
-//
-//import my.utils.io.ByteArray;
-//
-//public class CodeInvokeOperationBuilder implements ScriptInvokingOperation {
-// private TxTemplate txTemp;
-//
-// public CodeInvokeOperationBuilder(TxTemplate txTemp) {
-// this.txTemp = txTemp;
-// }
-//
-// @Override
-// public void invoke(String address, String[] args) {
-// ContractEventOperation operation = BlockchainOperationFactory.getInstance().event(address, new ByteArray[] {});
-//
-// txTemp.addOperation((OpBlob) operation.getOperation());
-// }
-//
-// /**
-// * 配置特权操作;
-// *
-// * @param accountAddress
-// * 账户地址;
-// * @return
-// */
-// @Override
-// public PrivilegeSettingOperationBuilder configPrivilege(String accountAddress) {
-// return null;
-// }
-//
-// /**
-// *
-// * @param accountAddress
-// * 要操作的账户地址;
-// * @return
-// */
-// @Override
-// public MapStateOperationBuilder updateState(String accountAddress) {
-// return null;
-// }
-//
-// /**
-// * 执行定义账户的合约脚本的操作;
-// *
-// * @param accountAddress
-// * 要操作的账户地址;
-// * @return
-// */
-// @Override
-// public CodeDeployOperation defineScript(String accountAddress) {
-// return null;
-// }
-//
-// /**
-// * 执行调用账户的合约脚本的方法的操作;
-// *
-// * @param accountAddress
-// * 要操作的账户地址;
-// * @return
-// */
-// @Override
-// public ScriptInvokingOperation executeScript(String accountAddress) {
-// return null;
-// }
-//}
+//package com.jd.blockchain.sdk.proxy;
+//
+//import com.jd.blockchain.ledger.CodeDeployOperation;
+//import com.jd.blockchain.ledger.ContractEventOperation;
+//import com.jd.blockchain.ledger.MapStateOperationBuilder;
+//import com.jd.blockchain.ledger.ScriptInvokingOperation;
+//import com.jd.blockchain.ledger.data.BlockchainOperationFactory;
+//import com.jd.blockchain.ledger.data.OpBlob;
+//import com.jd.blockchain.ledger.data.PrivilegeSettingOperationBuilder;
+//
+//import my.utils.io.ByteArray;
+//
+//public class CodeInvokeOperationBuilder implements ScriptInvokingOperation {
+// private TxTemplate txTemp;
+//
+// public CodeInvokeOperationBuilder(TxTemplate txTemp) {
+// this.txTemp = txTemp;
+// }
+//
+// @Override
+// public void invoke(String address, String[] args) {
+// ContractEventOperation operation = BlockchainOperationFactory.getInstance().event(address, new ByteArray[] {});
+//
+// txTemp.addOperation((OpBlob) operation.getOperation());
+// }
+//
+// /**
+// * 配置特权操作;
+// *
+// * @param accountAddress
+// * 账户地址;
+// * @return
+// */
+// @Override
+// public PrivilegeSettingOperationBuilder configPrivilege(String accountAddress) {
+// return null;
+// }
+//
+// /**
+// *
+// * @param accountAddress
+// * 要操作的账户地址;
+// * @return
+// */
+// @Override
+// public MapStateOperationBuilder updateState(String accountAddress) {
+// return null;
+// }
+//
+// /**
+// * 执行定义账户的合约脚本的操作;
+// *
+// * @param accountAddress
+// * 要操作的账户地址;
+// * @return
+// */
+// @Override
+// public CodeDeployOperation defineScript(String accountAddress) {
+// return null;
+// }
+//
+// /**
+// * 执行调用账户的合约脚本的方法的操作;
+// *
+// * @param accountAddress
+// * 要操作的账户地址;
+// * @return
+// */
+// @Override
+// public ScriptInvokingOperation executeScript(String accountAddress) {
+// return null;
+// }
+//}
diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/proxy/HttpQueryServiceAdapter.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/proxy/HttpQueryServiceAdapter.java
index cb44c64f..0fccc12b 100644
--- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/proxy/HttpQueryServiceAdapter.java
+++ b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/proxy/HttpQueryServiceAdapter.java
@@ -1,136 +1,136 @@
-//package com.jd.blockchain.sdk.proxy;
-//
-//import java.util.Map;
-//import java.util.Set;
-//
-//import org.springframework.util.Base64Utils;
-//
-//import com.jd.blockchain.ledger.Block;
-//import com.jd.blockchain.ledger.BlockchainAccount;
-//import com.jd.blockchain.ledger.Ledger;
-//import com.jd.blockchain.ledger.StateMap;
-//import com.jd.blockchain.ledger.Transaction;
-//import com.jd.blockchain.sdk.BlockchainQueryService;
-//import com.jd.blockchain.service.LedgerQueryHttpService;
-//
-//import my.utils.http.agent.HttpServiceAgent;
-//import my.utils.http.agent.ServiceEndpoint;
-//import my.utils.net.NetworkAddress;
-//import my.utils.serialize.binary.BinarySerializeUtils;
-//
-//public class HttpQueryServiceAdapter implements BlockchainQueryService {
-//
-// private LedgerQueryHttpService queryHttpService;
-//
-// public HttpQueryServiceAdapter(NetworkAddress serviceAddress) {
-// ServiceEndpoint endpoint = new ServiceEndpoint(serviceAddress);
-// this.queryHttpService = HttpServiceAgent.createService(LedgerQueryHttpService.class, endpoint);
-// }
-//
-// @Override
-// public String[] getAllLedgerHashs() {
-// // TODO Auto-generated method stub
-// return null;
-// }
-//
-// @Override
-// public Ledger getLedger(String ledgerHash) {
-// return decodeObject(queryHttpService.getLedger(ledgerHash), Ledger.class);
-// }
-//
-// @Override
-// public Block getBlock(String ledgerHash, long height) {
-// return decodeObject(queryHttpService.getBlock(ledgerHash, height), Block.class);
-// }
-//
-// /**
-// * 返回指定账本序号的区块;
-// *
-// * @param ledgerHash
-// * 账本hash;
-// * @param blockHash
-// * @return
-// */
-// @Override
-// public Block getBlock(String ledgerHash, String blockHash) {
-// return decodeObject(queryHttpService.getBlock(ledgerHash, blockHash), Block.class);
-// }
-//
-// @Override
-// public Transaction[] getTransactions(String ledgerHash, long height, int fromIndex, int count) {
-// return decodeObject(queryHttpService.getBlockTransactions(height), Transaction[].class);
-// }
-//
-// /**
-// * 分页返回指定账本序号的区块中的交易列表;
-// *
-// * @param ledgerHash
-// * 账本hash;
-// * @param blockHash
-// * 账本高度;
-// * @param fromIndex
-// * 开始的记录数;
-// * @param count
-// * 本次返回的记录数;
-// * 如果参数值为 -1,则返回全部的记录;
-// * 注:通过 {@link #getBlock(String, String)} 方法获得的区块信息中可以得到区块的总交易数
-// * {@link Block#getTxCount()};
-// * @return
-// */
-// @Override
-// public Transaction[] getTransactions(String ledgerHash, String blockHash, int fromIndex, int count) {
-// return decodeObject(queryHttpService.getBlockTransactions(ledgerHash, blockHash, fromIndex, count),
-// Transaction[].class);
-// }
-//
-// @Override
-// public Transaction getTransactionByTxHash(String ledgerHash, String txHash) {
-// return decodeObject(queryHttpService.getBlockTransactionByTxHash(ledgerHash, txHash), Transaction.class);
-// }
-//
-// @Override
-// public Transaction getTransactionByContentHash(String ledgerHash, String contentHash) {
-// return decodeObject(queryHttpService.getBlockTransactionByContentHash(ledgerHash, contentHash),
-// Transaction.class);
-// }
-//
-// @Override
-// public BlockchainAccount getAccount(String ledgerHash, String address) {
-// return decodeObject(queryHttpService.getAccount(ledgerHash, address), BlockchainAccount.class);
-// }
-//
-// @Override
-// public StateMap getStates(String ledgerHash, String address, Set keys) {
-// // TODO Auto-generated method stub
-// return null;
-// }
-//
-// public StateMap getState(String ledgerHash, String address, String keys) {
-// return decodeObject(queryHttpService.getAccountState(ledgerHash,address, keys), StateMap.class);
-// }
-//
-// @Override
-// public StateMap queryObject(String ledgerHash, String address, String condition) {
-// // TODO Auto-generated method stub
-// return null;
-// }
-//
-// @Override
-// public Map queryObject(String ledgerHash, String condition) {
-// // TODO Auto-generated method stub
-// return null;
-// }
-//
-// @Override
-// public boolean containState(String ledgerHash, String address, String key) {
-// // TODO Auto-generated method stub
-// return false;
-// }
-//
-// @SuppressWarnings("unchecked")
-// private T decodeObject(String base64Str, Class clazz) {
-// byte[] bts = Base64Utils.decodeFromString(base64Str);
-// return (T) BinarySerializeUtils.deserialize(bts);
-// }
-//
-//}
+//package com.jd.blockchain.sdk.proxy;
+//
+//import java.util.Map;
+//import java.util.Set;
+//
+//import org.springframework.util.Base64Utils;
+//
+//import com.jd.blockchain.ledger.Block;
+//import com.jd.blockchain.ledger.BlockchainAccount;
+//import com.jd.blockchain.ledger.Ledger;
+//import com.jd.blockchain.ledger.StateMap;
+//import com.jd.blockchain.ledger.Transaction;
+//import com.jd.blockchain.sdk.BlockchainQueryService;
+//import com.jd.blockchain.service.LedgerQueryHttpService;
+//
+//import my.utils.http.agent.HttpServiceAgent;
+//import my.utils.http.agent.ServiceEndpoint;
+//import my.utils.net.NetworkAddress;
+//import my.utils.serialize.binary.BinarySerializeUtils;
+//
+//public class HttpQueryServiceAdapter implements BlockchainQueryService {
+//
+// private LedgerQueryHttpService queryHttpService;
+//
+// public HttpQueryServiceAdapter(NetworkAddress serviceAddress) {
+// ServiceEndpoint endpoint = new ServiceEndpoint(serviceAddress);
+// this.queryHttpService = HttpServiceAgent.createService(LedgerQueryHttpService.class, endpoint);
+// }
+//
+// @Override
+// public String[] getAllLedgerHashs() {
+// // TODO Auto-generated method stub
+// return null;
+// }
+//
+// @Override
+// public Ledger getLedger(String ledgerHash) {
+// return decodeObject(queryHttpService.getLedger(ledgerHash), Ledger.class);
+// }
+//
+// @Override
+// public Block getBlock(String ledgerHash, long height) {
+// return decodeObject(queryHttpService.getBlock(ledgerHash, height), Block.class);
+// }
+//
+// /**
+// * 返回指定账本序号的区块;
+// *
+// * @param ledgerHash
+// * 账本hash;
+// * @param blockHash
+// * @return
+// */
+// @Override
+// public Block getBlock(String ledgerHash, String blockHash) {
+// return decodeObject(queryHttpService.getBlock(ledgerHash, blockHash), Block.class);
+// }
+//
+// @Override
+// public Transaction[] getTransactions(String ledgerHash, long height, int fromIndex, int count) {
+// return decodeObject(queryHttpService.getBlockTransactions(height), Transaction[].class);
+// }
+//
+// /**
+// * 分页返回指定账本序号的区块中的交易列表;
+// *
+// * @param ledgerHash
+// * 账本hash;
+// * @param blockHash
+// * 账本高度;
+// * @param fromIndex
+// * 开始的记录数;
+// * @param count
+// * 本次返回的记录数;
+// * 如果参数值为 -1,则返回全部的记录;
+// * 注:通过 {@link #getBlock(String, String)} 方法获得的区块信息中可以得到区块的总交易数
+// * {@link Block#getTxCount()};
+// * @return
+// */
+// @Override
+// public Transaction[] getTransactions(String ledgerHash, String blockHash, int fromIndex, int count) {
+// return decodeObject(queryHttpService.getBlockTransactions(ledgerHash, blockHash, fromIndex, count),
+// Transaction[].class);
+// }
+//
+// @Override
+// public Transaction getTransactionByTxHash(String ledgerHash, String txHash) {
+// return decodeObject(queryHttpService.getBlockTransactionByTxHash(ledgerHash, txHash), Transaction.class);
+// }
+//
+// @Override
+// public Transaction getTransactionByContentHash(String ledgerHash, String contentHash) {
+// return decodeObject(queryHttpService.getBlockTransactionByContentHash(ledgerHash, contentHash),
+// Transaction.class);
+// }
+//
+// @Override
+// public BlockchainAccount getAccount(String ledgerHash, String address) {
+// return decodeObject(queryHttpService.getAccount(ledgerHash, address), BlockchainAccount.class);
+// }
+//
+// @Override
+// public StateMap getStates(String ledgerHash, String address, Set keys) {
+// // TODO Auto-generated method stub
+// return null;
+// }
+//
+// public StateMap getState(String ledgerHash, String address, String keys) {
+// return decodeObject(queryHttpService.getAccountState(ledgerHash,address, keys), StateMap.class);
+// }
+//
+// @Override
+// public StateMap queryObject(String ledgerHash, String address, String condition) {
+// // TODO Auto-generated method stub
+// return null;
+// }
+//
+// @Override
+// public Map queryObject(String ledgerHash, String condition) {
+// // TODO Auto-generated method stub
+// return null;
+// }
+//
+// @Override
+// public boolean containState(String ledgerHash, String address, String key) {
+// // TODO Auto-generated method stub
+// return false;
+// }
+//
+// @SuppressWarnings("unchecked")
+// private T decodeObject(String base64Str, Class clazz) {
+// byte[] bts = Base64Utils.decodeFromString(base64Str);
+// return (T) BinarySerializeUtils.deserialize(bts);
+// }
+//
+//}
diff --git a/source/sdk/sdk-base/src/test/java/test/com/jd/blockchain/sdk/proxy/TxMessageTest.java b/source/sdk/sdk-base/src/test/java/test/com/jd/blockchain/sdk/proxy/TxMessageTest.java
index 650b6fd2..794f437b 100644
--- a/source/sdk/sdk-base/src/test/java/test/com/jd/blockchain/sdk/proxy/TxMessageTest.java
+++ b/source/sdk/sdk-base/src/test/java/test/com/jd/blockchain/sdk/proxy/TxMessageTest.java
@@ -1,64 +1,64 @@
-package test.com.jd.blockchain.sdk.proxy;
-
-//public class TxMessageTest {
-//
-// @Test
-// public void testSerialize() throws IOException {
-// BlockchainKeyPair id = BlockchainKeyGenerator.getInstance().generate(CryptoKeyType.ED25519);
-// BlockchainKeyPair id1 = BlockchainKeyGenerator.getInstance().generate(CryptoKeyType.ED25519);
-// BlockchainKeyPair id2 = BlockchainKeyGenerator.getInstance().generate(CryptoKeyType.ED25519);
-//
-// TxContentBlob contentBlob = new TxContentBlob();
-//
-// contentBlob.setSubjectAccount(id.getAddress());
-// contentBlob.setSequenceNumber(1);
-//
-// OpBlob op1 = new OpBlob();
-// op1.setOperation(OperationType.REGISTER_USER.CODE, ByteArray.parseString("AAA", "UTF-8"));
-// contentBlob.addOperation(op1);
-//
-// TxRequestMessage txMsg = new TxRequestMessage(contentBlob);
-//
-// ByteArray mockedDigest = ByteArray.wrap(RandomUtils.generateRandomBytes(32));
-// DigitalSignatureBlob signature = new DigitalSignatureBlob(id.getPubKey(), mockedDigest);
-// txMsg.addEndpointSignatures(signature);
-//
-// ByteArray mockedDigest1 = ByteArray.wrap(RandomUtils.generateRandomBytes(32));
-// DigitalSignatureBlob signature1 = new DigitalSignatureBlob(id1.getPubKey(), mockedDigest1);
-// txMsg.addEndpointSignatures(signature1);
-//
-// ByteArray mockedDigest2 = ByteArray.wrap(RandomUtils.generateRandomBytes(32));
-// DigitalSignatureBlob signature2 = new DigitalSignatureBlob(id2.getPubKey(), mockedDigest2);
-// txMsg.addNodeSignatures(signature2);
-//
-// // 输出;
-// byte[] msgBytes = BinaryEncodingUtils.encode(txMsg, TransactionRequest.class);
-//
-// assertEquals(MagicNumber.TX_REQUEST, msgBytes[0]);
-//
-//// TxRequestMessage resolvedTxMsg = new TxRequestMessage();
-//// resolvedTxMsg.resolvFrom(ByteArray.wrap(msgBytes).asInputStream());
-// TxRequestMessage resolvedTxMsg = BinaryEncodingUtils.decode(msgBytes, null, TxRequestMessage.class);
-//
-// assertEquals(txMsg.getTransactionContent().getSubjectAccount(),
-// resolvedTxMsg.getTransactionContent().getSubjectAccount());
-// assertEquals(txMsg.getTransactionContent().getHash(), resolvedTxMsg.getTransactionContent().getHash());
-// assertEquals(txMsg.getHash(), resolvedTxMsg.getHash());
-//
-// DigitalSignature[] pSignatures = txMsg.getEndpointSignatures();
-// DigitalSignature[] resolvedPSignatures = txMsg.getEndpointSignatures();
-// assertEquals(pSignatures.length, resolvedPSignatures.length);
-// for (int i = 0; i < resolvedPSignatures.length; i++) {
-// assertEquals(pSignatures[i].getPubKey().getType(), resolvedPSignatures[i].getPubKey().getType());
-// assertEquals(pSignatures[i].getPubKey().getValue(), resolvedPSignatures[i].getPubKey().getValue());
-// assertEquals(pSignatures[i].getDigest(), resolvedPSignatures[i].getDigest());
-// }
-//
-// assertEquals(txMsg.getNodeSignatures()[0].getPubKey().getType(),
-// resolvedTxMsg.getNodeSignatures()[0].getPubKey().getType());
-// assertEquals(txMsg.getNodeSignatures()[0].getPubKey().getValue(),
-// resolvedTxMsg.getNodeSignatures()[0].getPubKey().getValue());
-// assertEquals(txMsg.getNodeSignatures()[0].getDigest(), resolvedTxMsg.getNodeSignatures()[0].getDigest());
-// }
-//
-//}
+package test.com.jd.blockchain.sdk.proxy;
+
+//public class TxMessageTest {
+//
+// @Test
+// public void testSerialize() throws IOException {
+// BlockchainKeyPair id = BlockchainKeyGenerator.getInstance().generate(CryptoKeyType.ED25519);
+// BlockchainKeyPair id1 = BlockchainKeyGenerator.getInstance().generate(CryptoKeyType.ED25519);
+// BlockchainKeyPair id2 = BlockchainKeyGenerator.getInstance().generate(CryptoKeyType.ED25519);
+//
+// TxContentBlob contentBlob = new TxContentBlob();
+//
+// contentBlob.setSubjectAccount(id.getAddress());
+// contentBlob.setSequenceNumber(1);
+//
+// OpBlob op1 = new OpBlob();
+// op1.setOperation(OperationType.REGISTER_USER.CODE, ByteArray.parseString("AAA", "UTF-8"));
+// contentBlob.addOperation(op1);
+//
+// TxRequestMessage txMsg = new TxRequestMessage(contentBlob);
+//
+// ByteArray mockedDigest = ByteArray.wrap(RandomUtils.generateRandomBytes(32));
+// DigitalSignatureBlob signature = new DigitalSignatureBlob(id.getPubKey(), mockedDigest);
+// txMsg.addEndpointSignatures(signature);
+//
+// ByteArray mockedDigest1 = ByteArray.wrap(RandomUtils.generateRandomBytes(32));
+// DigitalSignatureBlob signature1 = new DigitalSignatureBlob(id1.getPubKey(), mockedDigest1);
+// txMsg.addEndpointSignatures(signature1);
+//
+// ByteArray mockedDigest2 = ByteArray.wrap(RandomUtils.generateRandomBytes(32));
+// DigitalSignatureBlob signature2 = new DigitalSignatureBlob(id2.getPubKey(), mockedDigest2);
+// txMsg.addNodeSignatures(signature2);
+//
+// // 输出;
+// byte[] msgBytes = BinaryEncodingUtils.encode(txMsg, TransactionRequest.class);
+//
+// assertEquals(MagicNumber.TX_REQUEST, msgBytes[0]);
+//
+//// TxRequestMessage resolvedTxMsg = new TxRequestMessage();
+//// resolvedTxMsg.resolvFrom(ByteArray.wrap(msgBytes).asInputStream());
+// TxRequestMessage resolvedTxMsg = BinaryEncodingUtils.decode(msgBytes, null, TxRequestMessage.class);
+//
+// assertEquals(txMsg.getTransactionContent().getSubjectAccount(),
+// resolvedTxMsg.getTransactionContent().getSubjectAccount());
+// assertEquals(txMsg.getTransactionContent().getHash(), resolvedTxMsg.getTransactionContent().getHash());
+// assertEquals(txMsg.getHash(), resolvedTxMsg.getHash());
+//
+// DigitalSignature[] pSignatures = txMsg.getEndpointSignatures();
+// DigitalSignature[] resolvedPSignatures = txMsg.getEndpointSignatures();
+// assertEquals(pSignatures.length, resolvedPSignatures.length);
+// for (int i = 0; i < resolvedPSignatures.length; i++) {
+// assertEquals(pSignatures[i].getPubKey().getType(), resolvedPSignatures[i].getPubKey().getType());
+// assertEquals(pSignatures[i].getPubKey().getValue(), resolvedPSignatures[i].getPubKey().getValue());
+// assertEquals(pSignatures[i].getDigest(), resolvedPSignatures[i].getDigest());
+// }
+//
+// assertEquals(txMsg.getNodeSignatures()[0].getPubKey().getType(),
+// resolvedTxMsg.getNodeSignatures()[0].getPubKey().getType());
+// assertEquals(txMsg.getNodeSignatures()[0].getPubKey().getValue(),
+// resolvedTxMsg.getNodeSignatures()[0].getPubKey().getValue());
+// assertEquals(txMsg.getNodeSignatures()[0].getDigest(), resolvedTxMsg.getNodeSignatures()[0].getDigest());
+// }
+//
+//}
diff --git a/source/sdk/sdk-client/pom.xml b/source/sdk/sdk-client/pom.xml
index e2e995f4..22b2c53b 100644
--- a/source/sdk/sdk-client/pom.xml
+++ b/source/sdk/sdk-client/pom.xml
@@ -1,24 +1,24 @@
-
- 4.0.0
-
- com.jd.blockchain
- sdk
- 1.1.2.RELEASE
-
- sdk-client
-
-
-
- com.jd.blockchain
- sdk-base
- ${project.version}
-
-
-
- com.jd.blockchain
- ledger-rpc
- ${project.version}
-
-
+
+ 4.0.0
+
+ com.jd.blockchain
+ sdk
+ 1.1.2.RELEASE
+
+ sdk-client
+
+
+
+ com.jd.blockchain
+ sdk-base
+ ${project.version}
+
+
+
+ com.jd.blockchain
+ ledger-rpc
+ ${project.version}
+
+
\ No newline at end of file
diff --git a/source/sdk/sdk-client/src/main/java/com/jd/blockchain/sdk/client/GatewayIncomingInfo.java b/source/sdk/sdk-client/src/main/java/com/jd/blockchain/sdk/client/GatewayIncomingInfo.java
index c59d314a..9af45ef7 100644
--- a/source/sdk/sdk-client/src/main/java/com/jd/blockchain/sdk/client/GatewayIncomingInfo.java
+++ b/source/sdk/sdk-client/src/main/java/com/jd/blockchain/sdk/client/GatewayIncomingInfo.java
@@ -1,37 +1,37 @@
-package com.jd.blockchain.sdk.client;
-
-import java.io.Serializable;
-
-import com.jd.blockchain.utils.net.NetworkAddress;
-
-/**
- * 网关接入信息;
- *
- * @author huanghaiquan
- *
- */
-public class GatewayIncomingInfo implements Serializable {
-
- private static final long serialVersionUID = 981081410237759756L;
-
- private String sessionId;
-
- private NetworkAddress queryServiceAddress;
-
- public String getSessionId() {
- return sessionId;
- }
-
- public void setSessionId(String sessionId) {
- this.sessionId = sessionId;
- }
-
- public NetworkAddress getQueryServiceAddress() {
- return queryServiceAddress;
- }
-
- public void setQueryServiceAddress(NetworkAddress queryServiceAddress) {
- this.queryServiceAddress = queryServiceAddress;
- }
-
-}
+package com.jd.blockchain.sdk.client;
+
+import java.io.Serializable;
+
+import com.jd.blockchain.utils.net.NetworkAddress;
+
+/**
+ * 网关接入信息;
+ *
+ * @author huanghaiquan
+ *
+ */
+public class GatewayIncomingInfo implements Serializable {
+
+ private static final long serialVersionUID = 981081410237759756L;
+
+ private String sessionId;
+
+ private NetworkAddress queryServiceAddress;
+
+ public String getSessionId() {
+ return sessionId;
+ }
+
+ public void setSessionId(String sessionId) {
+ this.sessionId = sessionId;
+ }
+
+ public NetworkAddress getQueryServiceAddress() {
+ return queryServiceAddress;
+ }
+
+ public void setQueryServiceAddress(NetworkAddress queryServiceAddress) {
+ this.queryServiceAddress = queryServiceAddress;
+ }
+
+}
diff --git a/source/sdk/sdk-client/src/main/java/com/jd/blockchain/sdk/client/GatewayServiceFactory.java b/source/sdk/sdk-client/src/main/java/com/jd/blockchain/sdk/client/GatewayServiceFactory.java
index 1d50d1d7..b13b941f 100644
--- a/source/sdk/sdk-client/src/main/java/com/jd/blockchain/sdk/client/GatewayServiceFactory.java
+++ b/source/sdk/sdk-client/src/main/java/com/jd/blockchain/sdk/client/GatewayServiceFactory.java
@@ -1,225 +1,225 @@
-package com.jd.blockchain.sdk.client;
-
-import java.io.Closeable;
-
-import com.jd.blockchain.binaryproto.BinaryProtocol;
-import com.jd.blockchain.binaryproto.DataContractRegistry;
-import com.jd.blockchain.consensus.ClientIdentification;
-import com.jd.blockchain.consensus.ClientIdentifications;
-import com.jd.blockchain.consensus.action.ActionRequest;
-import com.jd.blockchain.consensus.action.ActionResponse;
-import com.jd.blockchain.crypto.Crypto;
-import com.jd.blockchain.crypto.PrivKey;
-import com.jd.blockchain.crypto.SignatureDigest;
-import com.jd.blockchain.crypto.SignatureFunction;
-import com.jd.blockchain.ledger.*;
-import com.jd.blockchain.sdk.BlockchainService;
-import com.jd.blockchain.sdk.BlockchainServiceFactory;
-import com.jd.blockchain.sdk.proxy.HttpBlockchainQueryService;
-import com.jd.blockchain.transaction.*;
-import com.jd.blockchain.utils.http.agent.HttpServiceAgent;
-import com.jd.blockchain.utils.http.agent.ServiceConnection;
-import com.jd.blockchain.utils.http.agent.ServiceConnectionManager;
-import com.jd.blockchain.utils.http.agent.ServiceEndpoint;
-import com.jd.blockchain.utils.net.NetworkAddress;
-import com.jd.blockchain.web.serializes.ByteArrayObjectUtil;
-
-public class GatewayServiceFactory implements BlockchainServiceFactory, Closeable {
-
- private ServiceConnectionManager httpConnectionManager;
-
- private BlockchainKeypair userKey;
-
- private BlockchainService blockchainService;
-
- static {
- DataContractRegistry.register(TransactionContent.class);
- DataContractRegistry.register(TransactionContentBody.class);
- DataContractRegistry.register(TransactionRequest.class);
- DataContractRegistry.register(NodeRequest.class);
- DataContractRegistry.register(EndpointRequest.class);
- DataContractRegistry.register(TransactionResponse.class);
- DataContractRegistry.register(DataAccountKVSetOperation.class);
- DataContractRegistry.register(DataAccountKVSetOperation.KVWriteEntry.class);
-
- DataContractRegistry.register(Operation.class);
- DataContractRegistry.register(ContractCodeDeployOperation.class);
- DataContractRegistry.register(ContractEventSendOperation.class);
- DataContractRegistry.register(DataAccountRegisterOperation.class);
- DataContractRegistry.register(UserRegisterOperation.class);
- DataContractRegistry.register(ParticipantRegisterOperation.class);
- DataContractRegistry.register(ParticipantStateUpdateOperation.class);
-
- DataContractRegistry.register(ActionRequest.class);
- DataContractRegistry.register(ActionResponse.class);
- DataContractRegistry.register(ClientIdentifications.class);
- DataContractRegistry.register(ClientIdentification.class);
- DataContractRegistry.register(BytesValueList.class);
-
- // 注册角色/权限相关接口
- DataContractRegistry.register(RolesConfigureOperation.class);
- DataContractRegistry.register(RolesConfigureOperation.RolePrivilegeEntry.class);
- DataContractRegistry.register(UserAuthorizeOperation.class);
- DataContractRegistry.register(UserAuthorizeOperation.UserRolesEntry.class);
- DataContractRegistry.register(PrivilegeSet.class);
- DataContractRegistry.register(RoleSet.class);
- DataContractRegistry.register(SecurityInitSettings.class);
- DataContractRegistry.register(RoleInitSettings.class);
- DataContractRegistry.register(UserAuthInitSettings.class);
- DataContractRegistry.register(LedgerMetadata_V2.class);
-
- ByteArrayObjectUtil.init();
- }
-
- protected GatewayServiceFactory(ServiceEndpoint gatewayEndpoint, BlockchainKeypair userKey) {
- httpConnectionManager = new ServiceConnectionManager();
- this.userKey = userKey;
-
- BlockchainQueryService queryService = createQueryService(gatewayEndpoint);
- TransactionService txProcSrv = createConsensusService(gatewayEndpoint);
- this.blockchainService = new GatewayBlockchainServiceProxy(txProcSrv, queryService);
- }
-
- @Override
- public BlockchainService getBlockchainService() {
- return blockchainService;
- }
-
- // TODO:暂未实现基于“口令”的认证方式;
- /**
- * 基于“口令”连接;
- *
- * @param gatewayHost
- * @param gatewayPort
- * @param secure
- * @param userName
- * @param password
- * @return
- */
- // public static BlockchainServiceFactory connect(String gatewayHost, int
- // gatewayPort, boolean secure, String userName,
- // String password) {
- // ServiceEndpoint gatewayEndpoint = new ServiceEndpoint(gatewayHost,
- // gatewayPort, secure);
- // BlockchainServiceFactory factory = new
- // BlockchainServiceFactory(gatewayEndpoint);
- // factory.setMaxConnections(100);
- // return factory;
- // }
-
- /**
- * 连接网关节点;
- *
- * @param gatewayAddress 网关节点的网络地址;
- * @return 网关服务工厂的实例;
- */
- public static GatewayServiceFactory connect(NetworkAddress gatewayAddress) {
- return connect(gatewayAddress.getHost(), gatewayAddress.getPort(), gatewayAddress.isSecure(), null);
- }
-
- /**
- * 网关服务工厂的实例;
- *
- * @param gatewayAddress 网关节点的网络地址;
- * @param userKey 自动交易签名的用户密钥;可选参数,如果不为 null,则在提交交易时,自动以参数指定的密钥签署交易;
- * @return 网关服务工厂的实例;
- */
- public static GatewayServiceFactory connect(NetworkAddress gatewayAddress, BlockchainKeypair userKey) {
- return connect(gatewayAddress.getHost(), gatewayAddress.getPort(), gatewayAddress.isSecure(), userKey);
- }
-
- /**
- * 连接网关节点;
- *
- * @param gatewayHost 网关节点的地址;
- * @param gatewayPort 网关节点的端口;
- * @param secure 是否采用安全的通讯协议(HTTPS);
- * @return 网关服务工厂的实例;
- */
- public static GatewayServiceFactory connect(String gatewayHost, int gatewayPort, boolean secure) {
- return connect(gatewayHost, gatewayPort, secure, null);
- }
-
- /**
- * 连接网关节点;
- *
- * @param gatewayHost 网关节点的地址;
- * @param gatewayPort 网关节点的端口;
- * @param secure 是否采用安全的通讯协议(HTTPS);
- * @param userKey 自动交易签名的用户密钥;可选参数,如果不为 null,则在提交交易时,自动以参数指定的密钥签署交易;
- * @return 网关服务工厂的实例;
- */
- public static GatewayServiceFactory connect(String gatewayHost, int gatewayPort, boolean secure,
- BlockchainKeypair userKey) {
-// if (userKey == null) {
-// throw new IllegalArgumentException("User key is null!");
-// }
- ServiceEndpoint gatewayEndpoint = new ServiceEndpoint(gatewayHost, gatewayPort, secure);
- GatewayServiceFactory factory = new GatewayServiceFactory(gatewayEndpoint, userKey);
- factory.setMaxConnections(100);
- // TODO: 未实现网关对用户的认证;
- // TODO: 未实现加载不同账本的密码算法配置;
- return factory;
- }
-
- public void setMaxConnections(int maxCount) {
- httpConnectionManager.setMaxTotal(maxCount).setDefaultMaxPerRoute(maxCount);
- }
-
- private TransactionService createConsensusService(ServiceEndpoint gatewayEndpoint) {
- ServiceConnection connection = httpConnectionManager.create(gatewayEndpoint);
- TransactionService gatewayConsensusService = HttpServiceAgent.createService(HttpConsensusService.class,
- connection, null);
- if (userKey != null) {
- gatewayConsensusService = new EndpointAutoSigner(gatewayConsensusService, userKey);
- }
- return gatewayConsensusService;
- }
-
- private BlockchainQueryService createQueryService(ServiceEndpoint gatewayEndpoint) {
- ServiceConnection conn = httpConnectionManager.create(gatewayEndpoint);
- return HttpServiceAgent.createService(HttpBlockchainQueryService.class, conn, null);
- }
-
- @Override
- public void close() {
- httpConnectionManager.close();
- }
-
- private static class EndpointAutoSigner implements TransactionService {
-
- private TransactionService innerService;
-
- private BlockchainKeypair userKey;
-
- public EndpointAutoSigner(TransactionService innerService, BlockchainKeypair userKey) {
- this.innerService = innerService;
- this.userKey = userKey;
- }
-
- @Override
- public TransactionResponse process(TransactionRequest txRequest) {
- TxRequestMessage reqMsg = (TxRequestMessage) txRequest;
- // TODO: 未实现按不同的账本的密码参数配置,采用不同的哈希算法和签名算法;
- if (!reqMsg.containsEndpointSignature(userKey.getAddress())) {
- // TODO: 优化上下文对此 TransactionContent 的多次序列化带来的额外性能开销;
- DigitalSignature signature = SignatureUtils.sign(txRequest.getTransactionContent(), userKey);
- reqMsg.addEndpointSignatures(signature);
-//
-//
-//
-// byte[] txContentBytes = BinaryProtocol.encode(txRequest.getTransactionContent(),
-// TransactionContent.class);
-// PrivKey userPrivKey = userKey.getPrivKey();
-// SignatureFunction signatureFunction = Crypto.getSignatureFunction(userKey.getAlgorithm());
-// if (signatureFunction != null) {
-// SignatureDigest signatureDigest = signatureFunction.sign(userPrivKey, txContentBytes);
-// DigitalSignature signature = new DigitalSignatureBlob(userKey.getPubKey(), signatureDigest);
-// reqMsg.addEndpointSignatures(signature);
-// }
- }
- return innerService.process(txRequest);
- }
- }
-
-}
+package com.jd.blockchain.sdk.client;
+
+import java.io.Closeable;
+
+import com.jd.blockchain.binaryproto.BinaryProtocol;
+import com.jd.blockchain.binaryproto.DataContractRegistry;
+import com.jd.blockchain.consensus.ClientIdentification;
+import com.jd.blockchain.consensus.ClientIdentifications;
+import com.jd.blockchain.consensus.action.ActionRequest;
+import com.jd.blockchain.consensus.action.ActionResponse;
+import com.jd.blockchain.crypto.Crypto;
+import com.jd.blockchain.crypto.PrivKey;
+import com.jd.blockchain.crypto.SignatureDigest;
+import com.jd.blockchain.crypto.SignatureFunction;
+import com.jd.blockchain.ledger.*;
+import com.jd.blockchain.sdk.BlockchainService;
+import com.jd.blockchain.sdk.BlockchainServiceFactory;
+import com.jd.blockchain.sdk.proxy.HttpBlockchainQueryService;
+import com.jd.blockchain.transaction.*;
+import com.jd.blockchain.utils.http.agent.HttpServiceAgent;
+import com.jd.blockchain.utils.http.agent.ServiceConnection;
+import com.jd.blockchain.utils.http.agent.ServiceConnectionManager;
+import com.jd.blockchain.utils.http.agent.ServiceEndpoint;
+import com.jd.blockchain.utils.net.NetworkAddress;
+import com.jd.blockchain.web.serializes.ByteArrayObjectUtil;
+
+public class GatewayServiceFactory implements BlockchainServiceFactory, Closeable {
+
+ private ServiceConnectionManager httpConnectionManager;
+
+ private BlockchainKeypair userKey;
+
+ private BlockchainService blockchainService;
+
+ static {
+ DataContractRegistry.register(TransactionContent.class);
+ DataContractRegistry.register(TransactionContentBody.class);
+ DataContractRegistry.register(TransactionRequest.class);
+ DataContractRegistry.register(NodeRequest.class);
+ DataContractRegistry.register(EndpointRequest.class);
+ DataContractRegistry.register(TransactionResponse.class);
+ DataContractRegistry.register(DataAccountKVSetOperation.class);
+ DataContractRegistry.register(DataAccountKVSetOperation.KVWriteEntry.class);
+
+ DataContractRegistry.register(Operation.class);
+ DataContractRegistry.register(ContractCodeDeployOperation.class);
+ DataContractRegistry.register(ContractEventSendOperation.class);
+ DataContractRegistry.register(DataAccountRegisterOperation.class);
+ DataContractRegistry.register(UserRegisterOperation.class);
+ DataContractRegistry.register(ParticipantRegisterOperation.class);
+ DataContractRegistry.register(ParticipantStateUpdateOperation.class);
+
+ DataContractRegistry.register(ActionRequest.class);
+ DataContractRegistry.register(ActionResponse.class);
+ DataContractRegistry.register(ClientIdentifications.class);
+ DataContractRegistry.register(ClientIdentification.class);
+ DataContractRegistry.register(BytesValueList.class);
+
+ // 注册角色/权限相关接口
+ DataContractRegistry.register(RolesConfigureOperation.class);
+ DataContractRegistry.register(RolesConfigureOperation.RolePrivilegeEntry.class);
+ DataContractRegistry.register(UserAuthorizeOperation.class);
+ DataContractRegistry.register(UserAuthorizeOperation.UserRolesEntry.class);
+ DataContractRegistry.register(PrivilegeSet.class);
+ DataContractRegistry.register(RoleSet.class);
+ DataContractRegistry.register(SecurityInitSettings.class);
+ DataContractRegistry.register(RoleInitSettings.class);
+ DataContractRegistry.register(UserAuthInitSettings.class);
+ DataContractRegistry.register(LedgerMetadata_V2.class);
+
+ ByteArrayObjectUtil.init();
+ }
+
+ protected GatewayServiceFactory(ServiceEndpoint gatewayEndpoint, BlockchainKeypair userKey) {
+ httpConnectionManager = new ServiceConnectionManager();
+ this.userKey = userKey;
+
+ BlockchainQueryService queryService = createQueryService(gatewayEndpoint);
+ TransactionService txProcSrv = createConsensusService(gatewayEndpoint);
+ this.blockchainService = new GatewayBlockchainServiceProxy(txProcSrv, queryService);
+ }
+
+ @Override
+ public BlockchainService getBlockchainService() {
+ return blockchainService;
+ }
+
+ // TODO:暂未实现基于“口令”的认证方式;
+ /**
+ * 基于“口令”连接;
+ *
+ * @param gatewayHost
+ * @param gatewayPort
+ * @param secure
+ * @param userName
+ * @param password
+ * @return
+ */
+ // public static BlockchainServiceFactory connect(String gatewayHost, int
+ // gatewayPort, boolean secure, String userName,
+ // String password) {
+ // ServiceEndpoint gatewayEndpoint = new ServiceEndpoint(gatewayHost,
+ // gatewayPort, secure);
+ // BlockchainServiceFactory factory = new
+ // BlockchainServiceFactory(gatewayEndpoint);
+ // factory.setMaxConnections(100);
+ // return factory;
+ // }
+
+ /**
+ * 连接网关节点;
+ *
+ * @param gatewayAddress 网关节点的网络地址;
+ * @return 网关服务工厂的实例;
+ */
+ public static GatewayServiceFactory connect(NetworkAddress gatewayAddress) {
+ return connect(gatewayAddress.getHost(), gatewayAddress.getPort(), gatewayAddress.isSecure(), null);
+ }
+
+ /**
+ * 网关服务工厂的实例;
+ *
+ * @param gatewayAddress 网关节点的网络地址;
+ * @param userKey 自动交易签名的用户密钥;可选参数,如果不为 null,则在提交交易时,自动以参数指定的密钥签署交易;
+ * @return 网关服务工厂的实例;
+ */
+ public static GatewayServiceFactory connect(NetworkAddress gatewayAddress, BlockchainKeypair userKey) {
+ return connect(gatewayAddress.getHost(), gatewayAddress.getPort(), gatewayAddress.isSecure(), userKey);
+ }
+
+ /**
+ * 连接网关节点;
+ *
+ * @param gatewayHost 网关节点的地址;
+ * @param gatewayPort 网关节点的端口;
+ * @param secure 是否采用安全的通讯协议(HTTPS);
+ * @return 网关服务工厂的实例;
+ */
+ public static GatewayServiceFactory connect(String gatewayHost, int gatewayPort, boolean secure) {
+ return connect(gatewayHost, gatewayPort, secure, null);
+ }
+
+ /**
+ * 连接网关节点;
+ *
+ * @param gatewayHost 网关节点的地址;
+ * @param gatewayPort 网关节点的端口;
+ * @param secure 是否采用安全的通讯协议(HTTPS);
+ * @param userKey 自动交易签名的用户密钥;可选参数,如果不为 null,则在提交交易时,自动以参数指定的密钥签署交易;
+ * @return 网关服务工厂的实例;
+ */
+ public static GatewayServiceFactory connect(String gatewayHost, int gatewayPort, boolean secure,
+ BlockchainKeypair userKey) {
+// if (userKey == null) {
+// throw new IllegalArgumentException("User key is null!");
+// }
+ ServiceEndpoint gatewayEndpoint = new ServiceEndpoint(gatewayHost, gatewayPort, secure);
+ GatewayServiceFactory factory = new GatewayServiceFactory(gatewayEndpoint, userKey);
+ factory.setMaxConnections(100);
+ // TODO: 未实现网关对用户的认证;
+ // TODO: 未实现加载不同账本的密码算法配置;
+ return factory;
+ }
+
+ public void setMaxConnections(int maxCount) {
+ httpConnectionManager.setMaxTotal(maxCount).setDefaultMaxPerRoute(maxCount);
+ }
+
+ private TransactionService createConsensusService(ServiceEndpoint gatewayEndpoint) {
+ ServiceConnection connection = httpConnectionManager.create(gatewayEndpoint);
+ TransactionService gatewayConsensusService = HttpServiceAgent.createService(HttpConsensusService.class,
+ connection, null);
+ if (userKey != null) {
+ gatewayConsensusService = new EndpointAutoSigner(gatewayConsensusService, userKey);
+ }
+ return gatewayConsensusService;
+ }
+
+ private BlockchainQueryService createQueryService(ServiceEndpoint gatewayEndpoint) {
+ ServiceConnection conn = httpConnectionManager.create(gatewayEndpoint);
+ return HttpServiceAgent.createService(HttpBlockchainQueryService.class, conn, null);
+ }
+
+ @Override
+ public void close() {
+ httpConnectionManager.close();
+ }
+
+ private static class EndpointAutoSigner implements TransactionService {
+
+ private TransactionService innerService;
+
+ private BlockchainKeypair userKey;
+
+ public EndpointAutoSigner(TransactionService innerService, BlockchainKeypair userKey) {
+ this.innerService = innerService;
+ this.userKey = userKey;
+ }
+
+ @Override
+ public TransactionResponse process(TransactionRequest txRequest) {
+ TxRequestMessage reqMsg = (TxRequestMessage) txRequest;
+ // TODO: 未实现按不同的账本的密码参数配置,采用不同的哈希算法和签名算法;
+ if (!reqMsg.containsEndpointSignature(userKey.getAddress())) {
+ // TODO: 优化上下文对此 TransactionContent 的多次序列化带来的额外性能开销;
+ DigitalSignature signature = SignatureUtils.sign(txRequest.getTransactionContent(), userKey);
+ reqMsg.addEndpointSignatures(signature);
+//
+//
+//
+// byte[] txContentBytes = BinaryProtocol.encode(txRequest.getTransactionContent(),
+// TransactionContent.class);
+// PrivKey userPrivKey = userKey.getPrivKey();
+// SignatureFunction signatureFunction = Crypto.getSignatureFunction(userKey.getAlgorithm());
+// if (signatureFunction != null) {
+// SignatureDigest signatureDigest = signatureFunction.sign(userPrivKey, txContentBytes);
+// DigitalSignature signature = new DigitalSignatureBlob(userKey.getPubKey(), signatureDigest);
+// reqMsg.addEndpointSignatures(signature);
+// }
+ }
+ return innerService.process(txRequest);
+ }
+ }
+
+}
diff --git a/source/sdk/sdk-client/src/main/java/com/jd/blockchain/sdk/client/HttpConsensusService.java b/source/sdk/sdk-client/src/main/java/com/jd/blockchain/sdk/client/HttpConsensusService.java
index 9485436f..16e23e8e 100644
--- a/source/sdk/sdk-client/src/main/java/com/jd/blockchain/sdk/client/HttpConsensusService.java
+++ b/source/sdk/sdk-client/src/main/java/com/jd/blockchain/sdk/client/HttpConsensusService.java
@@ -1,19 +1,19 @@
-package com.jd.blockchain.sdk.client;
-
-import com.jd.blockchain.ledger.TransactionRequest;
-import com.jd.blockchain.ledger.TransactionResponse;
-import com.jd.blockchain.sdk.converters.BinarySerializeRequestConverter;
-import com.jd.blockchain.sdk.converters.BinarySerializeResponseConverter;
-import com.jd.blockchain.transaction.TransactionService;
-import com.jd.blockchain.utils.http.HttpAction;
-import com.jd.blockchain.utils.http.HttpMethod;
-import com.jd.blockchain.utils.http.HttpService;
-import com.jd.blockchain.utils.http.RequestBody;
-
-@HttpService(defaultRequestBodyConverter = BinarySerializeRequestConverter.class, defaultResponseConverter = BinarySerializeResponseConverter.class)
-public interface HttpConsensusService extends TransactionService {
-
- @HttpAction(method = HttpMethod.POST, path = "rpc/tx", contentType = BinarySerializeRequestConverter.CONTENT_TYPE_VALUE)
- @Override
- TransactionResponse process(@RequestBody TransactionRequest txRequest);
-}
+package com.jd.blockchain.sdk.client;
+
+import com.jd.blockchain.ledger.TransactionRequest;
+import com.jd.blockchain.ledger.TransactionResponse;
+import com.jd.blockchain.sdk.converters.BinarySerializeRequestConverter;
+import com.jd.blockchain.sdk.converters.BinarySerializeResponseConverter;
+import com.jd.blockchain.transaction.TransactionService;
+import com.jd.blockchain.utils.http.HttpAction;
+import com.jd.blockchain.utils.http.HttpMethod;
+import com.jd.blockchain.utils.http.HttpService;
+import com.jd.blockchain.utils.http.RequestBody;
+
+@HttpService(defaultRequestBodyConverter = BinarySerializeRequestConverter.class, defaultResponseConverter = BinarySerializeResponseConverter.class)
+public interface HttpConsensusService extends TransactionService {
+
+ @HttpAction(method = HttpMethod.POST, path = "rpc/tx", contentType = BinarySerializeRequestConverter.CONTENT_TYPE_VALUE)
+ @Override
+ TransactionResponse process(@RequestBody TransactionRequest txRequest);
+}
diff --git a/source/sdk/sdk-samples/pom.xml b/source/sdk/sdk-samples/pom.xml
index ece0c958..83caf6f7 100644
--- a/source/sdk/sdk-samples/pom.xml
+++ b/source/sdk/sdk-samples/pom.xml
@@ -1,53 +1,53 @@
-
- 4.0.0
-
- com.jd.blockchain
- sdk
- 1.1.2.RELEASE
-
- sdk-samples
-
-
-
- com.jd.blockchain
- sdk-client
- ${project.version}
-
-
- com.jd.blockchain
- ledger-model
- ${project.version}
-
-
- com.jd.blockchain
- tools-initializer
- ${project.version}
-
-
- com.jd.blockchain
- contract-samples
- ${project.version}
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-deploy-plugin
-
- true
-
-
-
-
-
-
-
-
-
-
-
+
+ 4.0.0
+
+ com.jd.blockchain
+ sdk
+ 1.1.2.RELEASE
+
+ sdk-samples
+
+
+
+ com.jd.blockchain
+ sdk-client
+ ${project.version}
+
+
+ com.jd.blockchain
+ ledger-model
+ ${project.version}
+
+
+ com.jd.blockchain
+ tools-initializer
+ ${project.version}
+
+
+ com.jd.blockchain
+ contract-samples
+ ${project.version}
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-deploy-plugin
+
+ true
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_EventListener.java b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_EventListener.java
index 935431ec..c4cb2642 100644
--- a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_EventListener.java
+++ b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_EventListener.java
@@ -1,74 +1,74 @@
-//package com.jd.blockchain.sdk.samples;
-//
-//import com.jd.blockchain.ledger.BlockchainEventType;
-//import com.jd.blockchain.ledger.BlockchainKeyGenerator;
-//import com.jd.blockchain.ledger.BlockchainKeyPair;
-//import com.jd.blockchain.ledger.CryptoKeyType;
-//import com.jd.blockchain.ledger.StateMap;
-//import com.jd.blockchain.sdk.BlockchainEventHandle;
-//import com.jd.blockchain.sdk.BlockchainEventListener;
-//import com.jd.blockchain.sdk.BlockchainEventMessage;
-//import com.jd.blockchain.sdk.BlockchainService;
-//import com.jd.blockchain.sdk.client.BlockchainServiceFactory;
-//
-//import my.utils.net.NetworkAddress;
-//
-///**
-// * 演示监听区块链事件的过程;
-// *
-// * @author huanghaiquan
-// *
-// */
-//public class SDKDemo_EventListener {
-//
-// public static BlockchainKeyPair CLIENT_CERT = BlockchainKeyGenerator.getInstance().generate(CryptoKeyType.ED25519);
-//
-// /**
-// * 演示合约执行的过程;
-// */
-// public static void demoContract() {
-// // 区块链共识域;
-// String realm = "SUPPLY_CHAIN_ALLIANCE";
-// // 节点地址列表;
-// NetworkAddress[] peerAddrs = { new NetworkAddress("192.168.10.10", 8080),
-// new NetworkAddress("192.168.10.11", 8080), new NetworkAddress("192.168.10.12", 8080),
-// new NetworkAddress("192.168.10.13", 8080) };
-//
-// // 网关客户端编号;
-// int gatewayId = 1001;
-// // 账本地址;
-// String ledgerAddress = "ffkjhkeqwiuhivnsh3298josijdocaijsda==";
-// // 客户端的认证账户;
-// String clientAddress = "kkjsafieweqEkadsfaslkdslkae998232jojf==";
-// String privKey = "safefsd32q34vdsvs";
-// // 创建服务代理;
-// final String GATEWAY_IP = "127.0.0.1";
-// final int GATEWAY_PORT = 80;
-// final boolean SECURE = false;
-// BlockchainServiceFactory serviceFactory = BlockchainServiceFactory.connect(GATEWAY_IP, GATEWAY_PORT, SECURE,
-// CLIENT_CERT);
-// BlockchainService service = serviceFactory.getBlockchainService();
-//
-// // 监听账户变动;
-// String walletAccount = "MMMEy902jkjjJJDkshreGeasdfassdfajjf==";
-// service.addBlockchainEventListener(BlockchainEventType.PAYLOAD_UPDATED.CODE, null, walletAccount,
-// new BlockchainEventListener() {
-// @Override
-// public void onEvent(BlockchainEventMessage eventMessage, BlockchainEventHandle eventHandle) {
-// // 钱包余额;
-// StateMap balancePayload = service.getState(walletAccount, "RMB-ASSET","name");
-// Long balance = (Long) balancePayload.get("RMB-ASSET").longValue();
-// if (balance != null) {
-// // notify balance change;
-// } else {
-// // wallet is empty and isn't listened any more;
-// eventHandle.cancel();
-// }
-// }
-// });
-//
-// // 销毁服务代理;
-// serviceFactory.close();
-// }
-//
-//}
+//package com.jd.blockchain.sdk.samples;
+//
+//import com.jd.blockchain.ledger.BlockchainEventType;
+//import com.jd.blockchain.ledger.BlockchainKeyGenerator;
+//import com.jd.blockchain.ledger.BlockchainKeyPair;
+//import com.jd.blockchain.ledger.CryptoKeyType;
+//import com.jd.blockchain.ledger.StateMap;
+//import com.jd.blockchain.sdk.BlockchainEventHandle;
+//import com.jd.blockchain.sdk.BlockchainEventListener;
+//import com.jd.blockchain.sdk.BlockchainEventMessage;
+//import com.jd.blockchain.sdk.BlockchainService;
+//import com.jd.blockchain.sdk.client.BlockchainServiceFactory;
+//
+//import my.utils.net.NetworkAddress;
+//
+///**
+// * 演示监听区块链事件的过程;
+// *
+// * @author huanghaiquan
+// *
+// */
+//public class SDKDemo_EventListener {
+//
+// public static BlockchainKeyPair CLIENT_CERT = BlockchainKeyGenerator.getInstance().generate(CryptoKeyType.ED25519);
+//
+// /**
+// * 演示合约执行的过程;
+// */
+// public static void demoContract() {
+// // 区块链共识域;
+// String realm = "SUPPLY_CHAIN_ALLIANCE";
+// // 节点地址列表;
+// NetworkAddress[] peerAddrs = { new NetworkAddress("192.168.10.10", 8080),
+// new NetworkAddress("192.168.10.11", 8080), new NetworkAddress("192.168.10.12", 8080),
+// new NetworkAddress("192.168.10.13", 8080) };
+//
+// // 网关客户端编号;
+// int gatewayId = 1001;
+// // 账本地址;
+// String ledgerAddress = "ffkjhkeqwiuhivnsh3298josijdocaijsda==";
+// // 客户端的认证账户;
+// String clientAddress = "kkjsafieweqEkadsfaslkdslkae998232jojf==";
+// String privKey = "safefsd32q34vdsvs";
+// // 创建服务代理;
+// final String GATEWAY_IP = "127.0.0.1";
+// final int GATEWAY_PORT = 80;
+// final boolean SECURE = false;
+// BlockchainServiceFactory serviceFactory = BlockchainServiceFactory.connect(GATEWAY_IP, GATEWAY_PORT, SECURE,
+// CLIENT_CERT);
+// BlockchainService service = serviceFactory.getBlockchainService();
+//
+// // 监听账户变动;
+// String walletAccount = "MMMEy902jkjjJJDkshreGeasdfassdfajjf==";
+// service.addBlockchainEventListener(BlockchainEventType.PAYLOAD_UPDATED.CODE, null, walletAccount,
+// new BlockchainEventListener() {
+// @Override
+// public void onEvent(BlockchainEventMessage eventMessage, BlockchainEventHandle eventHandle) {
+// // 钱包余额;
+// StateMap balancePayload = service.getState(walletAccount, "RMB-ASSET","name");
+// Long balance = (Long) balancePayload.get("RMB-ASSET").longValue();
+// if (balance != null) {
+// // notify balance change;
+// } else {
+// // wallet is empty and isn't listened any more;
+// eventHandle.cancel();
+// }
+// }
+// });
+//
+// // 销毁服务代理;
+// serviceFactory.close();
+// }
+//
+//}
diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_PrivilegeSetting.java b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_PrivilegeSetting.java
index ea85a11e..bdf819d2 100644
--- a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_PrivilegeSetting.java
+++ b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_PrivilegeSetting.java
@@ -1,75 +1,75 @@
-package com.jd.blockchain.sdk.samples;
-
-public class SDKDemo_PrivilegeSetting {
-
-// public static BlockchainKeyPair CLIENT_CERT = BlockchainKeyGenerator.getInstance().generate(CryptoKeyType.ED25519);
-//
-// /**
-// * 生成一个区块链账户,并注册到区块链;
-// */
-// public static void registerAccount() {
-// // 区块链共识域;
-// String realm = "SUPPLY_CHAIN_ALLIANCE";
-// // 节点地址列表;
-// NetworkAddress[] peerAddrs = { new NetworkAddress("192.168.10.10", 8080),
-// new NetworkAddress("192.168.10.11", 8080), new NetworkAddress("192.168.10.12", 8080),
-// new NetworkAddress("192.168.10.13", 8080) };
-//
-// // 网关客户端编号;
-// int gatewayId = 1001;
-// // 账本地址;
-// String ledgerAddress = "ffkjhkeqwiuhivnsh3298josijdocaijsda==";
-// // 客户端的认证账户;
-// String clientAddress = "kkjsafieweqEkadsfaslkdslkae998232jojf==";
-// String privKey = "safefsd32q34vdsvs";
-// // 创建服务代理;
-// final String GATEWAY_IP = "127.0.0.1";
-// final int GATEWAY_PORT = 80;
-// final boolean SECURE = false;
-// BlockchainServiceFactory serviceFactory = BlockchainServiceFactory.connect(GATEWAY_IP, GATEWAY_PORT, SECURE,
-// CLIENT_CERT);
-// BlockchainTransactionService service = serviceFactory.getBlockchainService();
-//
-// HashDigest ledgerHash = getLedgerHash();
-// // 在本地定义注册账号的 TX;
-// TransactionTemplate txTemp = service.newTransaction(ledgerHash);
-//
-// // --------------------------------------
-// // 配置账户的权限;
-// String walletAccount = "Kjfe8832hfa9jjjJJDkshrFjksjdlkfj93F==";
-// String user1 = "MMMEy902jkjjJJDkshreGeasdfassdfajjf==";
-// String user2 = "Kjfe8832hfa9jjjJJDkshrFjksjdlkfj93F==";
-// // 配置:
-// // “状态数据的写入权限”的阈值为 100;
-// // 需要 user1、user2 两个账户的联合签名才能写入;
-// // 当前账户仅用于表示一个业务钱包,禁止自身的写入权限,只能由业务角色的账户才能操作;
-//
-//
-//
-// txTemp.configPrivilege(walletAccount).setThreshhold(PrivilegeType.STATE_WRITE, 100)
-// .enable(PrivilegeType.STATE_WRITE, user1, 50).enable(PrivilegeType.STATE_WRITE, user2, 50)
-// .disable(PrivilegeType.STATE_WRITE, walletAccount);
-// // --------------------------------------
-//
-// // TX 准备就绪;
-// PreparedTransaction prepTx = txTemp.prepare();
-//
-// // 使用私钥进行签名;
-// BlockchainKeyPair sponsorKey = getSponsorKey();
-// prepTx.sign(sponsorKey);
-//
-// // 提交交易;
-// prepTx.commit();
-// }
-//
-// private static HashDigest getLedgerHash() {
-// // TODO Init ledger hash;
-// return null;
-// }
-//
-// private static BlockchainKeyPair getSponsorKey() {
-// // TODO Auto-generated method stub
-// return null;
-// }
-
-}
+package com.jd.blockchain.sdk.samples;
+
+public class SDKDemo_PrivilegeSetting {
+
+// public static BlockchainKeyPair CLIENT_CERT = BlockchainKeyGenerator.getInstance().generate(CryptoKeyType.ED25519);
+//
+// /**
+// * 生成一个区块链账户,并注册到区块链;
+// */
+// public static void registerAccount() {
+// // 区块链共识域;
+// String realm = "SUPPLY_CHAIN_ALLIANCE";
+// // 节点地址列表;
+// NetworkAddress[] peerAddrs = { new NetworkAddress("192.168.10.10", 8080),
+// new NetworkAddress("192.168.10.11", 8080), new NetworkAddress("192.168.10.12", 8080),
+// new NetworkAddress("192.168.10.13", 8080) };
+//
+// // 网关客户端编号;
+// int gatewayId = 1001;
+// // 账本地址;
+// String ledgerAddress = "ffkjhkeqwiuhivnsh3298josijdocaijsda==";
+// // 客户端的认证账户;
+// String clientAddress = "kkjsafieweqEkadsfaslkdslkae998232jojf==";
+// String privKey = "safefsd32q34vdsvs";
+// // 创建服务代理;
+// final String GATEWAY_IP = "127.0.0.1";
+// final int GATEWAY_PORT = 80;
+// final boolean SECURE = false;
+// BlockchainServiceFactory serviceFactory = BlockchainServiceFactory.connect(GATEWAY_IP, GATEWAY_PORT, SECURE,
+// CLIENT_CERT);
+// BlockchainTransactionService service = serviceFactory.getBlockchainService();
+//
+// HashDigest ledgerHash = getLedgerHash();
+// // 在本地定义注册账号的 TX;
+// TransactionTemplate txTemp = service.newTransaction(ledgerHash);
+//
+// // --------------------------------------
+// // 配置账户的权限;
+// String walletAccount = "Kjfe8832hfa9jjjJJDkshrFjksjdlkfj93F==";
+// String user1 = "MMMEy902jkjjJJDkshreGeasdfassdfajjf==";
+// String user2 = "Kjfe8832hfa9jjjJJDkshrFjksjdlkfj93F==";
+// // 配置:
+// // “状态数据的写入权限”的阈值为 100;
+// // 需要 user1、user2 两个账户的联合签名才能写入;
+// // 当前账户仅用于表示一个业务钱包,禁止自身的写入权限,只能由业务角色的账户才能操作;
+//
+//
+//
+// txTemp.configPrivilege(walletAccount).setThreshhold(PrivilegeType.STATE_WRITE, 100)
+// .enable(PrivilegeType.STATE_WRITE, user1, 50).enable(PrivilegeType.STATE_WRITE, user2, 50)
+// .disable(PrivilegeType.STATE_WRITE, walletAccount);
+// // --------------------------------------
+//
+// // TX 准备就绪;
+// PreparedTransaction prepTx = txTemp.prepare();
+//
+// // 使用私钥进行签名;
+// BlockchainKeyPair sponsorKey = getSponsorKey();
+// prepTx.sign(sponsorKey);
+//
+// // 提交交易;
+// prepTx.commit();
+// }
+//
+// private static HashDigest getLedgerHash() {
+// // TODO Init ledger hash;
+// return null;
+// }
+//
+// private static BlockchainKeyPair getSponsorKey() {
+// // TODO Auto-generated method stub
+// return null;
+// }
+
+}
diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Query.java b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Query.java
index a3e44d95..6d81393d 100644
--- a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Query.java
+++ b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Query.java
@@ -1,86 +1,86 @@
-package com.jd.blockchain.sdk.samples;
-
-import com.jd.blockchain.crypto.Crypto;
-import com.jd.blockchain.crypto.HashDigest;
-import com.jd.blockchain.ledger.BlockchainKeyGenerator;
-import com.jd.blockchain.ledger.BlockchainKeypair;
-import com.jd.blockchain.ledger.TypedKVEntry;
-import com.jd.blockchain.ledger.LedgerBlock;
-import com.jd.blockchain.ledger.LedgerTransaction;
-import com.jd.blockchain.ledger.Transaction;
-import com.jd.blockchain.sdk.BlockchainService;
-import com.jd.blockchain.sdk.client.GatewayServiceFactory;
-import com.jd.blockchain.utils.net.NetworkAddress;
-
-/**
- * 演示区块链信息查询的过程;
- *
- * @author huanghaiquan
- *
- */
-public class SDKDemo_Query {
-
- public static BlockchainKeypair CLIENT_CERT = BlockchainKeyGenerator.getInstance().generate("ED25519");
-
- public static final HashDigest LEDGER_HASH = Crypto.getHashFunction("SHA256")
- .hash("xkxjcioewfqwe".getBytes());
-
- /**
- * 演示合约执行的过程;
- */
- public static void demoContract() {
- // 区块链共识域;
- String realm = "SUPPLY_CHAIN_ALLIANCE";
- // 节点地址列表;
- NetworkAddress[] peerAddrs = { new NetworkAddress("192.168.10.10", 8080),
- new NetworkAddress("192.168.10.11", 8080), new NetworkAddress("192.168.10.12", 8080),
- new NetworkAddress("192.168.10.13", 8080) };
-
- // 网关客户端编号;
- int gatewayId = 1001; // 客户端的认证账户;
- // 账本地址;
- String ledgerAddress = "ffkjhkeqwiuhivnsh3298josijdocaijsda==";
- String clientAddress = "kkjsafieweqEkadsfaslkdslkae998232jojf==";
- String privKey = "safefsd32q34vdsvs";
- // 创建服务代理;
- final String GATEWAY_IP = "127.0.0.1";
- final int GATEWAY_PORT = 80;
- final boolean SECURE = false;
- GatewayServiceFactory serviceFactory = GatewayServiceFactory.connect(GATEWAY_IP, GATEWAY_PORT, SECURE,
- CLIENT_CERT);
- BlockchainService service = serviceFactory.getBlockchainService();
-
- // 查询区块信息;
- // 区块高度;
- long ledgerNumber = service.getLedger(LEDGER_HASH).getLatestBlockHeight();
- // 最新区块;
- LedgerBlock latestBlock = service.getBlock(LEDGER_HASH, ledgerNumber);
- // 区块中的交易的数量;
- long txCount = service.getTransactionCount(LEDGER_HASH, latestBlock.getHash());
- // 获取交易列表;
- LedgerTransaction[] txList = service.getTransactions(LEDGER_HASH, ledgerNumber, 0, 100);
-
- // 根据交易的 hash 获得交易;注:客户端生成 PrepareTransaction 时得到交易hash;
- HashDigest txHash = txList[0].getTransactionContent().getHash();
- Transaction tx = service.getTransactionByContentHash(LEDGER_HASH, txHash);
-
- // 获取数据;
- String commerceAccount = "GGhhreGeasdfasfUUfehf9932lkae99ds66jf==";
- String[] objKeys = new String[] { "x001", "x002" };
- TypedKVEntry[] kvData = service.getDataEntries(LEDGER_HASH, commerceAccount, objKeys);
-
- long payloadVersion = kvData[0].getVersion();
-
-// boolean exist = service.containState(LEDGER_HASH, commerceAccount, "x003");
-
- // 按条件查询;
- // 1、从保存会员信息的账户地址查询;
-// String condition = "female = true AND age > 18 AND address.city = 'beijing'";
-// String memberInfoAccountAddress = "kkf2io39823jfIjfiIRWKQj30203fx==";
-// StateMap memberInfo = service.queryObject(LEDGER_HASH, memberInfoAccountAddress, condition);
-//
-// // 2、从保存会员信息的账户地址查询;
-// Map memberInfoWithAccounts = service.queryObject(LEDGER_HASH, condition);
- }
-
-}
+package com.jd.blockchain.sdk.samples;
+
+import com.jd.blockchain.crypto.Crypto;
+import com.jd.blockchain.crypto.HashDigest;
+import com.jd.blockchain.ledger.BlockchainKeyGenerator;
+import com.jd.blockchain.ledger.BlockchainKeypair;
+import com.jd.blockchain.ledger.TypedKVEntry;
+import com.jd.blockchain.ledger.LedgerBlock;
+import com.jd.blockchain.ledger.LedgerTransaction;
+import com.jd.blockchain.ledger.Transaction;
+import com.jd.blockchain.sdk.BlockchainService;
+import com.jd.blockchain.sdk.client.GatewayServiceFactory;
+import com.jd.blockchain.utils.net.NetworkAddress;
+
+/**
+ * 演示区块链信息查询的过程;
+ *
+ * @author huanghaiquan
+ *
+ */
+public class SDKDemo_Query {
+
+ public static BlockchainKeypair CLIENT_CERT = BlockchainKeyGenerator.getInstance().generate("ED25519");
+
+ public static final HashDigest LEDGER_HASH = Crypto.getHashFunction("SHA256")
+ .hash("xkxjcioewfqwe".getBytes());
+
+ /**
+ * 演示合约执行的过程;
+ */
+ public static void demoContract() {
+ // 区块链共识域;
+ String realm = "SUPPLY_CHAIN_ALLIANCE";
+ // 节点地址列表;
+ NetworkAddress[] peerAddrs = { new NetworkAddress("192.168.10.10", 8080),
+ new NetworkAddress("192.168.10.11", 8080), new NetworkAddress("192.168.10.12", 8080),
+ new NetworkAddress("192.168.10.13", 8080) };
+
+ // 网关客户端编号;
+ int gatewayId = 1001; // 客户端的认证账户;
+ // 账本地址;
+ String ledgerAddress = "ffkjhkeqwiuhivnsh3298josijdocaijsda==";
+ String clientAddress = "kkjsafieweqEkadsfaslkdslkae998232jojf==";
+ String privKey = "safefsd32q34vdsvs";
+ // 创建服务代理;
+ final String GATEWAY_IP = "127.0.0.1";
+ final int GATEWAY_PORT = 80;
+ final boolean SECURE = false;
+ GatewayServiceFactory serviceFactory = GatewayServiceFactory.connect(GATEWAY_IP, GATEWAY_PORT, SECURE,
+ CLIENT_CERT);
+ BlockchainService service = serviceFactory.getBlockchainService();
+
+ // 查询区块信息;
+ // 区块高度;
+ long ledgerNumber = service.getLedger(LEDGER_HASH).getLatestBlockHeight();
+ // 最新区块;
+ LedgerBlock latestBlock = service.getBlock(LEDGER_HASH, ledgerNumber);
+ // 区块中的交易的数量;
+ long txCount = service.getTransactionCount(LEDGER_HASH, latestBlock.getHash());
+ // 获取交易列表;
+ LedgerTransaction[] txList = service.getTransactions(LEDGER_HASH, ledgerNumber, 0, 100);
+
+ // 根据交易的 hash 获得交易;注:客户端生成 PrepareTransaction 时得到交易hash;
+ HashDigest txHash = txList[0].getTransactionContent().getHash();
+ Transaction tx = service.getTransactionByContentHash(LEDGER_HASH, txHash);
+
+ // 获取数据;
+ String commerceAccount = "GGhhreGeasdfasfUUfehf9932lkae99ds66jf==";
+ String[] objKeys = new String[] { "x001", "x002" };
+ TypedKVEntry[] kvData = service.getDataEntries(LEDGER_HASH, commerceAccount, objKeys);
+
+ long payloadVersion = kvData[0].getVersion();
+
+// boolean exist = service.containState(LEDGER_HASH, commerceAccount, "x003");
+
+ // 按条件查询;
+ // 1、从保存会员信息的账户地址查询;
+// String condition = "female = true AND age > 18 AND address.city = 'beijing'";
+// String memberInfoAccountAddress = "kkf2io39823jfIjfiIRWKQj30203fx==";
+// StateMap memberInfo = service.queryObject(LEDGER_HASH, memberInfoAccountAddress, condition);
+//
+// // 2、从保存会员信息的账户地址查询;
+// Map memberInfoWithAccounts = service.queryObject(LEDGER_HASH, condition);
+ }
+
+}
diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterAccount.java b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterAccount.java
index 30de0042..07b84984 100644
--- a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterAccount.java
+++ b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterAccount.java
@@ -1,57 +1,57 @@
-package com.jd.blockchain.sdk.samples;
-
-import com.jd.blockchain.binaryproto.DataContractRegistry;
-import com.jd.blockchain.crypto.AsymmetricKeypair;
-import com.jd.blockchain.crypto.HashDigest;
-import com.jd.blockchain.ledger.*;
-import com.jd.blockchain.sdk.BlockchainService;
-import com.jd.blockchain.sdk.client.GatewayServiceFactory;
-import com.jd.blockchain.utils.ConsoleUtils;
-
-public class SDKDemo_RegisterAccount {
-
- public static void main(String[] args) {
-
- String GATEWAY_IPADDR = "127.0.0.1";
- int GATEWAY_PORT = 8081;
- if (args != null && args.length == 2) {
- GATEWAY_IPADDR = args[0];
- GATEWAY_PORT = Integer.parseInt(args[1]);
- }
-
- DataContractRegistry.register(TransactionContent.class);
- DataContractRegistry.register(TransactionContentBody.class);
- DataContractRegistry.register(TransactionRequest.class);
- DataContractRegistry.register(NodeRequest.class);
- DataContractRegistry.register(EndpointRequest.class);
- DataContractRegistry.register(TransactionResponse.class);
-
- BlockchainKeypair CLIENT_CERT = new BlockchainKeypair(SDKDemo_Params.pubKey0, SDKDemo_Params.privkey0);
- boolean SECURE = false;
- GatewayServiceFactory serviceFactory = GatewayServiceFactory.connect(GATEWAY_IPADDR, GATEWAY_PORT, SECURE,
- CLIENT_CERT);
- BlockchainService service = serviceFactory.getBlockchainService();
-
- HashDigest[] ledgerHashs = service.getLedgerHashs();
- // 在本地定义注册账号的 TX;
- TransactionTemplate txTemp = service.newTransaction(ledgerHashs[0]);
-
- //existed signer
- AsymmetricKeypair keyPair = new BlockchainKeypair(SDKDemo_Params.pubKey1, SDKDemo_Params.privkey1);
-
- BlockchainKeypair dataAcount = BlockchainKeyGenerator.getInstance().generate();
-
- // 注册
- txTemp.dataAccounts().register(dataAcount.getIdentity());
-
- // TX 准备就绪;
- PreparedTransaction prepTx = txTemp.prepare();
-
- prepTx.sign(keyPair);
-
- // 提交交易;
- TransactionResponse transactionResponse = prepTx.commit();
-
- ConsoleUtils.info("register dataaccount complete, result is [%s]", transactionResponse.isSuccess());
- }
-}
+package com.jd.blockchain.sdk.samples;
+
+import com.jd.blockchain.binaryproto.DataContractRegistry;
+import com.jd.blockchain.crypto.AsymmetricKeypair;
+import com.jd.blockchain.crypto.HashDigest;
+import com.jd.blockchain.ledger.*;
+import com.jd.blockchain.sdk.BlockchainService;
+import com.jd.blockchain.sdk.client.GatewayServiceFactory;
+import com.jd.blockchain.utils.ConsoleUtils;
+
+public class SDKDemo_RegisterAccount {
+
+ public static void main(String[] args) {
+
+ String GATEWAY_IPADDR = "127.0.0.1";
+ int GATEWAY_PORT = 8081;
+ if (args != null && args.length == 2) {
+ GATEWAY_IPADDR = args[0];
+ GATEWAY_PORT = Integer.parseInt(args[1]);
+ }
+
+ DataContractRegistry.register(TransactionContent.class);
+ DataContractRegistry.register(TransactionContentBody.class);
+ DataContractRegistry.register(TransactionRequest.class);
+ DataContractRegistry.register(NodeRequest.class);
+ DataContractRegistry.register(EndpointRequest.class);
+ DataContractRegistry.register(TransactionResponse.class);
+
+ BlockchainKeypair CLIENT_CERT = new BlockchainKeypair(SDKDemo_Params.pubKey0, SDKDemo_Params.privkey0);
+ boolean SECURE = false;
+ GatewayServiceFactory serviceFactory = GatewayServiceFactory.connect(GATEWAY_IPADDR, GATEWAY_PORT, SECURE,
+ CLIENT_CERT);
+ BlockchainService service = serviceFactory.getBlockchainService();
+
+ HashDigest[] ledgerHashs = service.getLedgerHashs();
+ // 在本地定义注册账号的 TX;
+ TransactionTemplate txTemp = service.newTransaction(ledgerHashs[0]);
+
+ //existed signer
+ AsymmetricKeypair keyPair = new BlockchainKeypair(SDKDemo_Params.pubKey1, SDKDemo_Params.privkey1);
+
+ BlockchainKeypair dataAcount = BlockchainKeyGenerator.getInstance().generate();
+
+ // 注册
+ txTemp.dataAccounts().register(dataAcount.getIdentity());
+
+ // TX 准备就绪;
+ PreparedTransaction prepTx = txTemp.prepare();
+
+ prepTx.sign(keyPair);
+
+ // 提交交易;
+ TransactionResponse transactionResponse = prepTx.commit();
+
+ ConsoleUtils.info("register dataaccount complete, result is [%s]", transactionResponse.isSuccess());
+ }
+}
diff --git a/source/storage/storage-redis/src/main/java/com/jd/blockchain/storage/service/impl/redis/JedisProperties.java b/source/storage/storage-redis/src/main/java/com/jd/blockchain/storage/service/impl/redis/JedisProperties.java
index 8536df26..8a60f079 100644
--- a/source/storage/storage-redis/src/main/java/com/jd/blockchain/storage/service/impl/redis/JedisProperties.java
+++ b/source/storage/storage-redis/src/main/java/com/jd/blockchain/storage/service/impl/redis/JedisProperties.java
@@ -1,35 +1,35 @@
-package com.jd.blockchain.storage.service.impl.redis;
-
-public class JedisProperties {
-
- private String host;
-
- private int port = 6379;
-
- private int db = 0;
-
- public String getHost() {
- return host;
- }
-
- public void setHost(String host) {
- this.host = host;
- }
-
- public int getPort() {
- return port;
- }
-
- public void setPort(int port) {
- this.port = port;
- }
-
- public int getDb() {
- return db;
- }
-
- public void setDb(int db) {
- this.db = db;
- }
-
-}
+package com.jd.blockchain.storage.service.impl.redis;
+
+public class JedisProperties {
+
+ private String host;
+
+ private int port = 6379;
+
+ private int db = 0;
+
+ public String getHost() {
+ return host;
+ }
+
+ public void setHost(String host) {
+ this.host = host;
+ }
+
+ public int getPort() {
+ return port;
+ }
+
+ public void setPort(int port) {
+ this.port = port;
+ }
+
+ public int getDb() {
+ return db;
+ }
+
+ public void setDb(int db) {
+ this.db = db;
+ }
+
+}
diff --git a/source/storage/storage-redis/src/main/java/com/jd/blockchain/storage/service/impl/redis/RedisStorageService.java b/source/storage/storage-redis/src/main/java/com/jd/blockchain/storage/service/impl/redis/RedisStorageService.java
index 787b77c5..06cef779 100644
--- a/source/storage/storage-redis/src/main/java/com/jd/blockchain/storage/service/impl/redis/RedisStorageService.java
+++ b/source/storage/storage-redis/src/main/java/com/jd/blockchain/storage/service/impl/redis/RedisStorageService.java
@@ -1,39 +1,39 @@
-package com.jd.blockchain.storage.service.impl.redis;
-
-import com.jd.blockchain.storage.service.ExPolicyKVStorage;
-import com.jd.blockchain.storage.service.KVStorageService;
-import com.jd.blockchain.storage.service.VersioningKVStorage;
-
-import redis.clients.jedis.Jedis;
-import redis.clients.jedis.JedisPool;
-
-public class RedisStorageService implements KVStorageService {
-
- private RedisExPolicyStorage exStorage;
-
- private RedisVerioningStorage verStorage;
-
- private JedisPool jedisPool;
-
- public RedisStorageService(JedisPool jedisPool) {
- this.jedisPool = jedisPool;
- this.exStorage = new RedisExPolicyStorage(jedisPool);
- this.verStorage = new RedisVerioningStorage(jedisPool);
- }
-
- @Override
- public ExPolicyKVStorage getExPolicyKVStorage() {
- return exStorage;
- }
-
- @Override
- public VersioningKVStorage getVersioningKVStorage() {
- return verStorage;
- }
-
- public void clearDB() {
- try (Jedis jedis = jedisPool.getResource()) {
- jedis.flushDB();
- }
- }
-}
+package com.jd.blockchain.storage.service.impl.redis;
+
+import com.jd.blockchain.storage.service.ExPolicyKVStorage;
+import com.jd.blockchain.storage.service.KVStorageService;
+import com.jd.blockchain.storage.service.VersioningKVStorage;
+
+import redis.clients.jedis.Jedis;
+import redis.clients.jedis.JedisPool;
+
+public class RedisStorageService implements KVStorageService {
+
+ private RedisExPolicyStorage exStorage;
+
+ private RedisVerioningStorage verStorage;
+
+ private JedisPool jedisPool;
+
+ public RedisStorageService(JedisPool jedisPool) {
+ this.jedisPool = jedisPool;
+ this.exStorage = new RedisExPolicyStorage(jedisPool);
+ this.verStorage = new RedisVerioningStorage(jedisPool);
+ }
+
+ @Override
+ public ExPolicyKVStorage getExPolicyKVStorage() {
+ return exStorage;
+ }
+
+ @Override
+ public VersioningKVStorage getVersioningKVStorage() {
+ return verStorage;
+ }
+
+ public void clearDB() {
+ try (Jedis jedis = jedisPool.getResource()) {
+ jedis.flushDB();
+ }
+ }
+}
diff --git a/source/storage/storage-redis/src/main/resources/META-INF/spring.factories b/source/storage/storage-redis/src/main/resources/META-INF/spring.factories
index c5a24b7e..58aec406 100644
--- a/source/storage/storage-redis/src/main/resources/META-INF/spring.factories
+++ b/source/storage/storage-redis/src/main/resources/META-INF/spring.factories
@@ -1,2 +1,2 @@
-org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
+org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.jd.blockchain.storage.service.impl.redis.RedisStorageConfiguration
\ No newline at end of file
diff --git a/source/storage/storage-rocksdb/src/main/java/com/jd/blockchain/storage/service/impl/rocksdb/RocksDBStorageService.java b/source/storage/storage-rocksdb/src/main/java/com/jd/blockchain/storage/service/impl/rocksdb/RocksDBStorageService.java
index db7b673c..e1fc5d17 100644
--- a/source/storage/storage-rocksdb/src/main/java/com/jd/blockchain/storage/service/impl/rocksdb/RocksDBStorageService.java
+++ b/source/storage/storage-rocksdb/src/main/java/com/jd/blockchain/storage/service/impl/rocksdb/RocksDBStorageService.java
@@ -1,30 +1,30 @@
-package com.jd.blockchain.storage.service.impl.rocksdb;
-
-import org.rocksdb.RocksDB;
-
-import com.jd.blockchain.storage.service.ExPolicyKVStorage;
-import com.jd.blockchain.storage.service.KVStorageService;
-import com.jd.blockchain.storage.service.VersioningKVStorage;
-
-public class RocksDBStorageService implements KVStorageService {
-
- private ExPolicyKVStorage exStorage;
-
- private VersioningKVStorage verStorage;
-
- public RocksDBStorageService(RocksDB db) {
- this.verStorage = new RocksDBVersioningStorage(db);
- this.exStorage = new RocksDBExPolicyStorage(new RocksDBVersioningStorage(db));
- }
-
- @Override
- public ExPolicyKVStorage getExPolicyKVStorage() {
- return exStorage;
- }
-
- @Override
- public VersioningKVStorage getVersioningKVStorage() {
- return verStorage;
- }
-
-}
+package com.jd.blockchain.storage.service.impl.rocksdb;
+
+import org.rocksdb.RocksDB;
+
+import com.jd.blockchain.storage.service.ExPolicyKVStorage;
+import com.jd.blockchain.storage.service.KVStorageService;
+import com.jd.blockchain.storage.service.VersioningKVStorage;
+
+public class RocksDBStorageService implements KVStorageService {
+
+ private ExPolicyKVStorage exStorage;
+
+ private VersioningKVStorage verStorage;
+
+ public RocksDBStorageService(RocksDB db) {
+ this.verStorage = new RocksDBVersioningStorage(db);
+ this.exStorage = new RocksDBExPolicyStorage(new RocksDBVersioningStorage(db));
+ }
+
+ @Override
+ public ExPolicyKVStorage getExPolicyKVStorage() {
+ return exStorage;
+ }
+
+ @Override
+ public VersioningKVStorage getVersioningKVStorage() {
+ return verStorage;
+ }
+
+}
diff --git a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/VersioningKVStorage.java b/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/VersioningKVStorage.java
index 980cc32c..b1f6a9a3 100644
--- a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/VersioningKVStorage.java
+++ b/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/VersioningKVStorage.java
@@ -1,81 +1,81 @@
-package com.jd.blockchain.storage.service;
-
-import com.jd.blockchain.utils.Bytes;
-import com.jd.blockchain.utils.DataEntry;
-
-/**
- * Versioning Key-Value Storage
- *
- *
- * One key in this storage has a version attribute, which starts from zero and
- * increased by 1 on it's value being updated.
- *
- *
- * The writing of a key must be specified a explict integer of it's latest
- * version at the executing moment.
- *
- *
- * @author huanghaiquan
- *
- */
-public interface VersioningKVStorage extends BatchStorageService {
-
- /**
- * Return the latest version entry associated the specified key;
- *
- * If the key doesn't exist, then return -1;
- *
- * @param key
- * @return
- */
- long getVersion(Bytes key);
-
- /**
- * Return the specified verson's entry;
- *
- * It will return the latest one if the version is -1;
- *
- * It will return null if the key or version not exist.
- *
- * @param key
- * @param version
- * @return
- */
- DataEntry getEntry(Bytes key, long version);
-
- /**
- * Return the specified verson's value;
- *
- * If the specified version of key doesn't exist, then return null;
- *
- * If the version is specified to -1, then return the latest version's
- * value;
- *
- * @param key
- * @param version
- * @return
- */
- byte[] get(Bytes key, long version);
-
- /**
- * Update the value of the key;
- *
- * If key exist, and the specified version equals to it's latest version, then the value will be
- * updated and version will be increased by 1;
- * If key not exist, and the specified version is -1, then the value will be
- * created and initialized it's version by 0;
- *
- * @param key
- * the key;
- * @param value
- * the new value to update if expected version match the actual
- * version;
- * @param version
- * the latest version expected;
- * @return The latest version entry after setting.
- * If the version checking fail, or concurrent confliction occur, then
- * return -1 as indication.
- */
- long set(Bytes key, byte[] value, long version);
-
+package com.jd.blockchain.storage.service;
+
+import com.jd.blockchain.utils.Bytes;
+import com.jd.blockchain.utils.DataEntry;
+
+/**
+ * Versioning Key-Value Storage
+ *
+ *
+ * One key in this storage has a version attribute, which starts from zero and
+ * increased by 1 on it's value being updated.
+ *
+ *
+ * The writing of a key must be specified a explict integer of it's latest
+ * version at the executing moment.
+ *
+ *
+ * @author huanghaiquan
+ *
+ */
+public interface VersioningKVStorage extends BatchStorageService {
+
+ /**
+ * Return the latest version entry associated the specified key;
+ *
+ * If the key doesn't exist, then return -1;
+ *
+ * @param key
+ * @return
+ */
+ long getVersion(Bytes key);
+
+ /**
+ * Return the specified verson's entry;
+ *
+ * It will return the latest one if the version is -1;
+ *
+ * It will return null if the key or version not exist.
+ *
+ * @param key
+ * @param version
+ * @return
+ */
+ DataEntry getEntry(Bytes key, long version);
+
+ /**
+ * Return the specified verson's value;
+ *
+ * If the specified version of key doesn't exist, then return null;
+ *
+ * If the version is specified to -1, then return the latest version's
+ * value;
+ *
+ * @param key
+ * @param version
+ * @return
+ */
+ byte[] get(Bytes key, long version);
+
+ /**
+ * Update the value of the key;
+ *
+ * If key exist, and the specified version equals to it's latest version, then the value will be
+ * updated and version will be increased by 1;
+ * If key not exist, and the specified version is -1, then the value will be
+ * created and initialized it's version by 0;
+ *
+ * @param key
+ * the key;
+ * @param value
+ * the new value to update if expected version match the actual
+ * version;
+ * @param version
+ * the latest version expected;
+ * @return The latest version entry after setting.
+ * If the version checking fail, or concurrent confliction occur, then
+ * return -1 as indication.
+ */
+ long set(Bytes key, byte[] value, long version);
+
}
\ No newline at end of file
diff --git a/source/test/pom.xml b/source/test/pom.xml
index 5219328f..d7854070 100644
--- a/source/test/pom.xml
+++ b/source/test/pom.xml
@@ -1,32 +1,32 @@
-
- 4.0.0
-
- com.jd.blockchain
- jdchain-root
- 1.1.2.RELEASE
-
- test
- pom
-
-
- test-consensus-client
- test-consensus-node
- test-ledger
- test-integration
-
-
-
-
-
- org.apache.maven.plugins
- maven-deploy-plugin
- 2.8.2
-
- true
-
-
-
-
+
+ 4.0.0
+
+ com.jd.blockchain
+ jdchain-root
+ 1.1.2.RELEASE
+
+ test
+ pom
+
+
+ test-consensus-client
+ test-consensus-node
+ test-ledger
+ test-integration
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-deploy-plugin
+ 2.8.2
+
+ true
+
+
+
+
\ No newline at end of file
diff --git a/source/test/test-consensus-client/src/main/java/test/perf/com/jd/blockchain/consensus/client/Settings.java b/source/test/test-consensus-client/src/main/java/test/perf/com/jd/blockchain/consensus/client/Settings.java
index a296249c..af0bceb8 100644
--- a/source/test/test-consensus-client/src/main/java/test/perf/com/jd/blockchain/consensus/client/Settings.java
+++ b/source/test/test-consensus-client/src/main/java/test/perf/com/jd/blockchain/consensus/client/Settings.java
@@ -1,142 +1,142 @@
-package test.perf.com.jd.blockchain.consensus.client;
-
-import org.springframework.boot.context.properties.ConfigurationProperties;
-import org.springframework.context.annotation.Configuration;
-
-import com.jd.blockchain.utils.io.ByteArray;
-
-/**
- * @author huanghaiquan
- *
- */
-@Configuration
-@ConfigurationProperties(prefix = "client")
-public class Settings {
-
- private String name;
-
- private ConsensusSetting consensus;
-
- public ByteArray getLedgerHash() {
- return ledgerHash;
- }
-
- public void setLedgerHash(ByteArray ledgerHash) {
- this.ledgerHash = ledgerHash;
- }
-
- private ByteArray ledgerHash;
-
- public ConsensusSetting getConsensus() {
- return consensus;
- }
-
- public void setConsensus(ConsensusSetting consensus) {
- this.consensus = consensus;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- // ===================================================================================================
- /**
- * 共识相关的参数设置;
- *
- * @author huanghaiquan
- *
- */
- public static class ConsensusSetting {
-
- /**
- * 本机用于共识的IP地址;
- */
- private String ip;
-
- /**
- * 本机用于共识的端口;
- */
- private int port;
-
- public ConsensusSetting() {
- }
-
- public ConsensusSetting(String ip, int port) {
- this.ip = ip;
- this.port = port;
- }
-
- private BftsmartSetting bftsmartConfig = new BftsmartSetting("config/system.config", "config/hosts.config");
-
- public String getIp() {
- return ip;
- }
-
- public void setIp(String ip) {
- this.ip = ip;
- }
-
- public int getPort() {
- return port;
- }
-
- public void setPort(int port) {
- this.port = port;
- }
-
- public BftsmartSetting getBftsmartConfig() {
- return bftsmartConfig;
- }
-
- public void setBftsmartConfig(BftsmartSetting bftsmartConfig) {
- this.bftsmartConfig = bftsmartConfig;
- }
-
- }
-
- public static class BftsmartSetting {
-
- private String hosts;
-
- private String system;
-
- private String home;
-
- public BftsmartSetting() {
- }
-
- public BftsmartSetting(String systemConfig, String hostsConfig) {
- this.system = systemConfig;
- this.hosts = hostsConfig;
- }
-
- public String getHosts() {
- return hosts;
- }
-
- public void setHosts(String hosts) {
- this.hosts = hosts;
- }
-
- public String getSystem() {
- return system;
- }
-
- public void setSystem(String system) {
- this.system = system;
- }
-
- public String getHome() {
- return home;
- }
-
- public void setHome(String home) {
- this.home = home;
- }
-
- }
-}
+package test.perf.com.jd.blockchain.consensus.client;
+
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Configuration;
+
+import com.jd.blockchain.utils.io.ByteArray;
+
+/**
+ * @author huanghaiquan
+ *
+ */
+@Configuration
+@ConfigurationProperties(prefix = "client")
+public class Settings {
+
+ private String name;
+
+ private ConsensusSetting consensus;
+
+ public ByteArray getLedgerHash() {
+ return ledgerHash;
+ }
+
+ public void setLedgerHash(ByteArray ledgerHash) {
+ this.ledgerHash = ledgerHash;
+ }
+
+ private ByteArray ledgerHash;
+
+ public ConsensusSetting getConsensus() {
+ return consensus;
+ }
+
+ public void setConsensus(ConsensusSetting consensus) {
+ this.consensus = consensus;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ // ===================================================================================================
+ /**
+ * 共识相关的参数设置;
+ *
+ * @author huanghaiquan
+ *
+ */
+ public static class ConsensusSetting {
+
+ /**
+ * 本机用于共识的IP地址;
+ */
+ private String ip;
+
+ /**
+ * 本机用于共识的端口;
+ */
+ private int port;
+
+ public ConsensusSetting() {
+ }
+
+ public ConsensusSetting(String ip, int port) {
+ this.ip = ip;
+ this.port = port;
+ }
+
+ private BftsmartSetting bftsmartConfig = new BftsmartSetting("config/system.config", "config/hosts.config");
+
+ public String getIp() {
+ return ip;
+ }
+
+ public void setIp(String ip) {
+ this.ip = ip;
+ }
+
+ public int getPort() {
+ return port;
+ }
+
+ public void setPort(int port) {
+ this.port = port;
+ }
+
+ public BftsmartSetting getBftsmartConfig() {
+ return bftsmartConfig;
+ }
+
+ public void setBftsmartConfig(BftsmartSetting bftsmartConfig) {
+ this.bftsmartConfig = bftsmartConfig;
+ }
+
+ }
+
+ public static class BftsmartSetting {
+
+ private String hosts;
+
+ private String system;
+
+ private String home;
+
+ public BftsmartSetting() {
+ }
+
+ public BftsmartSetting(String systemConfig, String hostsConfig) {
+ this.system = systemConfig;
+ this.hosts = hostsConfig;
+ }
+
+ public String getHosts() {
+ return hosts;
+ }
+
+ public void setHosts(String hosts) {
+ this.hosts = hosts;
+ }
+
+ public String getSystem() {
+ return system;
+ }
+
+ public void setSystem(String system) {
+ this.system = system;
+ }
+
+ public String getHome() {
+ return home;
+ }
+
+ public void setHome(String home) {
+ this.home = home;
+ }
+
+ }
+}
diff --git a/source/test/test-consensus-client/src/main/java/test/perf/com/jd/blockchain/consensus/client/WebConfiguration.java b/source/test/test-consensus-client/src/main/java/test/perf/com/jd/blockchain/consensus/client/WebConfiguration.java
index b43acb34..b99c161b 100644
--- a/source/test/test-consensus-client/src/main/java/test/perf/com/jd/blockchain/consensus/client/WebConfiguration.java
+++ b/source/test/test-consensus-client/src/main/java/test/perf/com/jd/blockchain/consensus/client/WebConfiguration.java
@@ -1,11 +1,11 @@
-package test.perf.com.jd.blockchain.consensus.client;
-
-import org.springframework.context.annotation.ComponentScan;
-import org.springframework.context.annotation.Configuration;
-
-@Configuration
-@ComponentScan
-public class WebConfiguration {
-
-}
-
+package test.perf.com.jd.blockchain.consensus.client;
+
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+@ComponentScan
+public class WebConfiguration {
+
+}
+
diff --git a/source/test/test-consensus-client/src/main/resources/application.properties b/source/test/test-consensus-client/src/main/resources/application.properties
index 6fdb220e..63feb453 100644
--- a/source/test/test-consensus-client/src/main/resources/application.properties
+++ b/source/test/test-consensus-client/src/main/resources/application.properties
@@ -1,28 +1,28 @@
-server.port=10010
-
-#server.ssl.key-store=classpath:mykeys.jks
-#server.ssl.key-store-password=abc123
-#server.ssl.key-password=abc123
-
-server.tomcat.accesslog.enabled=false
-
-debug=false
-
-#logging.file=logs/peer.log
-logging.level.com.jd.blockchain.peer=DEBUG
-logging.level.org.org.springframework=DEBUG
-
-spring.mvc.favicon.enabled=false
-
-
-
-client.name=peer[0]
-
-client.consensus.ip=127.0.0.1
-client.consensus.port=10000
-
-client.consensus.bftsmart-config.home=config
-client.consensus.bftsmart-config.system=config/system.config
-client.consensus.bftsmart-config.hosts=config/hosts.config
-
-
+server.port=10010
+
+#server.ssl.key-store=classpath:mykeys.jks
+#server.ssl.key-store-password=abc123
+#server.ssl.key-password=abc123
+
+server.tomcat.accesslog.enabled=false
+
+debug=false
+
+#logging.file=logs/peer.log
+logging.level.com.jd.blockchain.peer=DEBUG
+logging.level.org.org.springframework=DEBUG
+
+spring.mvc.favicon.enabled=false
+
+
+
+client.name=peer[0]
+
+client.consensus.ip=127.0.0.1
+client.consensus.port=10000
+
+client.consensus.bftsmart-config.home=config
+client.consensus.bftsmart-config.system=config/system.config
+client.consensus.bftsmart-config.hosts=config/hosts.config
+
+
diff --git a/source/test/test-consensus-node/config/bft-system.config b/source/test/test-consensus-node/config/bft-system.config
index ddf28b45..ada42b49 100644
--- a/source/test/test-consensus-node/config/bft-system.config
+++ b/source/test/test-consensus-node/config/bft-system.config
@@ -1,121 +1,121 @@
-# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-############################################
-####### Communication Configurations #######
-############################################
-
-#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value)
-#This parameter is not currently being used being used
-#system.authentication.hmacAlgorithm = HmacSHA1
-
-#Specify if the communication system should use a thread to send data (true or false)
-system.communication.useSenderThread = true
-
-#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments
-#and benchmarks, but must not be used in production systems.
-system.communication.defaultkeys = true
-
-############################################
-### Replication Algorithm Configurations ###
-############################################
-
-#Number of servers in the group
-system.servers.num = 4
-
-#Maximum number of faulty replicas
-system.servers.f = 1
-
-#Timeout to asking for a client request
-system.totalordermulticast.timeout = 2000
-
-
-#Maximum batch size (in number of messages)
-system.totalordermulticast.maxbatchsize = 400
-
-#Number of nonces (for non-determinism actions) generated
-system.totalordermulticast.nonces = 10
-
-#if verification of leader-generated timestamps are increasing
-#it can only be used on systems in which the network clocks
-#are synchronized
-system.totalordermulticast.verifyTimestamps = false
-
-#Quantity of messages that can be stored in the receive queue of the communication system
-system.communication.inQueueSize = 500000
-
-# Quantity of messages that can be stored in the send queue of each replica
-system.communication.outQueueSize = 500000
-
-#Set to 1 if SMaRt should use signatures, set to 0 if otherwise
-system.communication.useSignatures = 0
-
-#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise
-system.communication.useMACs = 1
-
-#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise
-system.debug = 0
-
-#Print information about the replica when it is shutdown
-system.shutdownhook = true
-
-############################################
-###### State Transfer Configurations #######
-############################################
-
-#Activate the state transfer protocol ('true' to activate, 'false' to de-activate)
-system.totalordermulticast.state_transfer = true
-
-#Maximum ahead-of-time message not discarded
-system.totalordermulticast.highMark = 10000
-
-#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered)
-system.totalordermulticast.revival_highMark = 10
-
-#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs
-system.totalordermulticast.timeout_highMark = 200
-
-############################################
-###### Log and Checkpoint Configurations ###
-############################################
-
-system.totalordermulticast.log = true
-system.totalordermulticast.log_parallel = false
-system.totalordermulticast.log_to_disk = false
-system.totalordermulticast.sync_log = false
-
-#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol)
-system.totalordermulticast.checkpoint_period = 1000
-system.totalordermulticast.global_checkpoint_period = 120000
-
-system.totalordermulticast.checkpoint_to_disk = false
-system.totalordermulticast.sync_ckp = false
-
-
-############################################
-###### Reconfiguration Configurations ######
-############################################
-
-#Replicas ID for the initial view, separated by a comma.
-# The number of replicas in this parameter should be equal to that specified in 'system.servers.num'
-system.initial.view = 0,1,2,3
-
-#The ID of the trust third party (TTP)
-system.ttp.id = 7002
-
-#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults
-system.bft = true
-
-#Custom View Storage;
-#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage
+# Copyright (c) 2007-2013 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+############################################
+####### Communication Configurations #######
+############################################
+
+#HMAC algorithm used to authenticate messages between processes (HmacMD5 is the default value)
+#This parameter is not currently being used being used
+#system.authentication.hmacAlgorithm = HmacSHA1
+
+#Specify if the communication system should use a thread to send data (true or false)
+system.communication.useSenderThread = true
+
+#Force all processes to use the same public/private keys pair and secret key. This is useful when deploying experiments
+#and benchmarks, but must not be used in production systems.
+system.communication.defaultkeys = true
+
+############################################
+### Replication Algorithm Configurations ###
+############################################
+
+#Number of servers in the group
+system.servers.num = 4
+
+#Maximum number of faulty replicas
+system.servers.f = 1
+
+#Timeout to asking for a client request
+system.totalordermulticast.timeout = 2000
+
+
+#Maximum batch size (in number of messages)
+system.totalordermulticast.maxbatchsize = 400
+
+#Number of nonces (for non-determinism actions) generated
+system.totalordermulticast.nonces = 10
+
+#if verification of leader-generated timestamps are increasing
+#it can only be used on systems in which the network clocks
+#are synchronized
+system.totalordermulticast.verifyTimestamps = false
+
+#Quantity of messages that can be stored in the receive queue of the communication system
+system.communication.inQueueSize = 500000
+
+# Quantity of messages that can be stored in the send queue of each replica
+system.communication.outQueueSize = 500000
+
+#Set to 1 if SMaRt should use signatures, set to 0 if otherwise
+system.communication.useSignatures = 0
+
+#Set to 1 if SMaRt should use MAC's, set to 0 if otherwise
+system.communication.useMACs = 1
+
+#Set to 1 if SMaRt should use the standard output to display debug messages, set to 0 if otherwise
+system.debug = 0
+
+#Print information about the replica when it is shutdown
+system.shutdownhook = true
+
+############################################
+###### State Transfer Configurations #######
+############################################
+
+#Activate the state transfer protocol ('true' to activate, 'false' to de-activate)
+system.totalordermulticast.state_transfer = true
+
+#Maximum ahead-of-time message not discarded
+system.totalordermulticast.highMark = 10000
+
+#Maximum ahead-of-time message not discarded when the replica is still on EID 0 (after which the state transfer is triggered)
+system.totalordermulticast.revival_highMark = 10
+
+#Number of ahead-of-time messages necessary to trigger the state transfer after a request timeout occurs
+system.totalordermulticast.timeout_highMark = 200
+
+############################################
+###### Log and Checkpoint Configurations ###
+############################################
+
+system.totalordermulticast.log = true
+system.totalordermulticast.log_parallel = false
+system.totalordermulticast.log_to_disk = false
+system.totalordermulticast.sync_log = false
+
+#Period at which BFT-SMaRt requests the state to the application (for the state transfer state protocol)
+system.totalordermulticast.checkpoint_period = 1000
+system.totalordermulticast.global_checkpoint_period = 120000
+
+system.totalordermulticast.checkpoint_to_disk = false
+system.totalordermulticast.sync_ckp = false
+
+
+############################################
+###### Reconfiguration Configurations ######
+############################################
+
+#Replicas ID for the initial view, separated by a comma.
+# The number of replicas in this parameter should be equal to that specified in 'system.servers.num'
+system.initial.view = 0,1,2,3
+
+#The ID of the trust third party (TTP)
+system.ttp.id = 7002
+
+#This sets if the system will function in Byzantine or crash-only mode. Set to "true" to support Byzantine faults
+system.bft = true
+
+#Custom View Storage;
+#view.storage.handler=bftsmart.reconfiguration.views.DefaultViewStorage
diff --git a/source/test/test-consensus-node/src/main/java/test/perf/com/jd/blockchain/consensus/node/Settings.java b/source/test/test-consensus-node/src/main/java/test/perf/com/jd/blockchain/consensus/node/Settings.java
index c7f75903..1847308d 100644
--- a/source/test/test-consensus-node/src/main/java/test/perf/com/jd/blockchain/consensus/node/Settings.java
+++ b/source/test/test-consensus-node/src/main/java/test/perf/com/jd/blockchain/consensus/node/Settings.java
@@ -1,57 +1,57 @@
-package test.perf.com.jd.blockchain.consensus.node;
-
-import org.springframework.boot.context.properties.ConfigurationProperties;
-import org.springframework.context.annotation.Configuration;
-
-/**
- * @author huanghaiquan
- *
- */
-@Configuration
-@ConfigurationProperties(prefix = "bft")
-public class Settings {
-
- private String name;
-
- private String systemConfig = "config/system.config";
-
- private String nodesConfig = "config/hosts.config";
-
-// private String runtimeHome = "./runtime";
-
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- // ===================================================================================================
-
- public String getSystemConfig() {
- return systemConfig;
- }
-
- public void setSystemConfig(String systemConfig) {
- this.systemConfig = systemConfig;
- }
-
- public String getNodesConfig() {
- return nodesConfig;
- }
-
- public void setNodesConfig(String nodesConfig) {
- this.nodesConfig = nodesConfig;
- }
-
-// public String getRuntimeHome() {
-// return runtimeHome;
-// }
-//
-// public void setRuntimeHome(String runtimeHome) {
-// this.runtimeHome = runtimeHome;
-// }
-
-}
+package test.perf.com.jd.blockchain.consensus.node;
+
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Configuration;
+
+/**
+ * @author huanghaiquan
+ *
+ */
+@Configuration
+@ConfigurationProperties(prefix = "bft")
+public class Settings {
+
+ private String name;
+
+ private String systemConfig = "config/system.config";
+
+ private String nodesConfig = "config/hosts.config";
+
+// private String runtimeHome = "./runtime";
+
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ // ===================================================================================================
+
+ public String getSystemConfig() {
+ return systemConfig;
+ }
+
+ public void setSystemConfig(String systemConfig) {
+ this.systemConfig = systemConfig;
+ }
+
+ public String getNodesConfig() {
+ return nodesConfig;
+ }
+
+ public void setNodesConfig(String nodesConfig) {
+ this.nodesConfig = nodesConfig;
+ }
+
+// public String getRuntimeHome() {
+// return runtimeHome;
+// }
+//
+// public void setRuntimeHome(String runtimeHome) {
+// this.runtimeHome = runtimeHome;
+// }
+
+}
diff --git a/source/test/test-consensus-node/src/main/java/test/perf/com/jd/blockchain/consensus/node/WebConfiguration.java b/source/test/test-consensus-node/src/main/java/test/perf/com/jd/blockchain/consensus/node/WebConfiguration.java
index 34a4843a..1abe783b 100644
--- a/source/test/test-consensus-node/src/main/java/test/perf/com/jd/blockchain/consensus/node/WebConfiguration.java
+++ b/source/test/test-consensus-node/src/main/java/test/perf/com/jd/blockchain/consensus/node/WebConfiguration.java
@@ -1,11 +1,11 @@
-package test.perf.com.jd.blockchain.consensus.node;
-
-import org.springframework.context.annotation.ComponentScan;
-import org.springframework.context.annotation.Configuration;
-
-@Configuration
-@ComponentScan
-public class WebConfiguration {
-
-}
-
+package test.perf.com.jd.blockchain.consensus.node;
+
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+@ComponentScan
+public class WebConfiguration {
+
+}
+
diff --git a/source/test/test-consensus-node/src/main/resources/application.properties b/source/test/test-consensus-node/src/main/resources/application.properties
index bbe35d4d..626dd740 100644
--- a/source/test/test-consensus-node/src/main/resources/application.properties
+++ b/source/test/test-consensus-node/src/main/resources/application.properties
@@ -1,19 +1,19 @@
-server.port=9000
-#server.ssl.key-store=classpath:mykeys.jks
-#server.ssl.key-store-password=abc123
-#server.ssl.key-password=abc123
-
-server.tomcat.accesslog.enabled=false
-
-debug=false
-
-#logging.file=logs/peer.log
-logging.level.com.jd.blockchain.peer=DEBUG
-logging.level.org.org.springframework=DEBUG
-
-spring.mvc.favicon.enabled=false
-
-bft.name=node-0
-bft.nodes-config=config/hosts.config
-bft.system-config=config/system.config
+server.port=9000
+#server.ssl.key-store=classpath:mykeys.jks
+#server.ssl.key-store-password=abc123
+#server.ssl.key-password=abc123
+
+server.tomcat.accesslog.enabled=false
+
+debug=false
+
+#logging.file=logs/peer.log
+logging.level.com.jd.blockchain.peer=DEBUG
+logging.level.org.org.springframework=DEBUG
+
+spring.mvc.favicon.enabled=false
+
+bft.name=node-0
+bft.nodes-config=config/hosts.config
+bft.system-config=config/system.config
bft.runtime-home=config
\ No newline at end of file
diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/DecisionRequestBodyConverter.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/DecisionRequestBodyConverter.java
index 5c7c72e2..e4483c15 100644
--- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/DecisionRequestBodyConverter.java
+++ b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/DecisionRequestBodyConverter.java
@@ -1,20 +1,20 @@
-package com.jd.blockchain.tools.initializer.web;
-
-import java.io.IOException;
-import java.io.OutputStream;
-
-import com.jd.blockchain.binaryproto.BinaryProtocol;
-import com.jd.blockchain.ledger.core.LedgerInitDecision;
-import com.jd.blockchain.utils.http.RequestBodyConverter;
-
-public class DecisionRequestBodyConverter implements RequestBodyConverter {
-
- @Override
- public void write(Object param, OutputStream out) throws IOException {
- if (param instanceof LedgerInitDecision) {
- BinaryProtocol.encode(param, LedgerInitDecision.class, out);
- return;
- }
- }
-
+package com.jd.blockchain.tools.initializer.web;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+import com.jd.blockchain.binaryproto.BinaryProtocol;
+import com.jd.blockchain.ledger.core.LedgerInitDecision;
+import com.jd.blockchain.utils.http.RequestBodyConverter;
+
+public class DecisionRequestBodyConverter implements RequestBodyConverter {
+
+ @Override
+ public void write(Object param, OutputStream out) throws IOException {
+ if (param instanceof LedgerInitDecision) {
+ BinaryProtocol.encode(param, LedgerInitDecision.class, out);
+ return;
+ }
+ }
+
}
\ No newline at end of file
diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/DecisionResponseConverter.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/DecisionResponseConverter.java
index e9d3017d..862ff491 100644
--- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/DecisionResponseConverter.java
+++ b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/DecisionResponseConverter.java
@@ -1,23 +1,23 @@
-package com.jd.blockchain.tools.initializer.web;
-
-import java.io.InputStream;
-
-import com.jd.blockchain.binaryproto.BinaryProtocol;
-import com.jd.blockchain.ledger.LedgerInitException;
-import com.jd.blockchain.utils.http.HttpServiceContext;
-import com.jd.blockchain.utils.http.ResponseConverter;
-import com.jd.blockchain.utils.http.agent.ServiceRequest;
-
-public class DecisionResponseConverter implements ResponseConverter {
-
- @Override
- public Object getResponse(ServiceRequest request, InputStream responseStream, HttpServiceContext serviceContext)
- throws Exception {
- LedgerInitResponse resp = LedgerInitResponse.resolve(responseStream);
- if (resp.isError()) {
- throw new LedgerInitException("Error occurred at remote participant! --" + resp.getErrorMessage());
- }
- return BinaryProtocol.decode(resp.getData());
- }
-
-}
+package com.jd.blockchain.tools.initializer.web;
+
+import java.io.InputStream;
+
+import com.jd.blockchain.binaryproto.BinaryProtocol;
+import com.jd.blockchain.ledger.LedgerInitException;
+import com.jd.blockchain.utils.http.HttpServiceContext;
+import com.jd.blockchain.utils.http.ResponseConverter;
+import com.jd.blockchain.utils.http.agent.ServiceRequest;
+
+public class DecisionResponseConverter implements ResponseConverter {
+
+ @Override
+ public Object getResponse(ServiceRequest request, InputStream responseStream, HttpServiceContext serviceContext)
+ throws Exception {
+ LedgerInitResponse resp = LedgerInitResponse.resolve(responseStream);
+ if (resp.isError()) {
+ throw new LedgerInitException("Error occurred at remote participant! --" + resp.getErrorMessage());
+ }
+ return BinaryProtocol.decode(resp.getData());
+ }
+
+}
diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/InitServiceExceptionHandler.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/InitServiceExceptionHandler.java
index 3a7d295f..753d3d33 100644
--- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/InitServiceExceptionHandler.java
+++ b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/InitServiceExceptionHandler.java
@@ -1,26 +1,26 @@
-package com.jd.blockchain.tools.initializer.web;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.web.bind.annotation.ExceptionHandler;
-import org.springframework.web.bind.annotation.ResponseBody;
-import org.springframework.web.bind.annotation.RestControllerAdvice;
-
-/**
- * 全局异常处理类
- */
-@RestControllerAdvice
-public class InitServiceExceptionHandler {
- protected final Logger logger = LoggerFactory.getLogger(getClass());
-
- @ExceptionHandler(value = Exception.class)
- @ResponseBody
- public LedgerInitResponse json(HttpServletRequest req, Exception ex) {
-// logger.error("Error of web controllers! --" + ex.getMessage(), ex);
- System.out.println("[InitServiceExceptionHandler] Error of web controllers! --" + ex.getMessage());
- return LedgerInitResponse.error(ex.getMessage());
- }
-
+package com.jd.blockchain.tools.initializer.web;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+
+/**
+ * 全局异常处理类
+ */
+@RestControllerAdvice
+public class InitServiceExceptionHandler {
+ protected final Logger logger = LoggerFactory.getLogger(getClass());
+
+ @ExceptionHandler(value = Exception.class)
+ @ResponseBody
+ public LedgerInitResponse json(HttpServletRequest req, Exception ex) {
+// logger.error("Error of web controllers! --" + ex.getMessage(), ex);
+ System.out.println("[InitServiceExceptionHandler] Error of web controllers! --" + ex.getMessage());
+ return LedgerInitResponse.error(ex.getMessage());
+ }
+
}
\ No newline at end of file
diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/InitWebSecurityConfiguration.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/InitWebSecurityConfiguration.java
index cef38324..f997679a 100644
--- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/InitWebSecurityConfiguration.java
+++ b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/InitWebSecurityConfiguration.java
@@ -1,19 +1,19 @@
-package com.jd.blockchain.tools.initializer.web;
-
-import org.springframework.context.annotation.Configuration;
-import org.springframework.security.config.annotation.web.builders.HttpSecurity;
-import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
-import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
-
-@Configuration
-@EnableWebSecurity
-public class InitWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
-
-
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.authorizeRequests().anyRequest().permitAll();
- http.csrf().disable();
- }
-
-}
+package com.jd.blockchain.tools.initializer.web;
+
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+
+@Configuration
+@EnableWebSecurity
+public class InitWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
+
+
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http.authorizeRequests().anyRequest().permitAll();
+ http.csrf().disable();
+ }
+
+}
diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/InitWebServerConfiguration.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/InitWebServerConfiguration.java
index 69195dad..a4fed1f2 100644
--- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/InitWebServerConfiguration.java
+++ b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/InitWebServerConfiguration.java
@@ -1,38 +1,38 @@
-package com.jd.blockchain.tools.initializer.web;
-
-import java.util.List;
-
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.ComponentScan;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.http.converter.HttpMessageConverter;
-import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
-
-import com.jd.blockchain.ledger.core.LedgerManager;
-import com.jd.blockchain.utils.io.ByteArray;
-import com.jd.blockchain.utils.serialize.json.JSONSerializeUtils;
-
-@Configuration
-@ComponentScan
-public class InitWebServerConfiguration extends WebMvcConfigurerAdapter {
- static {
- JSONSerializeUtils.disableCircularReferenceDetect();
- JSONSerializeUtils.configStringSerializer(ByteArray.class);
- }
-
- @Override
- public void extendMessageConverters(List> converters) {
- converters.add(0, new LedgerInitMessageConverter());
- }
-
- @Bean
- public InitConsensusServiceFactory initCsServiceFactory() {
- return new HttpInitConsensServiceFactory();
- }
-
- @Bean
- public LedgerManager getLedgerManager() {
- return new LedgerManager();
- }
-
-}
+package com.jd.blockchain.tools.initializer.web;
+
+import java.util.List;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.http.converter.HttpMessageConverter;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
+
+import com.jd.blockchain.ledger.core.LedgerManager;
+import com.jd.blockchain.utils.io.ByteArray;
+import com.jd.blockchain.utils.serialize.json.JSONSerializeUtils;
+
+@Configuration
+@ComponentScan
+public class InitWebServerConfiguration extends WebMvcConfigurerAdapter {
+ static {
+ JSONSerializeUtils.disableCircularReferenceDetect();
+ JSONSerializeUtils.configStringSerializer(ByteArray.class);
+ }
+
+ @Override
+ public void extendMessageConverters(List> converters) {
+ converters.add(0, new LedgerInitMessageConverter());
+ }
+
+ @Bean
+ public InitConsensusServiceFactory initCsServiceFactory() {
+ return new HttpInitConsensServiceFactory();
+ }
+
+ @Bean
+ public LedgerManager getLedgerManager() {
+ return new LedgerManager();
+ }
+
+}
diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitMessageConverter.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitMessageConverter.java
index 6361d6a1..d43d581f 100644
--- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitMessageConverter.java
+++ b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitMessageConverter.java
@@ -1,113 +1,113 @@
-package com.jd.blockchain.tools.initializer.web;
-
-import java.io.IOException;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.springframework.http.HttpInputMessage;
-import org.springframework.http.HttpOutputMessage;
-import org.springframework.http.MediaType;
-import org.springframework.http.converter.HttpMessageConverter;
-import org.springframework.http.converter.HttpMessageNotReadableException;
-import org.springframework.http.converter.HttpMessageNotWritableException;
-
-import com.jd.blockchain.binaryproto.BinaryProtocol;
-import com.jd.blockchain.binaryproto.DataContractRegistry;
-import com.jd.blockchain.crypto.SignatureDigest;
-import com.jd.blockchain.ledger.core.LedgerInitDecision;
-import com.jd.blockchain.ledger.core.LedgerInitProposal;
-import com.jd.blockchain.ledger.core.LedgerInitProposalData;
-import com.jd.blockchain.utils.io.BytesUtils;
-
-/**
- * 针对二进制对象的序列化和反序列化的 HTTP 消息转换器;
- *
- * @author huanghaiquan
- *
- */
-public class LedgerInitMessageConverter implements HttpMessageConverter {
-
- public static final String CONTENT_TYPE_VALUE = "application/bin-obj";
-
- public static final MediaType CONTENT_TYPE = MediaType.valueOf(CONTENT_TYPE_VALUE);
-
- private static final List SUPPORTED_MEDIA_TYPES = Collections.singletonList(CONTENT_TYPE);
-
- private static final Map, Class>> SUPPORTED_CONTRACT_TYPES = new HashMap<>();
-
- static {
- DataContractRegistry.register(LedgerInitProposal.class);
- DataContractRegistry.register(LedgerInitDecision.class);
-
- SUPPORTED_CONTRACT_TYPES.put(LedgerInitProposal.class, LedgerInitProposalData.class);
- SUPPORTED_CONTRACT_TYPES.put(LedgerInitDecision.class, LedgerInitDecisionData.class);
-
- // SUPPORTED_CONTRACT_TYPES.add(LedgerInitResponse.class);
- // DataContractRegistry.register(LedgerInitResponse.class);
- }
-
- private boolean isSupported(Class> clazz) {
- return getContractType(clazz) != null;
- }
-
- private Class> getContractType(Class> clazz) {
- for (Class> itf : SUPPORTED_CONTRACT_TYPES.keySet()) {
- if (itf.isAssignableFrom(clazz)) {
- return itf;
- }
- }
- return null;
- }
-
- @Override
- public boolean canRead(Class> clazz, MediaType mediaType) {
- return CONTENT_TYPE.includes(mediaType)
- && (clazz.isPrimitive() || SignatureDigest.class == clazz || isSupported(clazz));
- }
-
- @Override
- public boolean canWrite(Class> clazz, MediaType mediaType) {
- return CONTENT_TYPE.includes(mediaType) && (clazz.isPrimitive() || LedgerInitResponse.class.isAssignableFrom(clazz) || isSupported(clazz));
- }
-
- @Override
- public List getSupportedMediaTypes() {
- return SUPPORTED_MEDIA_TYPES;
- }
-
- @Override
- public Object read(Class extends Object> clazz, HttpInputMessage inputMessage)
- throws IOException, HttpMessageNotReadableException {
- if (SignatureDigest.class == clazz) {
- byte[] signDigestBytes = BytesUtils.copyToBytes(inputMessage.getBody());
- return new SignatureDigest(signDigestBytes);
- }
-
- Class> contractType = getContractType(clazz);
- Class> implType = SUPPORTED_CONTRACT_TYPES.get(contractType);
- return BinaryProtocol.decode(inputMessage.getBody());
- }
-
- @Override
- public void write(Object t, MediaType contentType, HttpOutputMessage outputMessage)
- throws IOException, HttpMessageNotWritableException {
- LedgerInitResponse resp;
- if (t == null) {
- resp = LedgerInitResponse.success(null);
- } else if (t instanceof LedgerInitResponse) {
- resp = (LedgerInitResponse) t;
- outputMessage.getBody().write(resp.toBytes());
- } else {
- Class> contractType = getContractType(t.getClass());
- if (contractType == null) {
- throw new IllegalStateException("Unsupported type[" + t.getClass().getName() + "]!");
- }
- byte[] data = BinaryProtocol.encode(t, contractType);
- resp = LedgerInitResponse.success(data);
- outputMessage.getBody().write(resp.toBytes());
- }
- }
-
-}
+package com.jd.blockchain.tools.initializer.web;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.springframework.http.HttpInputMessage;
+import org.springframework.http.HttpOutputMessage;
+import org.springframework.http.MediaType;
+import org.springframework.http.converter.HttpMessageConverter;
+import org.springframework.http.converter.HttpMessageNotReadableException;
+import org.springframework.http.converter.HttpMessageNotWritableException;
+
+import com.jd.blockchain.binaryproto.BinaryProtocol;
+import com.jd.blockchain.binaryproto.DataContractRegistry;
+import com.jd.blockchain.crypto.SignatureDigest;
+import com.jd.blockchain.ledger.core.LedgerInitDecision;
+import com.jd.blockchain.ledger.core.LedgerInitProposal;
+import com.jd.blockchain.ledger.core.LedgerInitProposalData;
+import com.jd.blockchain.utils.io.BytesUtils;
+
+/**
+ * 针对二进制对象的序列化和反序列化的 HTTP 消息转换器;
+ *
+ * @author huanghaiquan
+ *
+ */
+public class LedgerInitMessageConverter implements HttpMessageConverter {
+
+ public static final String CONTENT_TYPE_VALUE = "application/bin-obj";
+
+ public static final MediaType CONTENT_TYPE = MediaType.valueOf(CONTENT_TYPE_VALUE);
+
+ private static final List SUPPORTED_MEDIA_TYPES = Collections.singletonList(CONTENT_TYPE);
+
+ private static final Map, Class>> SUPPORTED_CONTRACT_TYPES = new HashMap<>();
+
+ static {
+ DataContractRegistry.register(LedgerInitProposal.class);
+ DataContractRegistry.register(LedgerInitDecision.class);
+
+ SUPPORTED_CONTRACT_TYPES.put(LedgerInitProposal.class, LedgerInitProposalData.class);
+ SUPPORTED_CONTRACT_TYPES.put(LedgerInitDecision.class, LedgerInitDecisionData.class);
+
+ // SUPPORTED_CONTRACT_TYPES.add(LedgerInitResponse.class);
+ // DataContractRegistry.register(LedgerInitResponse.class);
+ }
+
+ private boolean isSupported(Class> clazz) {
+ return getContractType(clazz) != null;
+ }
+
+ private Class> getContractType(Class> clazz) {
+ for (Class> itf : SUPPORTED_CONTRACT_TYPES.keySet()) {
+ if (itf.isAssignableFrom(clazz)) {
+ return itf;
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public boolean canRead(Class> clazz, MediaType mediaType) {
+ return CONTENT_TYPE.includes(mediaType)
+ && (clazz.isPrimitive() || SignatureDigest.class == clazz || isSupported(clazz));
+ }
+
+ @Override
+ public boolean canWrite(Class> clazz, MediaType mediaType) {
+ return CONTENT_TYPE.includes(mediaType) && (clazz.isPrimitive() || LedgerInitResponse.class.isAssignableFrom(clazz) || isSupported(clazz));
+ }
+
+ @Override
+ public List getSupportedMediaTypes() {
+ return SUPPORTED_MEDIA_TYPES;
+ }
+
+ @Override
+ public Object read(Class extends Object> clazz, HttpInputMessage inputMessage)
+ throws IOException, HttpMessageNotReadableException {
+ if (SignatureDigest.class == clazz) {
+ byte[] signDigestBytes = BytesUtils.copyToBytes(inputMessage.getBody());
+ return new SignatureDigest(signDigestBytes);
+ }
+
+ Class> contractType = getContractType(clazz);
+ Class> implType = SUPPORTED_CONTRACT_TYPES.get(contractType);
+ return BinaryProtocol.decode(inputMessage.getBody());
+ }
+
+ @Override
+ public void write(Object t, MediaType contentType, HttpOutputMessage outputMessage)
+ throws IOException, HttpMessageNotWritableException {
+ LedgerInitResponse resp;
+ if (t == null) {
+ resp = LedgerInitResponse.success(null);
+ } else if (t instanceof LedgerInitResponse) {
+ resp = (LedgerInitResponse) t;
+ outputMessage.getBody().write(resp.toBytes());
+ } else {
+ Class> contractType = getContractType(t.getClass());
+ if (contractType == null) {
+ throw new IllegalStateException("Unsupported type[" + t.getClass().getName() + "]!");
+ }
+ byte[] data = BinaryProtocol.encode(t, contractType);
+ resp = LedgerInitResponse.success(data);
+ outputMessage.getBody().write(resp.toBytes());
+ }
+ }
+
+}
diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/PermissionResponseConverter.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/PermissionResponseConverter.java
index f291d6c9..685af45d 100644
--- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/PermissionResponseConverter.java
+++ b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/PermissionResponseConverter.java
@@ -1,24 +1,24 @@
-package com.jd.blockchain.tools.initializer.web;
-
-import java.io.InputStream;
-
-import com.jd.blockchain.binaryproto.BinaryProtocol;
-import com.jd.blockchain.ledger.LedgerInitException;
-import com.jd.blockchain.ledger.core.LedgerInitProposalData;
-import com.jd.blockchain.utils.http.HttpServiceContext;
-import com.jd.blockchain.utils.http.ResponseConverter;
-import com.jd.blockchain.utils.http.agent.ServiceRequest;
-
-public class PermissionResponseConverter implements ResponseConverter {
-
- @Override
- public Object getResponse(ServiceRequest request, InputStream responseStream, HttpServiceContext serviceContext)
- throws Exception {
- LedgerInitResponse resp = LedgerInitResponse.resolve(responseStream);
- if (resp.isError()) {
- throw new LedgerInitException("Error occurred at remote participant! --" + resp.getErrorMessage());
- }
- return BinaryProtocol.decode(resp.getData());
- }
-
-}
+package com.jd.blockchain.tools.initializer.web;
+
+import java.io.InputStream;
+
+import com.jd.blockchain.binaryproto.BinaryProtocol;
+import com.jd.blockchain.ledger.LedgerInitException;
+import com.jd.blockchain.ledger.core.LedgerInitProposalData;
+import com.jd.blockchain.utils.http.HttpServiceContext;
+import com.jd.blockchain.utils.http.ResponseConverter;
+import com.jd.blockchain.utils.http.agent.ServiceRequest;
+
+public class PermissionResponseConverter implements ResponseConverter {
+
+ @Override
+ public Object getResponse(ServiceRequest request, InputStream responseStream, HttpServiceContext serviceContext)
+ throws Exception {
+ LedgerInitResponse resp = LedgerInitResponse.resolve(responseStream);
+ if (resp.isError()) {
+ throw new LedgerInitException("Error occurred at remote participant! --" + resp.getErrorMessage());
+ }
+ return BinaryProtocol.decode(resp.getData());
+ }
+
+}
diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/SignatureDigestRequestBodyConverter.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/SignatureDigestRequestBodyConverter.java
index ec6fc7c0..79abf7d5 100644
--- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/SignatureDigestRequestBodyConverter.java
+++ b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/SignatureDigestRequestBodyConverter.java
@@ -1,19 +1,19 @@
-package com.jd.blockchain.tools.initializer.web;
-
-import java.io.IOException;
-import java.io.OutputStream;
-
-import com.jd.blockchain.crypto.SignatureDigest;
-import com.jd.blockchain.utils.http.RequestBodyConverter;
-
-public class SignatureDigestRequestBodyConverter implements RequestBodyConverter {
-
- @Override
- public void write(Object param, OutputStream out) throws IOException {
- if (param instanceof SignatureDigest) {
- out.write(((SignatureDigest)param).toBytes());
- return;
- }
- }
-
+package com.jd.blockchain.tools.initializer.web;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+import com.jd.blockchain.crypto.SignatureDigest;
+import com.jd.blockchain.utils.http.RequestBodyConverter;
+
+public class SignatureDigestRequestBodyConverter implements RequestBodyConverter {
+
+ @Override
+ public void write(Object param, OutputStream out) throws IOException {
+ if (param instanceof SignatureDigest) {
+ out.write(((SignatureDigest)param).toBytes());
+ return;
+ }
+ }
+
}
\ No newline at end of file
diff --git a/source/tools/tools-initializer/src/main/resources/META-INF/spring.factories b/source/tools/tools-initializer/src/main/resources/META-INF/spring.factories
index 854f0848..459b87c8 100644
--- a/source/tools/tools-initializer/src/main/resources/META-INF/spring.factories
+++ b/source/tools/tools-initializer/src/main/resources/META-INF/spring.factories
@@ -1,2 +1,2 @@
-org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
+org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.jd.blockchain.tools.initializer.InitializerConfiguration
\ No newline at end of file
diff --git a/source/tools/tools-initializer/src/main/resources/application.properties b/source/tools/tools-initializer/src/main/resources/application.properties
index 16cdc6bf..892ff79d 100644
--- a/source/tools/tools-initializer/src/main/resources/application.properties
+++ b/source/tools/tools-initializer/src/main/resources/application.properties
@@ -1,13 +1,13 @@
-server.address=127.0.0.1
-server.port=8900
-
-server.tomcat.accesslog.enabled=true
-
-debug=false
-
-logging.config=classpath:log4j2-init.xml
-#logging.file=logs/peer.log
-logging.level.com.jd.blockchain=DEBUG
-logging.level.org.org.springframework=DEBUG
-
+server.address=127.0.0.1
+server.port=8900
+
+server.tomcat.accesslog.enabled=true
+
+debug=false
+
+logging.config=classpath:log4j2-init.xml
+#logging.file=logs/peer.log
+logging.level.com.jd.blockchain=DEBUG
+logging.level.org.org.springframework=DEBUG
+
spring.mvc.favicon.enabled=false
\ No newline at end of file
diff --git a/source/utils/.gitignore b/source/utils/.gitignore
index bb88c990..49a77c09 100644
--- a/source/utils/.gitignore
+++ b/source/utils/.gitignore
@@ -1,23 +1,23 @@
-**.classpath
-**.project
-**/bin/
-**.class
-
-target/
-
-*.bak
-bin/
-*.iml
-*.ipr
-*.iws
-.idea
-.classpath
-.project
-.settings/
-.DS_Store
-.springBeans
-.externalToolBuilders/
-
-
-*.versionsBackup
-.factorypath
+**.classpath
+**.project
+**/bin/
+**.class
+
+target/
+
+*.bak
+bin/
+*.iml
+*.ipr
+*.iws
+.idea
+.classpath
+.project
+.settings/
+.DS_Store
+.springBeans
+.externalToolBuilders/
+
+
+*.versionsBackup
+.factorypath
diff --git a/source/utils/pom.xml b/source/utils/pom.xml
index a9233b6d..4e50253c 100644
--- a/source/utils/pom.xml
+++ b/source/utils/pom.xml
@@ -1,59 +1,59 @@
-
- 4.0.0
-
- com.jd.blockchain
- jdchain-root
- 1.1.2.RELEASE
-
- utils
- pom
-
-
- utils-serialize
- utils-web
- utils-web-server
- utils-common
- utils-http
- utils-test
-
-
-
-
- junit
- junit
- test
-
-
- org.mockito
- mockito-core
- test
-
-
-
-
-
-
- net.i2p.crypto
- eddsa
- 0.1.0
-
-
-
-
-
-
+
+ 4.0.0
+
+ com.jd.blockchain
+ jdchain-root
+ 1.1.2.RELEASE
+
+ utils
+ pom
+
+
+ utils-serialize
+ utils-web
+ utils-web-server
+ utils-common
+ utils-http
+ utils-test
+
+
+
+
+ junit
+ junit
+ test
+
+
+ org.mockito
+ mockito-core
+ test
+
+
+
+
+
+
+ net.i2p.crypto
+ eddsa
+ 0.1.0
+
+
+
+
+
+
\ No newline at end of file
diff --git a/source/utils/utils-common/.gitignore b/source/utils/utils-common/.gitignore
index 24d64373..b83d2226 100644
--- a/source/utils/utils-common/.gitignore
+++ b/source/utils/utils-common/.gitignore
@@ -1 +1 @@
-/target/
+/target/
diff --git a/source/utils/utils-common/pom.xml b/source/utils/utils-common/pom.xml
index 04fec308..60f71abf 100644
--- a/source/utils/utils-common/pom.xml
+++ b/source/utils/utils-common/pom.xml
@@ -1,103 +1,103 @@
-
- 4.0.0
-
- com.jd.blockchain
- utils
- 1.1.2.RELEASE
-
- utils-common
-
-
-
-
- org.slf4j
- slf4j-api
-
-
-
- commons-codec
- commons-codec
-
-
-
- commons-io
- commons-io
- 2.4
-
-
-
- net.i2p.crypto
- eddsa
-
-
- org.bouncycastle
- bcprov-jdk15on
-
-
- org.springframework
- spring-beans
-
-
-
- org.bitbucket.mstrobel
- procyon-core
-
-
- org.bitbucket.mstrobel
- procyon-expressions
-
-
- org.bitbucket.mstrobel
- procyon-reflection
-
-
- org.bitbucket.mstrobel
- procyon-compilertools
-
-
-
-
-
-
- org.slf4j
- slf4j-log4j12
- test
-
-
- org.apache.logging.log4j
- log4j-api
- test
-
-
- org.apache.logging.log4j
- log4j-core
- test
-
-
-
-
-
+
+ 4.0.0
+
+ com.jd.blockchain
+ utils
+ 1.1.2.RELEASE
+
+ utils-common
+
+
+
+
+ org.slf4j
+ slf4j-api
+
+
+
+ commons-codec
+ commons-codec
+
+
+
+ commons-io
+ commons-io
+ 2.4
+
+
+
+ net.i2p.crypto
+ eddsa
+
+
+ org.bouncycastle
+ bcprov-jdk15on
+
+
+ org.springframework
+ spring-beans
+
+
+
+ org.bitbucket.mstrobel
+ procyon-core
+
+
+ org.bitbucket.mstrobel
+ procyon-expressions
+
+
+ org.bitbucket.mstrobel
+ procyon-reflection
+
+
+ org.bitbucket.mstrobel
+ procyon-compilertools
+
+
+
+
+
+
+ org.slf4j
+ slf4j-log4j12
+ test
+
+
+ org.apache.logging.log4j
+ log4j-api
+ test
+
+
+ org.apache.logging.log4j
+ log4j-core
+ test
+
+
+
+
+
\ No newline at end of file
diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/ArrayUtils.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/ArrayUtils.java
index cea92cbc..399aba80 100644
--- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/ArrayUtils.java
+++ b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/ArrayUtils.java
@@ -1,122 +1,122 @@
-package com.jd.blockchain.utils;
-
-import java.lang.reflect.Array;
-import java.util.*;
-
-/**
- * @author haiq
- *
- */
-public abstract class ArrayUtils {
- private ArrayUtils() {
-
- }
-
- public static R[] castTo(T[] objs, Class clazz, CastFunction cf) {
- if (objs == null) {
- return null;
- }
- @SuppressWarnings("unchecked")
- R[] array = (R[]) Array.newInstance(clazz, objs.length);
- for (int i = 0; i < objs.length; i++) {
- array[i] = cf.cast(objs[i]);
- }
- return array;
- }
-
- public static T[] singleton(T obj, Class clazz) {
- @SuppressWarnings("unchecked")
- T[] array = (T[]) Array.newInstance(clazz, 1);
- array[0] = obj;
- return array;
- }
-
- public static T[] toArray(Iterator itr, Class clazz) {
- List lst = new LinkedList();
- while (itr.hasNext()) {
- T t = (T) itr.next();
- lst.add(t);
- }
- @SuppressWarnings("unchecked")
- T[] array = (T[]) Array.newInstance(clazz, lst.size());
- lst.toArray(array);
- return array;
- }
-
- public static T[] toArray(Collection collection, Class clazz) {
- @SuppressWarnings("unchecked")
- T[] array = (T[]) Array.newInstance(clazz, collection.size());
- collection.toArray(array);
- return array;
- }
-
- public static