diff --git a/newfeatures-authorize.txt b/newfeatures-authorize.txt new file mode 100644 index 00000000..3bb8e333 --- /dev/null +++ b/newfeatures-authorize.txt @@ -0,0 +1,6 @@ + + +1、网关节点移除查询接口 HTTP GET ledgers/{ledgerHash}/settings (出于设计合理性原因) + + +2、网关节点增加查询接口 HTTP GET ledgers/{ledgerHash}/admininfo ,接口返回指定账本管理配置信息; \ No newline at end of file diff --git a/source/base/pom.xml b/source/base/pom.xml index 367d7c8a..94592186 100644 --- a/source/base/pom.xml +++ b/source/base/pom.xml @@ -8,12 +8,4 @@ 1.1.0-SNAPSHOT base - - - - org.slf4j - slf4j-api - - - \ No newline at end of file diff --git a/source/base/src/main/java/com/jd/blockchain/consts/DataCodes.java b/source/base/src/main/java/com/jd/blockchain/consts/DataCodes.java index 600053e8..bf262ef0 100644 --- a/source/base/src/main/java/com/jd/blockchain/consts/DataCodes.java +++ b/source/base/src/main/java/com/jd/blockchain/consts/DataCodes.java @@ -8,11 +8,11 @@ package com.jd.blockchain.consts; */ public interface DataCodes { - public static final int BYTES_VALUE = 0x80; - - public static final int BYTES_VALUE_LIST = 0x81; + public static final int BYTES_VALUE = 0x080; + + public static final int BYTES_VALUE_LIST = 0x081; - public static final int BLOCK_CHAIN_IDENTITY = 0x90; + public static final int BLOCK_CHAIN_IDENTITY = 0x090; public static final int BLOCK = 0x100; @@ -22,6 +22,8 @@ public interface DataCodes { public static final int DATA_SNAPSHOT = 0x130; +// public static final int LEDGER_ADMIN_DATA = 0x131; + public static final int TX = 0x200; public static final int TX_LEDGER = 0x201; @@ -55,12 +57,37 @@ public interface DataCodes { public static final int TX_RESPONSE = 0x360; public static final int TX_OP_RESULT = 0x370; + + public static final int TX_OP_ROLE_CONFIGURE = 0x370; + + public static final int TX_OP_ROLE_CONFIGURE_ENTRY = 0x371; + + public static final int TX_OP_USER_ROLES_AUTHORIZE = 0x372; + + public static final int TX_OP_USER_ROLE_AUTHORIZE_ENTRY = 0x373; + + // enum types of permissions; + public static final int ENUM_TX_PERMISSION = 0x401; + public static final int ENUM_LEDGER_PERMISSION = 0x402; + public static final int ENUM_MULTI_ROLES_POLICY = 0x403; + + public static final int PRIVILEGE_SET = 0x410; + public static final int ROLE_SET = 0x411; + + public static final int SECURITY_INIT_SETTING = 0x420; + + public static final int SECURITY_ROLE_INIT_SETTING = 0x421; + + public static final int SECURITY_USER_AUTH_INIT_SETTING = 0x422; + + // contract types of metadata; public static final int METADATA = 0x600; + public static final int METADATA_V2 = 0x601; public static final int METADATA_INIT_SETTING = 0x610; - public static final int METADATA_INIT_PERMISSION = 0x611; + public static final int METADATA_INIT_PROPOSAL = 0x611; public static final int METADATA_INIT_DECISION = 0x612; @@ -68,6 +95,15 @@ public interface DataCodes { public static final int METADATA_CONSENSUS_PARTICIPANT = 0x621; +// public static final int METADATA_CONSENSUS_NODE = 0x630; +// +// public static final int METADATA_CONSENSUS_SETTING = 0x631; +// +// public static final int METADATA_PARTICIPANT_INFO = 0x640; + + public static final int METADATA_CRYPTO_SETTING = 0x642; + + // public static final int METADATA_CONSENSUS_NODE = 0x630; public static final int METADATA_CONSENSUS_SETTING = 0x631; @@ -88,11 +124,10 @@ public interface DataCodes { public static final int DATA = 0x900; - //contract related; + // contract related; public static final int CONTRACT = 0xA00; - - //...0xA19 + // ...0xA19 public static final int HASH = 0xB00; public static final int HASH_OBJECT = 0xB10; diff --git a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/MsgQueueConsensusSettingsBuilder.java b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/MsgQueueConsensusSettingsBuilder.java index 5790bae3..448955c8 100644 --- a/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/MsgQueueConsensusSettingsBuilder.java +++ b/source/consensus/consensus-mq/src/main/java/com/jd/blockchain/consensus/mq/MsgQueueConsensusSettingsBuilder.java @@ -21,10 +21,10 @@ import com.jd.blockchain.consensus.mq.settings.MsgQueueConsensusSettings; import com.jd.blockchain.consensus.mq.settings.MsgQueueNetworkSettings; import com.jd.blockchain.consensus.mq.settings.MsgQueueNodeSettings; import com.jd.blockchain.crypto.AddressEncoding; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.ledger.ParticipantInfo; import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.tools.keygen.KeyGenCommand; import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.PropertiesUtils; import com.jd.blockchain.utils.codec.Base58Utils; @@ -134,7 +134,7 @@ public class MsgQueueConsensusSettingsBuilder implements ConsensusSettingsBuilde String keyOfPubkey = nodeKey(PUBKEY_PATTERN, id); String base58PubKey = PropertiesUtils.getRequiredProperty(resolvingProps, keyOfPubkey); - PubKey pubKey = KeyGenCommand.decodePubKey(base58PubKey); + PubKey pubKey = KeyGenUtils.decodePubKey(base58PubKey); // PubKey pubKey = new PubKey(Base58Utils.decode(base58PubKey)); resolvingProps.remove(keyOfPubkey); diff --git a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/ContractDeployExeUtil.java b/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/ContractDeployExeUtil.java index 157abcbb..b84cc712 100644 --- a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/ContractDeployExeUtil.java +++ b/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/ContractDeployExeUtil.java @@ -7,12 +7,12 @@ import java.io.InputStream; import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.ledger.*; import com.jd.blockchain.sdk.BlockchainService; import com.jd.blockchain.sdk.client.GatewayServiceFactory; -import com.jd.blockchain.tools.keygen.KeyGenCommand; import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.codec.Base58Utils; import com.jd.blockchain.utils.net.NetworkAddress; @@ -30,8 +30,8 @@ public enum ContractDeployExeUtil { PubKey pub = null; PrivKey prv = null; try { - prv = KeyGenCommand.readPrivKey(prvPath, KeyGenCommand.encodePassword(rawPassword)); - pub = KeyGenCommand.readPubKey(pubPath); + prv = KeyGenUtils.readPrivKey(prvPath, KeyGenUtils.encodePassword(rawPassword)); + pub = KeyGenUtils.readPubKey(pubPath); } catch (Exception e) { e.printStackTrace(); @@ -47,7 +47,7 @@ public enum ContractDeployExeUtil { BlockchainKeypair contractKeyPair = BlockchainKeyGenerator.getInstance().generate(); pub = contractKeyPair.getPubKey(); }else { - pub = KeyGenCommand.readPubKey(pubPath); + pub = KeyGenUtils.readPubKey(pubPath); } } catch (Exception e) { diff --git a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/ContractDeployMojo.java b/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/ContractDeployMojo.java index 3eac13bb..427fe00f 100644 --- a/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/ContractDeployMojo.java +++ b/source/contract/contract-maven-plugin/src/main/java/com/jd/blockchain/ContractDeployMojo.java @@ -1,10 +1,10 @@ package com.jd.blockchain; import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.tools.keygen.KeyGenCommand; import com.jd.blockchain.utils.StringUtils; import com.jd.blockchain.utils.codec.Base58Utils; import com.jd.blockchain.utils.io.FileUtils; @@ -102,8 +102,8 @@ public class ContractDeployMojo extends AbstractMojo { byte[] contractBytes = FileUtils.readBytes(contractPath); - PrivKey prv = KeyGenCommand.decodePrivKeyWithRawPassword(prvKey, password); - PubKey pub = KeyGenCommand.decodePubKey(pubKey); + PrivKey prv = KeyGenUtils.decodePrivKeyWithRawPassword(prvKey, password); + PubKey pub = KeyGenUtils.decodePubKey(pubKey); BlockchainKeypair blockchainKeyPair = new BlockchainKeypair(pub, prv); HashDigest ledgerHash = new HashDigest(Base58Utils.decode(ledger)); diff --git a/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/KeyGenUtils.java b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/KeyGenUtils.java new file mode 100644 index 00000000..717c813c --- /dev/null +++ b/source/crypto/crypto-framework/src/main/java/com/jd/blockchain/crypto/KeyGenUtils.java @@ -0,0 +1,187 @@ +package com.jd.blockchain.crypto; + +import java.util.Arrays; + +import javax.crypto.SecretKey; + +import com.jd.blockchain.utils.ConsoleUtils; +import com.jd.blockchain.utils.codec.Base58Utils; +import com.jd.blockchain.utils.io.BytesUtils; +import com.jd.blockchain.utils.io.FileUtils; +import com.jd.blockchain.utils.security.AESUtils; +import com.jd.blockchain.utils.security.DecryptionException; +import com.jd.blockchain.utils.security.ShaUtils; + +public class KeyGenUtils { + + private static final byte[] PUB_KEY_FILE_MAGICNUM = { (byte) 0xFF, 112, 117, 98 }; + + private static final byte[] PRIV_KEY_FILE_MAGICNUM = { (byte) 0x00, 112, 114, 118 }; + + /** + * 公钥编码输出为 Base58 字符; + * + * @param pubKey + * @return + */ + public static String encodePubKey(PubKey pubKey) { + byte[] pubKeyBytes = BytesUtils.concat(PUB_KEY_FILE_MAGICNUM, pubKey.toBytes()); + String base58PubKey = Base58Utils.encode(pubKeyBytes); + return base58PubKey; + } + + public static PubKey decodePubKey(String base58PubKey) { + byte[] keyBytes = Base58Utils.decode(base58PubKey); + return decodePubKey(keyBytes); + } + + public static String encodePrivKey(PrivKey privKey, String base58Pwd) { + byte[] pwdBytes = Base58Utils.decode(base58Pwd); + return encodePrivKey(privKey, pwdBytes); + } + + public static String encodePrivKey(PrivKey privKey, byte[] pwdBytes) { + byte[] encodedPrivKeyBytes = encryptPrivKey(privKey, pwdBytes); + String base58PrivKey = Base58Utils.encode(encodedPrivKeyBytes); + return base58PrivKey; + } + + public static byte[] encryptPrivKey(PrivKey privKey, byte[] pwdBytes) { + SecretKey userKey = AESUtils.generateKey128(pwdBytes); + byte[] encryptedPrivKeyBytes = AESUtils.encrypt(privKey.toBytes(), userKey); + return BytesUtils.concat(PRIV_KEY_FILE_MAGICNUM, encryptedPrivKeyBytes); + } + + /** + * @param encodedPubKeyBytes + * @return + */ + private static PubKey decodePubKeyBytes(byte[] encodedPubKeyBytes) { + byte[] pubKeyBytes = Arrays.copyOfRange(encodedPubKeyBytes, PUB_KEY_FILE_MAGICNUM.length, + encodedPubKeyBytes.length); + return new PubKey(pubKeyBytes); + } + + public static PrivKey decryptedPrivKeyBytes(byte[] encodedPrivKeyBytes, byte[] pwdBytes) { + // Read privKye; + SecretKey userKey = AESUtils.generateKey128(pwdBytes); + byte[] encryptedKeyBytes = Arrays.copyOfRange(encodedPrivKeyBytes, PRIV_KEY_FILE_MAGICNUM.length, + encodedPrivKeyBytes.length); + try { + byte[] plainKeyBytes = AESUtils.decrypt(encryptedKeyBytes, userKey); + return new PrivKey(plainKeyBytes); + } catch (DecryptionException e) { + throw new DecryptionException("Invalid password!", e); + } + } + + public static PubKey readPubKey(String keyFile) { + String base58KeyString = FileUtils.readText(keyFile); + return decodePubKey(base58KeyString); + } + + /** + * 解码公钥; + * + * @param encodedPubKeyBytes 从公钥; + * @return + */ + public static PubKey decodePubKey(byte[] encodedPubKeyBytes) { + if (BytesUtils.startsWith(encodedPubKeyBytes, PUB_KEY_FILE_MAGICNUM)) { + // Read pubKey; + return decodePubKeyBytes(encodedPubKeyBytes); + } + + throw new IllegalArgumentException("The specified bytes is not valid PubKey generated by the KeyGen tool!"); + } + + /** + * 从控制台读取加密口令,以二进制数组形式返回原始口令的一次SHA256的结果; + * + * @return + */ + public static byte[] readPassword() { + byte[] pwdBytes = ConsoleUtils.readPassword(); + return ShaUtils.hash_256(pwdBytes); + } + + /** + * 对指定的原始密码进行编码生成用于加解密的密码; + * + * @param rawPassword + * @return + */ + public static byte[] encodePassword(String rawPassword) { + byte[] pwdBytes = BytesUtils.toBytes(rawPassword, "UTF-8"); + return ShaUtils.hash_256(pwdBytes); + } + + /** + * 对指定的原始密码进行编码生成用于加解密的密码; + * + * @param rawPassword + * @return + */ + public static String encodePasswordAsBase58(String rawPassword) { + return Base58Utils.encode(encodePassword(rawPassword)); + } + + /** + * 从控制台读取加密口令,以Base58字符串形式返回口令的一次SHA256的结果; + * + * @return + */ + public static String readPasswordString() { + return Base58Utils.encode(readPassword()); + } + + public static PrivKey readPrivKey(String keyFile, String base58Pwd) { + return readPrivKey(keyFile, Base58Utils.decode(base58Pwd)); + } + + /** + * 从文件读取私钥; + * + * @param keyFile + * @param pwdBytes + * @return + */ + public static PrivKey readPrivKey(String keyFile, byte[] pwdBytes) { + String base58KeyString = FileUtils.readText(keyFile); + byte[] keyBytes = Base58Utils.decode(base58KeyString); + if (!BytesUtils.startsWith(keyBytes, PRIV_KEY_FILE_MAGICNUM)) { + throw new IllegalArgumentException("The specified file is not a private key file!"); + } + return decryptedPrivKeyBytes(keyBytes, pwdBytes); + } + + public static PrivKey decodePrivKey(String base58Key, String base58Pwd) { + byte[] decryptedKey = Base58Utils.decode(base58Pwd); + return decodePrivKey(base58Key, decryptedKey); + } + + public static PrivKey decodePrivKey(String base58Key, byte[] pwdBytes) { + byte[] keyBytes = Base58Utils.decode(base58Key); + if (!BytesUtils.startsWith(keyBytes, PRIV_KEY_FILE_MAGICNUM)) { + throw new IllegalArgumentException("The specified file is not a private key file!"); + } + return decryptedPrivKeyBytes(keyBytes, pwdBytes); + } + + public static PrivKey decodePrivKeyWithRawPassword(String base58Key, String rawPassword) { + byte[] pwdBytes = encodePassword(rawPassword); + byte[] keyBytes = Base58Utils.decode(base58Key); + if (!BytesUtils.startsWith(keyBytes, PRIV_KEY_FILE_MAGICNUM)) { + throw new IllegalArgumentException("The specified file is not a private key file!"); + } + return decryptedPrivKeyBytes(keyBytes, pwdBytes); + } + + public static boolean isPubKeyBytes(byte[] keyBytes) { + return BytesUtils.startsWith(keyBytes, PUB_KEY_FILE_MAGICNUM); + } + + public static boolean isPrivKeyBytes(byte[] keyBytes) { + return BytesUtils.startsWith(keyBytes, PRIV_KEY_FILE_MAGICNUM); + } +} diff --git a/source/deployment/deployment-gateway/conf/application-gw.properties b/source/deployment/deployment-gateway/conf/application-gw.properties new file mode 100644 index 00000000..e69de29b diff --git a/source/deployment/deployment-gateway/src/main/java/com/jd/blockchain/gateway/boot/GatewayBooter.java b/source/deployment/deployment-gateway/src/main/java/com/jd/blockchain/gateway/boot/GatewayBooter.java index 93ca75ff..f6c637ad 100644 --- a/source/deployment/deployment-gateway/src/main/java/com/jd/blockchain/gateway/boot/GatewayBooter.java +++ b/source/deployment/deployment-gateway/src/main/java/com/jd/blockchain/gateway/boot/GatewayBooter.java @@ -18,15 +18,13 @@ public class GatewayBooter { writePID(); GatewayServerBooter.main(args); } catch (Exception e) { + e.printStackTrace(); System.err.println("Error!!! --[" + e.getClass().getName() + "] " + e.getMessage()); } } private static final void writePID() throws Exception { - URL url = GatewayBooter.class - .getProtectionDomain() - .getCodeSource() - .getLocation(); + URL url = GatewayBooter.class.getProtectionDomain().getCodeSource().getLocation(); String currPath = java.net.URLDecoder.decode(url.getPath(), "UTF-8"); if (currPath.contains("!/")) { currPath = currPath.substring(5, currPath.indexOf("!/")); @@ -40,6 +38,10 @@ public class GatewayBooter { String pidFilePath = homeDir + File.separator + "bin" + File.separator + "PID.log"; File pidFile = new File(pidFilePath); if (!pidFile.exists()) { + File dir = pidFile.getParentFile(); + if (!dir.exists()) { + dir.mkdirs(); + } pidFile.createNewFile(); } String name = ManagementFactory.getRuntimeMXBean().getName(); diff --git a/source/gateway/pom.xml b/source/gateway/pom.xml index 6bd8122c..cb5478f6 100644 --- a/source/gateway/pom.xml +++ b/source/gateway/pom.xml @@ -75,7 +75,6 @@ commons-io commons-io - ${commons-io.version} @@ -98,18 +97,13 @@ org.springframework.boot spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-logging - - + - + org.springframework.boot 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 3b9604f3..76c39b61 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 @@ -5,20 +5,20 @@ import java.io.InputStream; import java.util.ArrayList; import java.util.List; -import com.jd.blockchain.gateway.web.BlockBrowserController; 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.tools.keygen.KeyGenCommand; +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; -import com.jd.blockchain.utils.ArgumentSet.ArgEntry; public class GatewayServerBooter { @@ -88,19 +88,19 @@ public class GatewayServerBooter { String base58Pwd = config.keys().getDefault().getPrivKeyPassword(); if (base58Pwd == null || base58Pwd.length() == 0) { - base58Pwd = KeyGenCommand.readPasswordString(); + base58Pwd = KeyGenUtils.readPasswordString(); } // 加载密钥; - PubKey pubKey = KeyGenCommand.decodePubKey(config.keys().getDefault().getPubKeyValue()); + PubKey pubKey = KeyGenUtils.decodePubKey(config.keys().getDefault().getPubKeyValue()); PrivKey privKey = null; String base58PrivKey = config.keys().getDefault().getPrivKeyValue(); if (base58PrivKey == null) { //注:GatewayConfigProperties 确保了 PrivKeyValue 和 PrivKeyPath 必有其一; - privKey = KeyGenCommand.readPrivKey(config.keys().getDefault().getPrivKeyPath(), base58Pwd); + privKey = KeyGenUtils.readPrivKey(config.keys().getDefault().getPrivKeyPath(), base58Pwd); } else { - privKey = KeyGenCommand.decodePrivKey(base58PrivKey, base58Pwd); + privKey = KeyGenUtils.decodePrivKey(base58PrivKey, base58Pwd); } defaultKeyPair = new AsymmetricKeypair(pubKey, privKey); } diff --git a/source/gateway/src/main/java/com/jd/blockchain/gateway/service/GatewayQueryService.java b/source/gateway/src/main/java/com/jd/blockchain/gateway/service/GatewayQueryService.java deleted file mode 100644 index 340527c7..00000000 --- a/source/gateway/src/main/java/com/jd/blockchain/gateway/service/GatewayQueryService.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.jd.blockchain.gateway.service; - -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.sdk.ContractSettings; -import com.jd.blockchain.sdk.LedgerInitSettings; -import com.jd.blockchain.utils.Bytes; - -/** - * queryService only for gateway; - * @Author zhaogw - * @Date 2019/2/22 10:37 - */ -public interface GatewayQueryService { - /** - * get all ledgers hashs; - * @param fromIndex - * @param count - */ - HashDigest[] getLedgersHash(int fromIndex, int count); - - /** - * get the participants by range; - * @param ledgerHash - * @param fromIndex - * @param count - * @return - */ - ParticipantNode[] getConsensusParticipants(HashDigest ledgerHash, int fromIndex, int count); - - /** - * 获取账本初始化配置信息 - * - * @param ledgerHash - * 账本Hash - * @return - */ - LedgerInitSettings getLedgerInitSettings(HashDigest ledgerHash); - - /** - * 获取账本指定合约信息 - * - * @param ledgerHash - * 账本Hash - * @param address - * 合约地址 - * @return - */ - ContractSettings getContractSettings(HashDigest ledgerHash, String address); -} diff --git a/source/gateway/src/main/java/com/jd/blockchain/gateway/service/GatewayQueryServiceHandler.java b/source/gateway/src/main/java/com/jd/blockchain/gateway/service/GatewayQueryServiceHandler.java deleted file mode 100644 index 4421dde1..00000000 --- a/source/gateway/src/main/java/com/jd/blockchain/gateway/service/GatewayQueryServiceHandler.java +++ /dev/null @@ -1,144 +0,0 @@ -package com.jd.blockchain.gateway.service; - -import com.jd.blockchain.consensus.ConsensusProvider; -import com.jd.blockchain.consensus.ConsensusProviders; -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider; -import com.jd.blockchain.consensus.mq.MsgQueueConsensusProvider; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.gateway.PeerService; -import com.jd.blockchain.gateway.decompiler.utils.DecompilerUtils; -import com.jd.blockchain.ledger.ContractInfo; -import com.jd.blockchain.ledger.LedgerMetadata; -import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.sdk.ContractSettings; -import com.jd.blockchain.sdk.LedgerInitSettings; -import com.jd.blockchain.utils.QueryUtil; -import com.jd.blockchain.utils.codec.HexUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import java.util.Arrays; - - -/** - * @Author zhaogw - * @Date 2019/2/22 10:39 - */ -@Component -public class GatewayQueryServiceHandler implements GatewayQueryService { - - @Autowired - private PeerService peerService; - - @Override - public HashDigest[] getLedgersHash(int fromIndex, int count) { - HashDigest ledgersHash[] = peerService.getQueryService().getLedgerHashs(); - int indexAndCount[] = QueryUtil.calFromIndexAndCount(fromIndex,count,ledgersHash.length); - HashDigest ledgersHashNew[] = Arrays.copyOfRange(ledgersHash,indexAndCount[0],indexAndCount[0]+indexAndCount[1]); - return ledgersHashNew; - } - - @Override - public ParticipantNode[] getConsensusParticipants(HashDigest ledgerHash, int fromIndex, int count) { - ParticipantNode participantNode[] = peerService.getQueryService().getConsensusParticipants(ledgerHash); - int indexAndCount[] = QueryUtil.calFromIndexAndCount(fromIndex,count,participantNode.length); - ParticipantNode participantNodesNew[] = Arrays.copyOfRange(participantNode,indexAndCount[0],indexAndCount[0]+indexAndCount[1]); - return participantNodesNew; - } - - @Override - public LedgerInitSettings getLedgerInitSettings(HashDigest ledgerHash) { - - ParticipantNode[] participantNodes = peerService.getQueryService().getConsensusParticipants(ledgerHash); - - LedgerMetadata ledgerMetadata = peerService.getQueryService().getLedgerMetadata(ledgerHash); - - return initLedgerInitSettings(participantNodes, ledgerMetadata); - } - - @Override - public ContractSettings getContractSettings(HashDigest ledgerHash, String address) { - ContractInfo contractInfo = peerService.getQueryService().getContract(ledgerHash, address); - return contractSettings(contractInfo); - } - - private ContractSettings contractSettings(ContractInfo contractInfo) { - ContractSettings contractSettings = new ContractSettings(contractInfo.getAddress(), contractInfo.getPubKey(), contractInfo.getRootHash()); - byte[] chainCodeBytes = contractInfo.getChainCode(); - // 将反编译chainCode - String mainClassJava = DecompilerUtils.decompileMainClassFromBytes(chainCodeBytes); - contractSettings.setChainCode(mainClassJava); - return contractSettings; - } - - /** - * 初始化账本配置 - * - * @param participantNodes - * 参与方列表 - * @param ledgerMetadata - * 账本元数据 - * @return - */ - private LedgerInitSettings initLedgerInitSettings(ParticipantNode[] participantNodes, LedgerMetadata ledgerMetadata) { - LedgerInitSettings ledgerInitSettings = new LedgerInitSettings(); - - // 设置参与方 - ledgerInitSettings.setParticipantNodes(participantNodes); - - // 设置共识设置 - ledgerInitSettings.setConsensusSettings(initConsensusSettings(ledgerMetadata)); - - // 设置参与方根Hash - ledgerInitSettings.setParticipantsHash(ledgerMetadata.getParticipantsHash()); - - // 设置算法配置 - ledgerInitSettings.setCryptoSetting(ledgerMetadata.getSetting().getCryptoSetting()); - - // 设置种子 - ledgerInitSettings.setSeed(initSeed(ledgerMetadata.getSeed())); - - // 设置共识协议 - ledgerInitSettings.setConsensusProtocol(ledgerMetadata.getSetting().getConsensusProvider()); - - return ledgerInitSettings; - } - - /** - * 初始化账本种子信息 - * - * @param seedBytes - * 种子的字节数组显示 - * @return - * 种子以十六进制方式显示,为方便阅读,每隔八个字符中间以"-"分割 - */ - private String initSeed(byte[] seedBytes) { - String seedString = HexUtils.encode(seedBytes); - // 每隔八个字符中加入一个一个横线 - StringBuffer seed = new StringBuffer(); - - for( int i = 0; i < seedString.length(); i++) { - char c = seedString.charAt(i); - if (i != 0 && i % 8 == 0) { - seed.append("-"); - } - seed.append(c); - } - - return seed.toString(); - } - - /** - * 初始化共识配置 - * - * @param ledgerMetadata - * 账本元数据 - * @return - */ - private ConsensusSettings initConsensusSettings(LedgerMetadata ledgerMetadata) { - String consensusProvider = ledgerMetadata.getSetting().getConsensusProvider(); - ConsensusProvider provider = ConsensusProviders.getProvider(consensusProvider); - byte[] consensusSettingsBytes = ledgerMetadata.getSetting().getConsensusSetting().toBytes(); - return provider.getSettingsFactory().getConsensusSettingsEncoder().decode(consensusSettingsBytes); - } -} diff --git a/source/gateway/src/main/java/com/jd/blockchain/gateway/web/BlockBrowserController.java b/source/gateway/src/main/java/com/jd/blockchain/gateway/web/BlockBrowserController.java index 91c498aa..895d2d23 100644 --- a/source/gateway/src/main/java/com/jd/blockchain/gateway/web/BlockBrowserController.java +++ b/source/gateway/src/main/java/com/jd/blockchain/gateway/web/BlockBrowserController.java @@ -1,546 +1,580 @@ package com.jd.blockchain.gateway.web; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; + +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + import com.jd.blockchain.crypto.AddressEncoding; import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.gateway.PeerService; +import com.jd.blockchain.gateway.decompiler.utils.DecompilerUtils; import com.jd.blockchain.gateway.service.DataRetrievalService; -import com.jd.blockchain.gateway.service.GatewayQueryService; -import com.jd.blockchain.ledger.*; +import com.jd.blockchain.ledger.AccountHeader; +import com.jd.blockchain.ledger.ContractInfo; +import com.jd.blockchain.ledger.KVDataEntry; +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.TransactionState; +import com.jd.blockchain.ledger.UserInfo; import com.jd.blockchain.sdk.BlockchainExtendQueryService; import com.jd.blockchain.sdk.ContractSettings; -import com.jd.blockchain.sdk.LedgerInitSettings; -import com.jd.blockchain.tools.keygen.KeyGenCommand; import com.jd.blockchain.utils.BaseConstant; import com.jd.blockchain.utils.ConsoleUtils; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import java.util.ArrayList; -import java.util.List; @RestController @RequestMapping(path = "/") public class BlockBrowserController implements BlockchainExtendQueryService { - private static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(BlockBrowserController.class); + private static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(BlockBrowserController.class); @Autowired private PeerService peerService; @Autowired - private DataRetrievalService dataRetrievalService; - - @Autowired - private GatewayQueryService gatewayQueryService; + private DataRetrievalService dataRetrievalService; - private String dataRetrievalUrl; + private String dataRetrievalUrl; private static final long BLOCK_MAX_DISPLAY = 3L; private static final long GENESIS_BLOCK_HEIGHT = 0L; - @Deprecated -// @RequestMapping(method = RequestMethod.GET, path = "ledgers") - @Override - public HashDigest[] getLedgerHashs() { - return peerService.getQueryService().getLedgerHashs(); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}") - @Override - public LedgerInfo getLedger(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - return peerService.getQueryService().getLedger(ledgerHash); - } - -// @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/participants") - @Override - public ParticipantNode[] getConsensusParticipants(HashDigest ledgerHash) { - return peerService.getQueryService().getConsensusParticipants(ledgerHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/metadata") - @Override - public LedgerMetadata getLedgerMetadata(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - return peerService.getQueryService().getLedgerMetadata(ledgerHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/settings") - public LedgerInitSettings getLedgerInitSettings(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - return gatewayQueryService.getLedgerInitSettings(ledgerHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks") - public LedgerBlock[] getBlocks(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - LedgerInfo ledgerInfo = peerService.getQueryService().getLedger(ledgerHash); - long maxBlockHeight = ledgerInfo.getLatestBlockHeight(); - List ledgerBlocks = new ArrayList<>(); - for (long blockHeight = maxBlockHeight; blockHeight > GENESIS_BLOCK_HEIGHT; blockHeight--) { - LedgerBlock ledgerBlock = peerService.getQueryService().getBlock(ledgerHash, blockHeight); - ledgerBlocks.add(0, ledgerBlock); - if (ledgerBlocks.size() == BLOCK_MAX_DISPLAY) { - break; - } - } - // 最后增加创世区块 - LedgerBlock genesisBlock = peerService.getQueryService().getBlock(ledgerHash, GENESIS_BLOCK_HEIGHT); - ledgerBlocks.add(0, genesisBlock); - LedgerBlock[] blocks = new LedgerBlock[ledgerBlocks.size()]; - ledgerBlocks.toArray(blocks); - return blocks; - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}") - @Override - public LedgerBlock getBlock(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHeight") long blockHeight) { - return peerService.getQueryService().getBlock(ledgerHash, blockHeight); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}") - @Override - public LedgerBlock getBlock(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHash") HashDigest blockHash) { - return peerService.getQueryService().getBlock(ledgerHash, blockHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/txs/count") - @Override - public long getTransactionCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHeight") long blockHeight) { - return peerService.getQueryService().getTransactionCount(ledgerHash, blockHeight); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/txs/count") - @Override - public long getTransactionCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHash") HashDigest blockHash) { - return peerService.getQueryService().getTransactionCount(ledgerHash, blockHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/txs/count") - @Override - public long getTransactionTotalCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - return peerService.getQueryService().getTransactionTotalCount(ledgerHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/accounts/count") - @Override - public long getDataAccountCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHeight") long blockHeight) { - return peerService.getQueryService().getDataAccountCount(ledgerHash, blockHeight); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/accounts/count") - @Override - public long getDataAccountCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHash") HashDigest blockHash) { - return peerService.getQueryService().getDataAccountCount(ledgerHash, blockHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/accounts/count") - @Override - public long getDataAccountTotalCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - return peerService.getQueryService().getDataAccountTotalCount(ledgerHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/users/count") - @Override - public long getUserCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHeight") long blockHeight) { - return peerService.getQueryService().getUserCount(ledgerHash, blockHeight); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/users/count") - @Override - public long getUserCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHash") HashDigest blockHash) { - return peerService.getQueryService().getUserCount(ledgerHash, blockHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/users/count") - @Override - public long getUserTotalCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - return peerService.getQueryService().getUserTotalCount(ledgerHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/contracts/count") - @Override - public long getContractCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHeight") long blockHeight) { - return peerService.getQueryService().getContractCount(ledgerHash, blockHeight); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/contracts/count") - @Override - public long getContractCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHash") HashDigest blockHash) { - return peerService.getQueryService().getContractCount(ledgerHash, blockHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/contracts/count") - @Override - public long getContractTotalCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - return peerService.getQueryService().getContractTotalCount(ledgerHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/txs") - @Override - public LedgerTransaction[] getTransactions(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHeight") long blockHeight, - @RequestParam(name = "fromIndex", required = false, defaultValue = "0") int fromIndex, - @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { - return peerService.getQueryService().getTransactions(ledgerHash, blockHeight, fromIndex, count); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/txs") - @Override - public LedgerTransaction[] getTransactions(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHash") HashDigest blockHash, - @RequestParam(name = "fromIndex", required = false, defaultValue = "0") int fromIndex, - @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { - return peerService.getQueryService().getTransactions(ledgerHash, blockHash, fromIndex, count); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/txs/hash/{contentHash}") - @Override - public LedgerTransaction getTransactionByContentHash(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "contentHash") HashDigest contentHash) { - return peerService.getQueryService().getTransactionByContentHash(ledgerHash, contentHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/txs/state/{contentHash}") - @Override - public TransactionState getTransactionStateByContentHash(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "contentHash") HashDigest contentHash) { - return peerService.getQueryService().getTransactionStateByContentHash(ledgerHash, contentHash); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/users/address/{address}") - @Override - public UserInfo getUser(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "address") String address) { - return peerService.getQueryService().getUser(ledgerHash, address); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/accounts/address/{address}") - @Override - public AccountHeader getDataAccount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "address") String address) { - - return peerService.getQueryService().getDataAccount(ledgerHash, address); - } - - @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, path = "ledgers/{ledgerHash}/accounts/{address}/entries") - @Override - public KVDataEntry[] getDataEntries(@PathVariable("ledgerHash") HashDigest ledgerHash, - @PathVariable("address") String address, - @RequestParam("keys") String... keys) { - return peerService.getQueryService().getDataEntries(ledgerHash, address, keys); - } - - @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, path = "ledgers/{ledgerHash}/accounts/{address}/entries-version") - public KVDataEntry[] getDataEntries(@PathVariable("ledgerHash") HashDigest ledgerHash, - @PathVariable("address") String address, - @RequestBody KVInfoVO kvInfoVO) { - return peerService.getQueryService().getDataEntries(ledgerHash, address, kvInfoVO); - } - - @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, path = "ledgers/{ledgerHash}/accounts/address/{address}/entries") - @Override - public KVDataEntry[] getDataEntries(@PathVariable("ledgerHash") HashDigest ledgerHash, - @PathVariable("address") String address, - @RequestParam(name = "fromIndex", required = false, defaultValue = "0") int fromIndex, - @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { - return peerService.getQueryService().getDataEntries(ledgerHash, address, fromIndex, count); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/accounts/address/{address}/entries/count") - @Override - public long getDataEntriesTotalCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "address") String address) { - return peerService.getQueryService().getDataEntriesTotalCount(ledgerHash, address); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/contracts/address/{address}") - public ContractSettings getContractSettings(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "address") String address) { - return gatewayQueryService.getContractSettings(ledgerHash, address); - } + @RequestMapping(method = RequestMethod.GET, path = "ledgers") + @Override + public HashDigest[] getLedgerHashs() { + return peerService.getQueryService().getLedgerHashs(); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}") + @Override + public LedgerInfo getLedger(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { + return peerService.getQueryService().getLedger(ledgerHash); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/admininfo") + @Override + public LedgerAdminInfo getLedgerAdminInfo(HashDigest ledgerHash) { + return peerService.getQueryService().getLedgerAdminInfo(ledgerHash); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/participants") + @Override + public ParticipantNode[] getConsensusParticipants(HashDigest ledgerHash) { + return peerService.getQueryService().getConsensusParticipants(ledgerHash); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/metadata") + @Override + public LedgerMetadata getLedgerMetadata(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { + return peerService.getQueryService().getLedgerMetadata(ledgerHash); + } + +// @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/settings") +// public LedgerInitSettings getLedgerInitSettings(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { +// return gatewayQueryService.getLedgerInitSettings(ledgerHash); +// } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks") + public LedgerBlock[] getBlocks(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { + LedgerInfo ledgerInfo = peerService.getQueryService().getLedger(ledgerHash); + long maxBlockHeight = ledgerInfo.getLatestBlockHeight(); + List ledgerBlocks = new ArrayList<>(); + for (long blockHeight = maxBlockHeight; blockHeight > GENESIS_BLOCK_HEIGHT; blockHeight--) { + LedgerBlock ledgerBlock = peerService.getQueryService().getBlock(ledgerHash, blockHeight); + ledgerBlocks.add(0, ledgerBlock); + if (ledgerBlocks.size() == BLOCK_MAX_DISPLAY) { + break; + } + } + // 最后增加创世区块 + LedgerBlock genesisBlock = peerService.getQueryService().getBlock(ledgerHash, GENESIS_BLOCK_HEIGHT); + ledgerBlocks.add(0, genesisBlock); + LedgerBlock[] blocks = new LedgerBlock[ledgerBlocks.size()]; + ledgerBlocks.toArray(blocks); + return blocks; + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}") + @Override + public LedgerBlock getBlock(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @PathVariable(name = "blockHeight") long blockHeight) { + return peerService.getQueryService().getBlock(ledgerHash, blockHeight); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}") + @Override + public LedgerBlock getBlock(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @PathVariable(name = "blockHash") HashDigest blockHash) { + return peerService.getQueryService().getBlock(ledgerHash, blockHash); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/txs/count") + @Override + public long getTransactionCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @PathVariable(name = "blockHeight") long blockHeight) { + return peerService.getQueryService().getTransactionCount(ledgerHash, blockHeight); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/txs/count") + @Override + public long getTransactionCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @PathVariable(name = "blockHash") HashDigest blockHash) { + return peerService.getQueryService().getTransactionCount(ledgerHash, blockHash); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/txs/count") + @Override + public long getTransactionTotalCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { + return peerService.getQueryService().getTransactionTotalCount(ledgerHash); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/accounts/count") + @Override + public long getDataAccountCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @PathVariable(name = "blockHeight") long blockHeight) { + return peerService.getQueryService().getDataAccountCount(ledgerHash, blockHeight); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/accounts/count") + @Override + public long getDataAccountCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @PathVariable(name = "blockHash") HashDigest blockHash) { + return peerService.getQueryService().getDataAccountCount(ledgerHash, blockHash); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/accounts/count") + @Override + public long getDataAccountTotalCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { + return peerService.getQueryService().getDataAccountTotalCount(ledgerHash); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/users/count") + @Override + public long getUserCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @PathVariable(name = "blockHeight") long blockHeight) { + return peerService.getQueryService().getUserCount(ledgerHash, blockHeight); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/users/count") + @Override + public long getUserCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @PathVariable(name = "blockHash") HashDigest blockHash) { + return peerService.getQueryService().getUserCount(ledgerHash, blockHash); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/users/count") + @Override + public long getUserTotalCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { + return peerService.getQueryService().getUserTotalCount(ledgerHash); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/contracts/count") + @Override + public long getContractCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @PathVariable(name = "blockHeight") long blockHeight) { + return peerService.getQueryService().getContractCount(ledgerHash, blockHeight); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/contracts/count") + @Override + public long getContractCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @PathVariable(name = "blockHash") HashDigest blockHash) { + return peerService.getQueryService().getContractCount(ledgerHash, blockHash); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/contracts/count") + @Override + public long getContractTotalCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { + return peerService.getQueryService().getContractTotalCount(ledgerHash); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/txs") + @Override + public LedgerTransaction[] getTransactions(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @PathVariable(name = "blockHeight") long blockHeight, + @RequestParam(name = "fromIndex", required = false, defaultValue = "0") int fromIndex, + @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { + return peerService.getQueryService().getTransactions(ledgerHash, blockHeight, fromIndex, count); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/txs") + @Override + public LedgerTransaction[] getTransactions(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @PathVariable(name = "blockHash") HashDigest blockHash, + @RequestParam(name = "fromIndex", required = false, defaultValue = "0") int fromIndex, + @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { + return peerService.getQueryService().getTransactions(ledgerHash, blockHash, fromIndex, count); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/txs/hash/{contentHash}") + @Override + public LedgerTransaction getTransactionByContentHash(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @PathVariable(name = "contentHash") HashDigest contentHash) { + return peerService.getQueryService().getTransactionByContentHash(ledgerHash, contentHash); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/txs/state/{contentHash}") + @Override + public TransactionState getTransactionStateByContentHash(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @PathVariable(name = "contentHash") HashDigest contentHash) { + return peerService.getQueryService().getTransactionStateByContentHash(ledgerHash, contentHash); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/users/address/{address}") + @Override + public UserInfo getUser(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @PathVariable(name = "address") String address) { + return peerService.getQueryService().getUser(ledgerHash, address); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/accounts/address/{address}") + @Override + public AccountHeader getDataAccount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @PathVariable(name = "address") String address) { + + return peerService.getQueryService().getDataAccount(ledgerHash, address); + } + + @RequestMapping(method = { RequestMethod.GET, + RequestMethod.POST }, path = "ledgers/{ledgerHash}/accounts/{address}/entries") + @Override + public KVDataEntry[] getDataEntries(@PathVariable("ledgerHash") HashDigest ledgerHash, + @PathVariable("address") String address, @RequestParam("keys") String... keys) { + return peerService.getQueryService().getDataEntries(ledgerHash, address, keys); + } + + @RequestMapping(method = { RequestMethod.GET, + RequestMethod.POST }, path = "ledgers/{ledgerHash}/accounts/{address}/entries-version") + public KVDataEntry[] getDataEntries(@PathVariable("ledgerHash") HashDigest ledgerHash, + @PathVariable("address") String address, @RequestBody KVInfoVO kvInfoVO) { + return peerService.getQueryService().getDataEntries(ledgerHash, address, kvInfoVO); + } + + @RequestMapping(method = { RequestMethod.GET, + RequestMethod.POST }, path = "ledgers/{ledgerHash}/accounts/address/{address}/entries") + @Override + public KVDataEntry[] getDataEntries(@PathVariable("ledgerHash") HashDigest ledgerHash, + @PathVariable("address") String address, + @RequestParam(name = "fromIndex", required = false, defaultValue = "0") int fromIndex, + @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { + return peerService.getQueryService().getDataEntries(ledgerHash, address, fromIndex, count); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/accounts/address/{address}/entries/count") + @Override + public long getDataEntriesTotalCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @PathVariable(name = "address") String address) { + return peerService.getQueryService().getDataEntriesTotalCount(ledgerHash, address); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/contracts/address/{address}") + public ContractSettings getContractSettings(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @PathVariable(name = "address") String address) { + ContractInfo contractInfo = peerService.getQueryService().getContract(ledgerHash, address); + return contractSettings(contractInfo); + } + + private ContractSettings contractSettings(ContractInfo contractInfo) { + ContractSettings contractSettings = new ContractSettings(contractInfo.getAddress(), contractInfo.getPubKey(), + contractInfo.getRootHash()); + byte[] chainCodeBytes = contractInfo.getChainCode(); + // 将反编译chainCode + String mainClassJava = DecompilerUtils.decompileMainClassFromBytes(chainCodeBytes); + contractSettings.setChainCode(mainClassJava); + return contractSettings; + } // @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/contracts/address/{address}") - @Override - public ContractInfo getContract(HashDigest ledgerHash, String address) { - return peerService.getQueryService().getContract(ledgerHash, address); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/latest") - @Override - public LedgerBlock getLatestBlock(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - long latestBlockHeight = peerService.getQueryService().getLedger(ledgerHash).getLatestBlockHeight(); - return peerService.getQueryService().getBlock(ledgerHash, latestBlockHeight); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/txs/additional-count") - @Override - public long getAdditionalTransactionCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHeight") long blockHeight) { - // 获取某个区块的交易总数 - long currentBlockTxCount = peerService.getQueryService().getTransactionCount(ledgerHash, blockHeight); - if (blockHeight == GENESIS_BLOCK_HEIGHT) { - return currentBlockTxCount; - } - long lastBlockHeight = blockHeight - 1; - long lastBlockTxCount = peerService.getQueryService().getTransactionCount(ledgerHash, lastBlockHeight); - // 当前区块交易数减上个区块交易数 - return currentBlockTxCount - lastBlockTxCount; - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/txs/additional-count") - @Override - public long getAdditionalTransactionCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHash") HashDigest blockHash) { - LedgerBlock currentBlock = peerService.getQueryService().getBlock(ledgerHash, blockHash); - long currentBlockTxCount = peerService.getQueryService().getTransactionCount(ledgerHash, blockHash); - if (currentBlock.getHeight() == GENESIS_BLOCK_HEIGHT) { - return currentBlockTxCount; - } - HashDigest previousHash = currentBlock.getPreviousHash(); - long lastBlockTxCount = peerService.getQueryService().getTransactionCount(ledgerHash, previousHash); - // 当前区块交易数减上个区块交易数 - return currentBlockTxCount - lastBlockTxCount; - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/txs/additional-count") - @Override - public long getAdditionalTransactionCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - LedgerInfo ledgerInfo = peerService.getQueryService().getLedger(ledgerHash); - long maxBlockHeight = ledgerInfo.getLatestBlockHeight(); - long totalCount = peerService.getQueryService().getTransactionTotalCount(ledgerHash); - if (maxBlockHeight == GENESIS_BLOCK_HEIGHT) { // 只有一个创世区块 - return totalCount; - } - long lastTotalCount = peerService.getQueryService().getTransactionCount(ledgerHash, maxBlockHeight - 1); - return totalCount - lastTotalCount; - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/accounts/additional-count") - @Override - public long getAdditionalDataAccountCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHeight") long blockHeight) { - long currentDaCount = peerService.getQueryService().getDataAccountCount(ledgerHash, blockHeight); - if (blockHeight == GENESIS_BLOCK_HEIGHT) { - return currentDaCount; - } - long lastBlockHeight = blockHeight - 1; - long lastDaCount = peerService.getQueryService().getDataAccountCount(ledgerHash, lastBlockHeight); - return currentDaCount - lastDaCount; - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/accounts/additional-count") - @Override - public long getAdditionalDataAccountCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHash") HashDigest blockHash) { - LedgerBlock currentBlock = peerService.getQueryService().getBlock(ledgerHash, blockHash); - long currentBlockDaCount = peerService.getQueryService().getDataAccountCount(ledgerHash, blockHash); - if (currentBlock.getHeight() == GENESIS_BLOCK_HEIGHT) { - return currentBlockDaCount; - } - HashDigest previousHash = currentBlock.getPreviousHash(); - long lastBlockDaCount = peerService.getQueryService().getDataAccountCount(ledgerHash, previousHash); - // 当前区块数据账户数量减上个区块数据账户数量 - return currentBlockDaCount - lastBlockDaCount; - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/accounts/additional-count") - @Override - public long getAdditionalDataAccountCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - LedgerInfo ledgerInfo = peerService.getQueryService().getLedger(ledgerHash); - long maxBlockHeight = ledgerInfo.getLatestBlockHeight(); - long totalCount = peerService.getQueryService().getDataAccountTotalCount(ledgerHash); - if (maxBlockHeight == GENESIS_BLOCK_HEIGHT) { // 只有一个创世区块 - return totalCount; - } - long lastTotalCount = peerService.getQueryService().getDataAccountCount(ledgerHash, maxBlockHeight - 1); - return totalCount - lastTotalCount; - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/users/additional-count") - @Override - public long getAdditionalUserCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHeight") long blockHeight) { - long currentUserCount = peerService.getQueryService().getUserCount(ledgerHash, blockHeight); - if (blockHeight == GENESIS_BLOCK_HEIGHT) { - return currentUserCount; - } - long lastBlockHeight = blockHeight - 1; - long lastUserCount = peerService.getQueryService().getUserCount(ledgerHash, lastBlockHeight); - return currentUserCount - lastUserCount; - } - - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/users/additional-count") - @Override - public long getAdditionalUserCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHash") HashDigest blockHash) { - LedgerBlock currentBlock = peerService.getQueryService().getBlock(ledgerHash, blockHash); - long currentBlockUserCount = peerService.getQueryService().getUserCount(ledgerHash, blockHash); - if (currentBlock.getHeight() == GENESIS_BLOCK_HEIGHT) { - return currentBlockUserCount; - } - HashDigest previousHash = currentBlock.getPreviousHash(); - long lastBlockUserCount = peerService.getQueryService().getUserCount(ledgerHash, previousHash); - // 当前区块用户数量减上个区块用户数量 - return currentBlockUserCount - lastBlockUserCount; - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/users/additional-count") - @Override - public long getAdditionalUserCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - LedgerInfo ledgerInfo = peerService.getQueryService().getLedger(ledgerHash); - long maxBlockHeight = ledgerInfo.getLatestBlockHeight(); - long totalCount = peerService.getQueryService().getUserTotalCount(ledgerHash); - if (maxBlockHeight == GENESIS_BLOCK_HEIGHT) { // 只有一个创世区块 - return totalCount; - } - long lastTotalCount = peerService.getQueryService().getUserCount(ledgerHash, maxBlockHeight - 1); - return totalCount - lastTotalCount; - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/contracts/additional-count") - @Override - public long getAdditionalContractCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHeight") long blockHeight) { - long currentContractCount = peerService.getQueryService().getContractCount(ledgerHash, blockHeight); - if (blockHeight == GENESIS_BLOCK_HEIGHT) { - return currentContractCount; - } - long lastBlockHeight = blockHeight - 1; - long lastContractCount = peerService.getQueryService().getUserCount(ledgerHash, lastBlockHeight); - return currentContractCount - lastContractCount; - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/contracts/additional-count") - @Override - public long getAdditionalContractCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @PathVariable(name = "blockHash") HashDigest blockHash) { - LedgerBlock currentBlock = peerService.getQueryService().getBlock(ledgerHash, blockHash); - long currentBlockContractCount = peerService.getQueryService().getContractCount(ledgerHash, blockHash); - if (currentBlock.getHeight() == GENESIS_BLOCK_HEIGHT) { - return currentBlockContractCount; - } - HashDigest previousHash = currentBlock.getPreviousHash(); - long lastBlockContractCount = peerService.getQueryService().getUserCount(ledgerHash, previousHash); - // 当前区块合约数量减上个区块合约数量 - return currentBlockContractCount - lastBlockContractCount; - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/contracts/additional-count") - @Override - public long getAdditionalContractCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - LedgerInfo ledgerInfo = peerService.getQueryService().getLedger(ledgerHash); - long maxBlockHeight = ledgerInfo.getLatestBlockHeight(); - long totalCount = peerService.getQueryService().getContractTotalCount(ledgerHash); - if (maxBlockHeight == GENESIS_BLOCK_HEIGHT) { // 只有一个创世区块 - return totalCount; - } - long lastTotalCount = peerService.getQueryService().getContractCount(ledgerHash, maxBlockHeight - 1); - return totalCount - lastTotalCount; - } - - @RequestMapping(method = RequestMethod.GET, path = "utils/pubkey/{pubkey}/addr") - public String getAddrByPubKey(@PathVariable(name = "pubkey") String strPubKey) { - PubKey pubKey = KeyGenCommand.decodePubKey(strPubKey); - return AddressEncoding.generateAddress(pubKey).toBase58(); - } - - @RequestMapping(method = RequestMethod.GET, value = "ledgers/{ledgerHash}/**/search") - public Object dataRetrieval(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - HttpServletRequest request) { - String result; - if (dataRetrievalUrl == null || dataRetrievalUrl.length() <= 0) { - result = "{'message':'OK','data':'" + "data.retrieval.url is empty" + "'}"; - } else { - String queryParams = request.getQueryString() == null ? "": request.getQueryString(); - String fullQueryUrl = new StringBuffer(dataRetrievalUrl) - .append(request.getRequestURI()) - .append(BaseConstant.DELIMETER_QUESTION) - .append(queryParams) - .toString(); - try { - result = dataRetrievalService.retrieval(fullQueryUrl); - ConsoleUtils.info("request = {%s} \r\n result = {%s} \r\n", fullQueryUrl, result); - } catch (Exception e) { - result = "{'message':'OK','data':'" + e.getMessage() + "'}"; - } - } - return result; - } - - public void setDataRetrievalUrl(String dataRetrievalUrl) { - this.dataRetrievalUrl = dataRetrievalUrl; - } - - /** - * get all ledgers count; - */ - @RequestMapping(method = RequestMethod.GET, path = "ledgers/count") - @Override - public int getLedgersCount() { - return peerService.getQueryService().getLedgerHashs().length; - } - - /** - * get all ledgers hashs; - */ - @RequestMapping(method = RequestMethod.GET, path = "ledgers") - public HashDigest[] getLedgersHash(@RequestParam(name = "fromIndex", required = false, defaultValue = "0") int fromIndex, - @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { - return gatewayQueryService.getLedgersHash(fromIndex, count); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/participants/count") - public int getConsensusParticipantCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { - return peerService.getQueryService().getConsensusParticipants(ledgerHash).length; - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/participants") - public ParticipantNode[] getConsensusParticipants(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @RequestParam(name = "fromIndex", required = false, defaultValue = "0") int fromIndex, - @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { - return gatewayQueryService.getConsensusParticipants(ledgerHash,fromIndex,count); - } - - /** - * get more users by fromIndex and count; - * @param ledgerHash - * @param fromIndex - * @param count - * @return - */ - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/users") - @Override - public AccountHeader[] getUsers(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @RequestParam(name = "fromIndex", required = false, defaultValue = "0") int fromIndex, - @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { - return peerService.getQueryService().getUsers(ledgerHash, fromIndex, count); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/accounts") - @Override - public AccountHeader[] getDataAccounts(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @RequestParam(name = "fromIndex", required = false, defaultValue = "0") int fromIndex, - @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { - return peerService.getQueryService().getDataAccounts(ledgerHash, fromIndex, count); - } - - @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/contracts") - @Override - public AccountHeader[] getContractAccounts(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, - @RequestParam(name = "fromIndex", required = false, defaultValue = "0") int fromIndex, - @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { - return peerService.getQueryService().getContractAccounts(ledgerHash, fromIndex, count); - } + @Override + public ContractInfo getContract(HashDigest ledgerHash, String address) { + return peerService.getQueryService().getContract(ledgerHash, address); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/latest") + @Override + public LedgerBlock getLatestBlock(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { + long latestBlockHeight = peerService.getQueryService().getLedger(ledgerHash).getLatestBlockHeight(); + return peerService.getQueryService().getBlock(ledgerHash, latestBlockHeight); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/txs/additional-count") + @Override + public long getAdditionalTransactionCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @PathVariable(name = "blockHeight") long blockHeight) { + // 获取某个区块的交易总数 + long currentBlockTxCount = peerService.getQueryService().getTransactionCount(ledgerHash, blockHeight); + if (blockHeight == GENESIS_BLOCK_HEIGHT) { + return currentBlockTxCount; + } + long lastBlockHeight = blockHeight - 1; + long lastBlockTxCount = peerService.getQueryService().getTransactionCount(ledgerHash, lastBlockHeight); + // 当前区块交易数减上个区块交易数 + return currentBlockTxCount - lastBlockTxCount; + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/txs/additional-count") + @Override + public long getAdditionalTransactionCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @PathVariable(name = "blockHash") HashDigest blockHash) { + LedgerBlock currentBlock = peerService.getQueryService().getBlock(ledgerHash, blockHash); + long currentBlockTxCount = peerService.getQueryService().getTransactionCount(ledgerHash, blockHash); + if (currentBlock.getHeight() == GENESIS_BLOCK_HEIGHT) { + return currentBlockTxCount; + } + HashDigest previousHash = currentBlock.getPreviousHash(); + long lastBlockTxCount = peerService.getQueryService().getTransactionCount(ledgerHash, previousHash); + // 当前区块交易数减上个区块交易数 + return currentBlockTxCount - lastBlockTxCount; + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/txs/additional-count") + @Override + public long getAdditionalTransactionCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { + LedgerInfo ledgerInfo = peerService.getQueryService().getLedger(ledgerHash); + long maxBlockHeight = ledgerInfo.getLatestBlockHeight(); + long totalCount = peerService.getQueryService().getTransactionTotalCount(ledgerHash); + if (maxBlockHeight == GENESIS_BLOCK_HEIGHT) { // 只有一个创世区块 + return totalCount; + } + long lastTotalCount = peerService.getQueryService().getTransactionCount(ledgerHash, maxBlockHeight - 1); + return totalCount - lastTotalCount; + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/accounts/additional-count") + @Override + public long getAdditionalDataAccountCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @PathVariable(name = "blockHeight") long blockHeight) { + long currentDaCount = peerService.getQueryService().getDataAccountCount(ledgerHash, blockHeight); + if (blockHeight == GENESIS_BLOCK_HEIGHT) { + return currentDaCount; + } + long lastBlockHeight = blockHeight - 1; + long lastDaCount = peerService.getQueryService().getDataAccountCount(ledgerHash, lastBlockHeight); + return currentDaCount - lastDaCount; + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/accounts/additional-count") + @Override + public long getAdditionalDataAccountCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @PathVariable(name = "blockHash") HashDigest blockHash) { + LedgerBlock currentBlock = peerService.getQueryService().getBlock(ledgerHash, blockHash); + long currentBlockDaCount = peerService.getQueryService().getDataAccountCount(ledgerHash, blockHash); + if (currentBlock.getHeight() == GENESIS_BLOCK_HEIGHT) { + return currentBlockDaCount; + } + HashDigest previousHash = currentBlock.getPreviousHash(); + long lastBlockDaCount = peerService.getQueryService().getDataAccountCount(ledgerHash, previousHash); + // 当前区块数据账户数量减上个区块数据账户数量 + return currentBlockDaCount - lastBlockDaCount; + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/accounts/additional-count") + @Override + public long getAdditionalDataAccountCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { + LedgerInfo ledgerInfo = peerService.getQueryService().getLedger(ledgerHash); + long maxBlockHeight = ledgerInfo.getLatestBlockHeight(); + long totalCount = peerService.getQueryService().getDataAccountTotalCount(ledgerHash); + if (maxBlockHeight == GENESIS_BLOCK_HEIGHT) { // 只有一个创世区块 + return totalCount; + } + long lastTotalCount = peerService.getQueryService().getDataAccountCount(ledgerHash, maxBlockHeight - 1); + return totalCount - lastTotalCount; + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/users/additional-count") + @Override + public long getAdditionalUserCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @PathVariable(name = "blockHeight") long blockHeight) { + long currentUserCount = peerService.getQueryService().getUserCount(ledgerHash, blockHeight); + if (blockHeight == GENESIS_BLOCK_HEIGHT) { + return currentUserCount; + } + long lastBlockHeight = blockHeight - 1; + long lastUserCount = peerService.getQueryService().getUserCount(ledgerHash, lastBlockHeight); + return currentUserCount - lastUserCount; + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/users/additional-count") + @Override + public long getAdditionalUserCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @PathVariable(name = "blockHash") HashDigest blockHash) { + LedgerBlock currentBlock = peerService.getQueryService().getBlock(ledgerHash, blockHash); + long currentBlockUserCount = peerService.getQueryService().getUserCount(ledgerHash, blockHash); + if (currentBlock.getHeight() == GENESIS_BLOCK_HEIGHT) { + return currentBlockUserCount; + } + HashDigest previousHash = currentBlock.getPreviousHash(); + long lastBlockUserCount = peerService.getQueryService().getUserCount(ledgerHash, previousHash); + // 当前区块用户数量减上个区块用户数量 + return currentBlockUserCount - lastBlockUserCount; + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/users/additional-count") + @Override + public long getAdditionalUserCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { + LedgerInfo ledgerInfo = peerService.getQueryService().getLedger(ledgerHash); + long maxBlockHeight = ledgerInfo.getLatestBlockHeight(); + long totalCount = peerService.getQueryService().getUserTotalCount(ledgerHash); + if (maxBlockHeight == GENESIS_BLOCK_HEIGHT) { // 只有一个创世区块 + return totalCount; + } + long lastTotalCount = peerService.getQueryService().getUserCount(ledgerHash, maxBlockHeight - 1); + return totalCount - lastTotalCount; + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/height/{blockHeight}/contracts/additional-count") + @Override + public long getAdditionalContractCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @PathVariable(name = "blockHeight") long blockHeight) { + long currentContractCount = peerService.getQueryService().getContractCount(ledgerHash, blockHeight); + if (blockHeight == GENESIS_BLOCK_HEIGHT) { + return currentContractCount; + } + long lastBlockHeight = blockHeight - 1; + long lastContractCount = peerService.getQueryService().getUserCount(ledgerHash, lastBlockHeight); + return currentContractCount - lastContractCount; + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/blocks/hash/{blockHash}/contracts/additional-count") + @Override + public long getAdditionalContractCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @PathVariable(name = "blockHash") HashDigest blockHash) { + LedgerBlock currentBlock = peerService.getQueryService().getBlock(ledgerHash, blockHash); + long currentBlockContractCount = peerService.getQueryService().getContractCount(ledgerHash, blockHash); + if (currentBlock.getHeight() == GENESIS_BLOCK_HEIGHT) { + return currentBlockContractCount; + } + HashDigest previousHash = currentBlock.getPreviousHash(); + long lastBlockContractCount = peerService.getQueryService().getUserCount(ledgerHash, previousHash); + // 当前区块合约数量减上个区块合约数量 + return currentBlockContractCount - lastBlockContractCount; + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/contracts/additional-count") + @Override + public long getAdditionalContractCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { + LedgerInfo ledgerInfo = peerService.getQueryService().getLedger(ledgerHash); + long maxBlockHeight = ledgerInfo.getLatestBlockHeight(); + long totalCount = peerService.getQueryService().getContractTotalCount(ledgerHash); + if (maxBlockHeight == GENESIS_BLOCK_HEIGHT) { // 只有一个创世区块 + return totalCount; + } + long lastTotalCount = peerService.getQueryService().getContractCount(ledgerHash, maxBlockHeight - 1); + return totalCount - lastTotalCount; + } + + @RequestMapping(method = RequestMethod.GET, path = "utils/pubkey/{pubkey}/addr") + public String getAddrByPubKey(@PathVariable(name = "pubkey") String strPubKey) { + PubKey pubKey = KeyGenUtils.decodePubKey(strPubKey); + return AddressEncoding.generateAddress(pubKey).toBase58(); + } + + @RequestMapping(method = RequestMethod.GET, value = "ledgers/{ledgerHash}/**/search") + public Object dataRetrieval(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, HttpServletRequest request) { + String result; + if (dataRetrievalUrl == null || dataRetrievalUrl.length() <= 0) { + result = "{'message':'OK','data':'" + "data.retrieval.url is empty" + "'}"; + } else { + String queryParams = request.getQueryString() == null ? "" : request.getQueryString(); + String fullQueryUrl = new StringBuffer(dataRetrievalUrl).append(request.getRequestURI()) + .append(BaseConstant.DELIMETER_QUESTION).append(queryParams).toString(); + try { + result = dataRetrievalService.retrieval(fullQueryUrl); + ConsoleUtils.info("request = {%s} \r\n result = {%s} \r\n", fullQueryUrl, result); + } catch (Exception e) { + result = "{'message':'OK','data':'" + e.getMessage() + "'}"; + } + } + return result; + } + + public void setDataRetrievalUrl(String dataRetrievalUrl) { + this.dataRetrievalUrl = dataRetrievalUrl; + } + + /** + * get all ledgers count; + */ + @RequestMapping(method = RequestMethod.GET, path = "ledgers/count") + @Override + public int getLedgersCount() { + return peerService.getQueryService().getLedgerHashs().length; + } + + // 注: 账本的数量不会很多,不需要分页; +// /** +// * get all ledgers hashs; +// */ +// @RequestMapping(method = RequestMethod.GET, path = "ledgers") +// public HashDigest[] getLedgersHash( +// @RequestParam(name = "fromIndex", required = false, defaultValue = "0") int fromIndex, +// @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { +// return gatewayQueryService.getLedgersHash(fromIndex, count); +// } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/participants/count") + public int getConsensusParticipantCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { + return peerService.getQueryService().getConsensusParticipants(ledgerHash).length; + } + +// @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/participants") +// public ParticipantNode[] getConsensusParticipants(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, +// @RequestParam(name = "fromIndex", required = false, defaultValue = "0") int fromIndex, +// @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { +// +// ParticipantNode participantNode[] = peerService.getQueryService().getConsensusParticipants(ledgerHash); +// int indexAndCount[] = QueryUtil.calFromIndexAndCount(fromIndex, count, participantNode.length); +// ParticipantNode participantNodesNew[] = Arrays.copyOfRange(participantNode, indexAndCount[0], +// indexAndCount[0] + indexAndCount[1]); +// return participantNodesNew; +// } + + /** + * get more users by fromIndex and count; + * + * @param ledgerHash + * @param fromIndex + * @param count + * @return + */ + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/users") + @Override + public AccountHeader[] getUsers(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @RequestParam(name = "fromIndex", required = false, defaultValue = "0") int fromIndex, + @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { + return peerService.getQueryService().getUsers(ledgerHash, fromIndex, count); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/accounts") + @Override + public AccountHeader[] getDataAccounts(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @RequestParam(name = "fromIndex", required = false, defaultValue = "0") int fromIndex, + @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { + return peerService.getQueryService().getDataAccounts(ledgerHash, fromIndex, count); + } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/contracts") + @Override + public AccountHeader[] getContractAccounts(@PathVariable(name = "ledgerHash") HashDigest ledgerHash, + @RequestParam(name = "fromIndex", required = false, defaultValue = "0") int fromIndex, + @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { + return peerService.getQueryService().getContractAccounts(ledgerHash, fromIndex, count); + } } diff --git a/source/gateway/src/main/java/com/jd/blockchain/gateway/web/GatewayWebServerConfigurer.java b/source/gateway/src/main/java/com/jd/blockchain/gateway/web/GatewayWebServerConfigurer.java index 4481088f..5fa20ae0 100644 --- a/source/gateway/src/main/java/com/jd/blockchain/gateway/web/GatewayWebServerConfigurer.java +++ b/source/gateway/src/main/java/com/jd/blockchain/gateway/web/GatewayWebServerConfigurer.java @@ -35,6 +35,9 @@ public class GatewayWebServerConfigurer implements WebMvcConfigurer { JSONSerializeUtils.disableCircularReferenceDetect(); JSONSerializeUtils.configStringSerializer(ByteArray.class); DataContractRegistry.register(BftsmartNodeSettings.class); + + + DataContractRegistry.register(LedgerAdminInfo.class); } diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AccountPrivilege.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AccountPrivilege.java deleted file mode 100644 index c57debff..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AccountPrivilege.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.jd.blockchain.ledger.core; - -public interface AccountPrivilege { - - /** - * 数据“读”的操作码; - * - * @return - */ - byte getReadingOpCode(); - - /** - * “写”的操作码; - * - * @return - */ - byte getWrittingOpCode(); - - /** - * 其它的扩展操作码; - * - * @return - */ - byte[] getExtOpCodes(); - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AccountSet.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AccountSet.java index bb57cd3c..dc4a59cd 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AccountSet.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AccountSet.java @@ -12,6 +12,7 @@ import com.jd.blockchain.ledger.AccountHeader; import com.jd.blockchain.ledger.BytesValue; 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; @@ -48,6 +49,10 @@ public class AccountSet implements Transactional, MerkleProvable { public boolean isReadonly() { return merkleDataset.isReadonly(); } + + void setReadonly() { + merkleDataset.setReadonly(); + } public AccountSet(CryptoSetting cryptoSetting, String keyPrefix, ExPolicyKVStorage exStorage, VersioningKVStorage verStorage, AccountAccessPolicy accessPolicy) { @@ -65,10 +70,6 @@ public class AccountSet implements Transactional, MerkleProvable { this.accessPolicy = accessPolicy; } - // public HashDigest getAccountRootHash() { - // return merkleDataset.getRootHash(); - // } - @Override public HashDigest getRootHash() { return merkleDataset.getRootHash(); diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AuthorizableDataSet.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AuthorizableDataSet.java deleted file mode 100644 index ca0a406a..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AuthorizableDataSet.java +++ /dev/null @@ -1,168 +0,0 @@ -//package com.jd.blockchain.ledger.core; -// -//import com.jd.blockchain.crypto.hash.HashDigest; -// -//import my.utils.Scratchable; -//import my.utils.io.ByteArray; -//import my.utils.io.BytesUtils; -//import my.utils.io.ExistancePolicyKVStorage; -//import my.utils.io.VersioningKVStorage; -// -///** -// * 可进行授权控制的数据集合; -// * -// * @author huanghaiquan -// * -// */ -//public class AuthorizableDataSet implements Scratchable { -// -// public static final String DATA_PREFIX = "DATA" + LedgerConsts.KEY_SEPERATOR; -//// public static final String PRIVILEGE_PREFIX = "PRVL" + LedgerConsts.KEY_SEPERATOR; -// -// private static final String DEFAULT_PRIVILEGE_KEY = "%"; -// -// private DataAccessable accessable; -// -// protected MerkleDataSet data; -// -//// private PrivilegeDataSet privileges; -// -// /** -// * Create a new Account instance; -// * -// * @param address -// * @param pubKey -// */ -// protected AuthorizableDataSet(CryptoSetting merkleTreeSetting, ExistancePolicyKVStorage simpleStorage, -// VersioningKVStorage versioningStorage) { -// this(null, merkleTreeSetting, null, simpleStorage, versioningStorage); -// } -// -// protected AuthorizableDataSet(byte[] dataRootHash, CryptoSetting merkleTreeSetting, byte[] privilegeRootHash, -// ExistancePolicyKVStorage simpleStorage, VersioningKVStorage versioningStorage) { -// this(dataRootHash, merkleTreeSetting, privilegeRootHash, simpleStorage, versioningStorage, false); -// } -// -// protected AuthorizableDataSet(byte[] dataRootHash, CryptoSetting merkleTreeSetting, byte[] privilegeRootHash, -// ExistancePolicyKVStorage simpleStorage, VersioningKVStorage versioningStorage, boolean readonly) { -// this.data = new MerkleDataSet(dataRootHash, merkleTreeSetting, -// PrefixAppender.prefix(DATA_PREFIX, simpleStorage), -// PrefixAppender.prefix(DATA_PREFIX, versioningStorage), readonly); -// -//// this.privileges = new PrivilegeDataSet(privilegeRootHash, merkleTreeSetting, -//// PrefixAppender.prefix(PRIVILEGE_PREFIX, simpleStorage), -//// PrefixAppender.prefix(PRIVILEGE_PREFIX, versioningStorage), readonly); -// } -// -// public ByteArray getDataRootHash() { -// return data.getRootHash(); -// } -// -//// public ByteArray getPrivilegeRootHash() { -//// return privileges.getRootHash(); -//// } -// -// /** -// * -// * @param userAddress -// * @param op -// * @param enable -// */ -// public void setPrivilege(String userAddress, byte op, boolean enable) { -// -// } -// -// /** -// * -// * @param op -// * @param enable -// */ -// public void setDefaultPrivilege(byte op, boolean enable) { -// } -// -// public boolean checkCurrentUserPrivilege() { -// return false; -// } -// -// /** -// * Return the latest version entry associated the specified key; If the key -// * doesn't exist, then return -1; -// * -// * @param key -// * @return -// */ -// public long getVersion(String key) { -// return data.getVersion(key); -// } -// -// protected long setString(String key, String value, long version) { -// checkWritting(); -// byte[] bytes = BytesUtils.toBytes(value, LedgerConsts.CHARSET); -// return data.setValue(key, bytes, version); -// } -// -// protected String getString(String key) { -// checkReading(); -// byte[] value = data.getValue(key); -// return BytesUtils.toString(value, LedgerConsts.CHARSET); -// } -// -// protected String getString(String key, long version) { -// checkReading(); -// byte[] value = data.getValue(key, version); -// return BytesUtils.toString(value, LedgerConsts.CHARSET); -// } -// -// protected long setValue(String key, byte[] value, long version) { -// checkWritting(); -// return data.setValue(key, value, version); -// } -// -// protected byte[] getValue(String key) { -// checkReading(); -// return data.getValue(key); -// } -// -// protected byte[] getValue(String key, long version) { -// checkReading(); -// return data.getValue(key, version); -// } -// -// private void checkWritting() { -// // Check writting enable; -// } -// -// private void checkReading() { -// // TODO Check privilege of reading; -// } -// -// // /** -// // * 数据“读”的操作码; -// // * -// // * @return -// // */ -// // protected abstract AccountPrivilege getPrivilege(); -// -// @Override -// public boolean isUpdated() { -// return data.isUpdated(); -//// return data.isUpdated()|| privileges.isUpdated(); -// } -// -// @Override -// public void commit() { -// if (data.isUpdated()) { -// data.commit(); -// } -//// if (privileges.isUpdated()) { -//// privileges.commit(); -//// } -// } -// -// @Override -// public void cancel() { -// data.cancel(); -//// privileges.cancel(); -// } -// -//} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/Authorization.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/Authorization.java deleted file mode 100644 index cba2ffe4..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/Authorization.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.ledger.DigitalSignature; - -/** - * {@link Authorization} 抽象了对特定用户/角色的授权信息; - * - * @author huanghaiquan - * - */ -public interface Authorization { - - /** - * 被授权用户/角色的地址; - * - * @return - */ - String getAddress(); - - /** - * 授权码;
- * - * @return - */ - byte[] getCode(); - - /** - * 授权者的签名; - * - * @return - */ - DigitalSignature getSignature(); - - // /** - // * 授权生成的时间戳; - // * @return - // */ - // long getTs(); - -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AuthorizationVO.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AuthorizationVO.java deleted file mode 100644 index 24d7f125..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/AuthorizationVO.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.ledger.DigitalSignature; - -public class AuthorizationVO implements Authorization { - - private String address; - - private byte[] code; - - private DigitalSignature signature; - - - @Override - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - - @Override - public byte[] getCode() { - return code; - } - - public void setCode(byte[] code) { - this.code = code; - } - - @Override - public DigitalSignature getSignature() { - return signature; - } - - - public void setSignature(DigitalSignature signature) { - this.signature = signature; - } - -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/BaseAccount.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/BaseAccount.java index 9a57c6d0..1c9b778f 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/BaseAccount.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/BaseAccount.java @@ -8,6 +8,7 @@ import com.jd.blockchain.ledger.BlockchainIdentity; import com.jd.blockchain.ledger.BlockchainIdentityData; import com.jd.blockchain.ledger.BytesValue; import com.jd.blockchain.ledger.CryptoSetting; +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; @@ -64,13 +65,13 @@ public class BaseAccount implements AccountHeader, MerkleProvable, Transactional /** * Create a account instance with the specified address and pubkey and load it's - * merkle dataset with the specified root hash. which is used for storing data + * merkle dataset from the specified root hash. This merkle dateset is used for storing data * of this account.
* * @param address * @param pubKey - * @param dataRootHash merkle root hash of account's data; if null be set, - * create a new empty merkle dataset; + * @param dataRootHash merkle root hash of account's data; if set to a null value, + * an empty merkle dataset is created; * @param cryptoSetting * @param exStorage * @param verStorage diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/Consensus.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/Consensus.java deleted file mode 100644 index da7b6104..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/Consensus.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jd.blockchain.ledger.core; - - -/** - * @author hhq - * @version 1.0 - * @created 14-6��-2018 12:13:32 - */ -public class Consensus { - - public P2PRealm m_P2PRealm; - - public Consensus(){ - - } - - public void finalize() throws Throwable { - - } - -} \ No newline at end of file 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 c4a94ee6..9f4a8622 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 @@ -2,10 +2,10 @@ package com.jd.blockchain.ledger.core; import com.jd.blockchain.crypto.HashDigest; import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.AccountHeader; -import com.jd.blockchain.ledger.BytesValue; import com.jd.blockchain.ledger.BytesData; +import com.jd.blockchain.ledger.BytesValue; import com.jd.blockchain.ledger.ContractInfo; +import com.jd.blockchain.ledger.MerkleProof; import com.jd.blockchain.utils.Bytes; public class ContractAccount implements ContractInfo { diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ContractAccountQuery.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ContractAccountQuery.java new file mode 100644 index 00000000..4013a239 --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ContractAccountQuery.java @@ -0,0 +1,29 @@ +package com.jd.blockchain.ledger.core; + +import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.ledger.AccountHeader; +import com.jd.blockchain.ledger.MerkleProof; +import com.jd.blockchain.utils.Bytes; + +public interface ContractAccountQuery { + + AccountHeader[] getAccounts(int fromIndex, int count); + + HashDigest getRootHash(); + + /** + * 返回合约总数; + * + * @return + */ + long getTotalCount(); + + MerkleProof getProof(Bytes address); + + boolean contains(Bytes address); + + ContractAccount getContract(Bytes address); + + ContractAccount getContract(Bytes address, long version); + +} \ 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 039be73d..89d3ab3d 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 @@ -5,12 +5,13 @@ import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.ledger.AccountHeader; 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 MerkleProvable, Transactional { +public class ContractAccountSet implements MerkleProvable, Transactional, ContractAccountQuery { private AccountSet accountSet; @@ -25,6 +26,7 @@ public class ContractAccountSet implements MerkleProvable, Transactional { accountSet = new AccountSet(dataRootHash, cryptoSetting, prefix, exStorage, verStorage, readonly, accessPolicy); } + @Override public AccountHeader[] getAccounts(int fromIndex, int count) { return accountSet.getAccounts(fromIndex,count); } @@ -33,6 +35,10 @@ public class ContractAccountSet implements MerkleProvable, Transactional { return accountSet.isReadonly(); } + void setReadonly() { + accountSet.setReadonly(); + } + @Override public HashDigest getRootHash() { return accountSet.getRootHash(); @@ -43,6 +49,7 @@ public class ContractAccountSet implements MerkleProvable, Transactional { * * @return */ + @Override public long getTotalCount() { return accountSet.getTotalCount(); } @@ -52,15 +59,18 @@ public class ContractAccountSet implements MerkleProvable, Transactional { return accountSet.getProof(address); } + @Override public boolean contains(Bytes address) { return accountSet.contains(address); } + @Override public ContractAccount getContract(Bytes address) { BaseAccount accBase = accountSet.getAccount(address); return new ContractAccount(accBase); } + @Override public ContractAccount getContract(Bytes address, long version) { BaseAccount accBase = accountSet.getAccount(address, version); return new ContractAccount(accBase); diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/CryptoConfig.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/CryptoConfig.java index 8f5d2ea1..2a23f8bf 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/CryptoConfig.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/CryptoConfig.java @@ -82,7 +82,7 @@ public class CryptoConfig implements CryptoSetting { public void setHashAlgorithm(short hashAlgorithm) { if (codeAlgorithms == null || !codeAlgorithms.containsKey(hashAlgorithm)) { - throw new LedgerException("The specified algorithm[" + hashAlgorithm + "] has no provider!"); + throw new LedgerException("Current CryptoConfig has no crypto provider!"); } this.hashAlgorithm = hashAlgorithm; } 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 93286676..cee3c29e 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 @@ -8,6 +8,7 @@ import com.jd.blockchain.ledger.BytesData; import com.jd.blockchain.ledger.BytesValue; import com.jd.blockchain.ledger.KVDataEntry; import com.jd.blockchain.ledger.KVDataObject; +import com.jd.blockchain.ledger.MerkleProof; import com.jd.blockchain.utils.Bytes; public class DataAccount implements AccountHeader, MerkleProvable { diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DataAccountQuery.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DataAccountQuery.java new file mode 100644 index 00000000..b7cc8d43 --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DataAccountQuery.java @@ -0,0 +1,32 @@ +package com.jd.blockchain.ledger.core; + +import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.ledger.AccountHeader; +import com.jd.blockchain.ledger.MerkleProof; +import com.jd.blockchain.utils.Bytes; + +public interface DataAccountQuery { + + AccountHeader[] getAccounts(int fromIndex, int count); + + HashDigest getRootHash(); + + long getTotalCount(); + + /** + * 返回账户的存在性证明; + */ + MerkleProof getProof(Bytes address); + + /** + * 返回数据账户;
+ * 如果不存在,则返回 null; + * + * @param address + * @return + */ + DataAccount getDataAccount(Bytes address); + + DataAccount getDataAccount(Bytes address, long version); + +} \ 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 d44e9dbf..dbc77437 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 @@ -5,12 +5,13 @@ import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.ledger.AccountHeader; 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 MerkleProvable, Transactional { +public class DataAccountSet implements MerkleProvable, Transactional, DataAccountQuery { private AccountSet accountSet; @@ -25,6 +26,7 @@ public class DataAccountSet implements MerkleProvable, Transactional { accountSet = new AccountSet(dataRootHash, cryptoSetting, prefix, exStorage, verStorage, readonly, accessPolicy); } + @Override public AccountHeader[] getAccounts(int fromIndex, int count) { return accountSet.getAccounts(fromIndex, count); } @@ -33,11 +35,16 @@ public class DataAccountSet implements MerkleProvable, Transactional { return accountSet.isReadonly(); } + void setReadonly() { + accountSet.setReadonly(); + } + @Override public HashDigest getRootHash() { return accountSet.getRootHash(); } + @Override public long getTotalCount() { return accountSet.getTotalCount(); } @@ -63,6 +70,7 @@ public class DataAccountSet implements MerkleProvable, Transactional { * @param address * @return */ + @Override public DataAccount getDataAccount(Bytes address) { BaseAccount accBase = accountSet.getAccount(address); if (accBase == null) { @@ -71,6 +79,7 @@ public class DataAccountSet implements MerkleProvable, Transactional { return new DataAccount(accBase); } + @Override public DataAccount getDataAccount(Bytes address, long version) { BaseAccount accBase = accountSet.getAccount(address, version); return new DataAccount(accBase); diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DefaultOperationHandleRegisteration.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DefaultOperationHandleRegisteration.java new file mode 100644 index 00000000..6dd34e0a --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/DefaultOperationHandleRegisteration.java @@ -0,0 +1,132 @@ +package com.jd.blockchain.ledger.core; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.springframework.stereotype.Component; + +import com.jd.blockchain.ledger.LedgerException; +import com.jd.blockchain.ledger.Operation; +import com.jd.blockchain.ledger.core.handles.ContractCodeDeployOperationHandle; +import com.jd.blockchain.ledger.core.handles.DataAccountKVSetOperationHandle; +import com.jd.blockchain.ledger.core.handles.DataAccountRegisterOperationHandle; +import com.jd.blockchain.ledger.core.handles.JVMContractEventSendOperationHandle; +import com.jd.blockchain.ledger.core.handles.LedgerInitOperationHandle; +import com.jd.blockchain.ledger.core.handles.RolesConfigureOperationHandle; +import com.jd.blockchain.ledger.core.handles.UserAuthorizeOperationHandle; +import com.jd.blockchain.ledger.core.handles.UserRegisterOperationHandle; +import com.jd.blockchain.transaction.ContractCodeDeployOpTemplate; +import com.jd.blockchain.transaction.ContractEventSendOpTemplate; +import com.jd.blockchain.transaction.DataAccountKVSetOpTemplate; +import com.jd.blockchain.transaction.DataAccountRegisterOpTemplate; +import com.jd.blockchain.transaction.LedgerInitOpTemplate; +import com.jd.blockchain.transaction.RolesConfigureOpTemplate; +import com.jd.blockchain.transaction.UserAuthorizeOpTemplate; +import com.jd.blockchain.transaction.UserRegisterOpTemplate; + +@Component +public class DefaultOperationHandleRegisteration implements OperationHandleRegisteration { + + private static Map, OperationHandle> DEFAULT_HANDLES = new HashMap<>(); + + private Map, OperationHandle> handles = new ConcurrentHashMap<>(); + + static { + registerDefaultHandle(new LedgerInitOperationHandle()); + + registerDefaultHandle(new RolesConfigureOperationHandle()); + + registerDefaultHandle(new UserAuthorizeOperationHandle()); + + registerDefaultHandle(new UserRegisterOperationHandle()); + + registerDefaultHandle(new DataAccountKVSetOperationHandle()); + + registerDefaultHandle(new DataAccountRegisterOperationHandle()); + + registerDefaultHandle(new ContractCodeDeployOperationHandle()); + + registerDefaultHandle(new JVMContractEventSendOperationHandle()); + } + + private static void registerDefaultHandle(OperationHandle handle) { + DEFAULT_HANDLES.put(handle.getOperationType(), handle); + } + + /** + * 注册操作处理器;此方法将覆盖默认的操作处理器配置; + * + * @param handle + */ + public void registerHandle(OperationHandle handle) { + List> opTypes = new ArrayList>(); + for (Class opType : handles.keySet()) { + if (opType.isAssignableFrom(handle.getOperationType())) { + opTypes.add(opType); + } + } + + for (Class opType : opTypes) { + handles.put(opType, handle); + } + handles.put(handle.getOperationType(), handle); + } + + private OperationHandle getRegisteredHandle(Class operationType) { + OperationHandle hdl = handles.get(operationType); + if (hdl == null) { + hdl = DEFAULT_HANDLES.get(operationType); + + //按“操作类型”的继承关系匹配; + if (hdl == null) { + for (Class opType : handles.keySet()) { + if (opType.isAssignableFrom(operationType)) { + hdl = handles.get(opType); + break; + } + } + } + + if (hdl == null) { + for (Class opType : DEFAULT_HANDLES.keySet()) { + if (opType.isAssignableFrom(operationType)) { + hdl = DEFAULT_HANDLES.get(opType); + break; + } + } + } + + if (hdl != null) { + handles.put(operationType, hdl); + } + } + return hdl; + } + + /* + * (non-Javadoc) + * + * @see + * com.jd.blockchain.ledger.core.impl.OperationHandleRegisteration#getHandle( + * java.lang.Class) + */ + @Override + public OperationHandle getHandle(Class operationType) { + OperationHandle hdl = getRegisteredHandle(operationType); + if (hdl == null) { + throw new LedgerException("Unsupported operation type[" + operationType.getName() + "]!"); + } + return hdl; + } + + private static class OpHandleStub { + + private Class operationType; + + private OperationHandle operationHandle; + + } +} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/EmptyLedgerDataset.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/EmptyLedgerDataset.java new file mode 100644 index 00000000..64e08117 --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/EmptyLedgerDataset.java @@ -0,0 +1,209 @@ +package com.jd.blockchain.ledger.core; + +import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.ledger.AccountHeader; +import com.jd.blockchain.ledger.LedgerAdminInfo; +import com.jd.blockchain.ledger.MerkleProof; +import com.jd.blockchain.ledger.ParticipantDataQuery; +import com.jd.blockchain.ledger.ParticipantNode; +import com.jd.blockchain.utils.Bytes; + +public class EmptyLedgerDataset implements LedgerDataQuery { + + private static final LedgerAdminDataQuery EMPTY_ADMIN_DATA = new EmptyAdminData(); + + private static final UserAccountQuery EMPTY_USER_ACCOUNTS = new EmptyUserAccountSet(); + + private static final DataAccountQuery EMPTY_DATA_ACCOUNTS = new EmptyDataAccountSet(); + + private static final ContractAccountQuery EMPTY_CONTRACT_ACCOUNTS = new EmptyContractAccountSet(); + + private static final ParticipantDataQuery EMPTY_PARTICIPANTS = new EmptyParticipantData(); + + @Override + public LedgerAdminDataQuery getAdminDataset() { + return EMPTY_ADMIN_DATA; + } + + @Override + public UserAccountQuery getUserAccountSet() { + return EMPTY_USER_ACCOUNTS; + } + + @Override + public DataAccountQuery getDataAccountSet() { + return EMPTY_DATA_ACCOUNTS; + } + + @Override + public ContractAccountQuery getContractAccountset() { + return EMPTY_CONTRACT_ACCOUNTS; + } + + + private static class EmptyAdminData implements LedgerAdminDataQuery{ + + + @Override + public LedgerAdminInfo getAdminInfo() { + return null; + } + + @Override + public ParticipantDataQuery getParticipantDataset() { + return EMPTY_PARTICIPANTS; + } + + } + + private static class EmptyParticipantData implements ParticipantDataQuery{ + + @Override + public HashDigest getRootHash() { + return null; + } + + @Override + public MerkleProof getProof(Bytes key) { + return null; + } + + @Override + public long getParticipantCount() { + return 0; + } + + @Override + public boolean contains(Bytes address) { + return false; + } + + @Override + public ParticipantNode getParticipant(Bytes address) { + return null; + } + + @Override + public ParticipantNode[] getParticipants() { + return null; + } + + } + + private static class EmptyUserAccountSet implements UserAccountQuery{ + + @Override + public AccountHeader[] getAccounts(int fromIndex, int count) { + return null; + } + + @Override + public long getTotalCount() { + return 0; + } + + @Override + public HashDigest getRootHash() { + return null; + } + + @Override + public MerkleProof getProof(Bytes key) { + return null; + } + + @Override + public UserAccount getUser(String address) { + return null; + } + + @Override + public UserAccount getUser(Bytes address) { + return null; + } + + @Override + public boolean contains(Bytes address) { + return false; + } + + @Override + public UserAccount getUser(Bytes address, long version) { + return null; + } + + + } + + private static class EmptyDataAccountSet implements DataAccountQuery{ + + @Override + public AccountHeader[] getAccounts(int fromIndex, int count) { + return null; + } + + @Override + public HashDigest getRootHash() { + return null; + } + + @Override + public long getTotalCount() { + return 0; + } + + @Override + public MerkleProof getProof(Bytes address) { + return null; + } + + @Override + public DataAccount getDataAccount(Bytes address) { + return null; + } + + @Override + public DataAccount getDataAccount(Bytes address, long version) { + return null; + } + + } + + private static class EmptyContractAccountSet implements ContractAccountQuery{ + + @Override + public AccountHeader[] getAccounts(int fromIndex, int count) { + return null; + } + + @Override + public HashDigest getRootHash() { + return null; + } + + @Override + public long getTotalCount() { + return 0; + } + + @Override + public MerkleProof getProof(Bytes address) { + return null; + } + + @Override + public boolean contains(Bytes address) { + return false; + } + + @Override + public ContractAccount getContract(Bytes address) { + return null; + } + + @Override + public ContractAccount getContract(Bytes address, long version) { + return null; + } + } +} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/FullPermissionedSecurityManager.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/FullPermissionedSecurityManager.java new file mode 100644 index 00000000..c217ee34 --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/FullPermissionedSecurityManager.java @@ -0,0 +1,98 @@ +package com.jd.blockchain.ledger.core; + +import java.util.Set; + +import com.jd.blockchain.ledger.LedgerPermission; +import com.jd.blockchain.ledger.LedgerSecurityException; +import com.jd.blockchain.ledger.TransactionPermission; +import com.jd.blockchain.utils.Bytes; + +class FullPermissionedSecurityManager implements LedgerSecurityManager { + + public static final FullPermissionedSecurityManager INSTANCE = new FullPermissionedSecurityManager(); + + @Override + public SecurityPolicy createSecurityPolicy(Set endpoints, Set nodes) { + return new FullPermissionedPolicy(endpoints, nodes); + } + + private static class FullPermissionedPolicy implements SecurityPolicy { + + private Set endpoints; + private Set nodes; + + public FullPermissionedPolicy(Set endpoints, Set nodes) { + this.endpoints = endpoints; + this.nodes = nodes; + } + + @Override + public Set getEndpoints() { + return endpoints; + } + + @Override + public Set getNodes() { + return nodes; + } + + @Override + public boolean isEndpointEnable(LedgerPermission permission, MultiIDsPolicy midPolicy) { + return true; + } + + @Override + public boolean isEndpointEnable(TransactionPermission permission, MultiIDsPolicy midPolicy) { + return true; + } + + @Override + public boolean isNodeEnable(LedgerPermission permission, MultiIDsPolicy midPolicy) { + return true; + } + + @Override + public boolean isNodeEnable(TransactionPermission permission, MultiIDsPolicy midPolicy) { + return true; + } + + @Override + public void checkEndpointPermission(LedgerPermission permission, MultiIDsPolicy midPolicy) + throws LedgerSecurityException { + } + + @Override + public void checkEndpointPermission(TransactionPermission permission, MultiIDsPolicy midPolicy) + throws LedgerSecurityException { + } + + @Override + public void checkNodePermission(LedgerPermission permission, MultiIDsPolicy midPolicy) throws LedgerSecurityException { + } + + @Override + public void checkNodePermission(TransactionPermission permission, MultiIDsPolicy midPolicy) + throws LedgerSecurityException { + } + + @Override + public boolean isEndpointValid(MultiIDsPolicy midPolicy) { + return true; + } + + @Override + public boolean isNodeValid(MultiIDsPolicy midPolicy) { + return true; + } + + @Override + public void checkEndpointValidity(MultiIDsPolicy midPolicy) throws LedgerSecurityException { + } + + @Override + public void checkNodeValidity(MultiIDsPolicy midPolicy) throws LedgerSecurityException { + } + + } + +} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/Gateway.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/Gateway.java deleted file mode 100644 index 6874d8aa..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/Gateway.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.ledger.ParticipantNode; - -/** - * @author hhq - * @version 1.0 - * @created 14-6��-2018 12:13:32 - */ -public class Gateway extends Node { - - public ParticipantNode m_Participant; - - public Gateway(){ - - } - - 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/impl/GenesisLedgerStorageProxy.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/GenesisLedgerStorageProxy.java similarity index 97% rename from source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/GenesisLedgerStorageProxy.java rename to source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/GenesisLedgerStorageProxy.java index 5682c50a..c93e1fed 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/GenesisLedgerStorageProxy.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/GenesisLedgerStorageProxy.java @@ -1,3 +1,4 @@ +package com.jd.blockchain.ledger.core; //package com.jd.blockchain.ledger.core.impl; // //import com.jd.blockchain.storage.service.ExPolicyKVStorage; diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerAdminDataQuery.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerAdminDataQuery.java new file mode 100644 index 00000000..05c62138 --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerAdminDataQuery.java @@ -0,0 +1,12 @@ +package com.jd.blockchain.ledger.core; + +import com.jd.blockchain.ledger.LedgerAdminInfo; +import com.jd.blockchain.ledger.ParticipantDataQuery; + +public interface LedgerAdminDataQuery { + + LedgerAdminInfo getAdminInfo(); + + ParticipantDataQuery getParticipantDataset(); + +} \ 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 new file mode 100644 index 00000000..c4961b12 --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerAdminDataset.java @@ -0,0 +1,469 @@ +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.LedgerAdminInfo; +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.UserRolesSettings; +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, LedgerAdminInfo { + + 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 UserRolesSettings getUserRoles() { + return userRoles; + } + + @Override + public LedgerAdminInfo 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 + */ + 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); + } + + @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/LedgerAdminPrivilege.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerAdminPrivilege.java deleted file mode 100644 index b436b5da..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerAdminPrivilege.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.jd.blockchain.ledger.core; - -public enum LedgerAdminPrivilege { - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerAdministration.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerAdministration.java deleted file mode 100644 index cc09138f..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerAdministration.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import com.jd.blockchain.ledger.LedgerMetadata; -import com.jd.blockchain.ledger.ParticipantNode; - -public interface LedgerAdministration { - - LedgerMetadata getMetadata(); - - long getParticipantCount(); - -// ParticipantNode getParticipant(int id); - - ParticipantNode[] getParticipants(); - -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerBlockData.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerBlockData.java similarity index 98% rename from source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerBlockData.java rename to source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerBlockData.java index 1e8865b7..3c667ebe 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerBlockData.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerBlockData.java @@ -1,4 +1,4 @@ -package com.jd.blockchain.ledger.core.impl; +package com.jd.blockchain.ledger.core; import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.crypto.HashDigest; diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerConfiguration.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerConfiguration.java index 5605003c..e727c5ad 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerConfiguration.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerConfiguration.java @@ -1,10 +1,10 @@ package com.jd.blockchain.ledger.core; import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.ledger.LedgerSetting; +import com.jd.blockchain.ledger.LedgerSettings; import com.jd.blockchain.utils.Bytes; -public class LedgerConfiguration implements LedgerSetting { +public class LedgerConfiguration implements LedgerSettings { private String consensusProvider; @@ -16,7 +16,7 @@ public class LedgerConfiguration implements LedgerSetting { this.cryptoSetting = new CryptoConfig(); } - public LedgerConfiguration(LedgerSetting origSetting) { + public LedgerConfiguration(LedgerSettings origSetting) { if (origSetting != null) { this.consensusProvider = origSetting.getConsensusProvider(); this.consensusSetting = origSetting.getConsensusSetting(); diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerDataQuery.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerDataQuery.java new file mode 100644 index 00000000..df70d0c0 --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerDataQuery.java @@ -0,0 +1,19 @@ +package com.jd.blockchain.ledger.core; + +/** + * {@link LedgerDataset} 表示账本在某一个区块上的数据集合; + * + * @author huanghaiquan + * + */ +public interface LedgerDataQuery{ + + LedgerAdminDataQuery getAdminDataset(); + + UserAccountQuery getUserAccountSet(); + + DataAccountQuery getDataAccountSet(); + + ContractAccountQuery getContractAccountset(); + +} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerDataSet.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerDataSet.java deleted file mode 100644 index 40f63da6..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerDataSet.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jd.blockchain.ledger.core; - -/** - * {@link LedgerDataSet} 表示账本在某一个区块上的数据集合; - * - * @author huanghaiquan - * - */ -public interface LedgerDataSet{ - - boolean isReadonly(); - - LedgerAdminAccount getAdminAccount(); - - UserAccountSet getUserAccountSet(); - - DataAccountSet getDataAccountSet(); - - ContractAccountSet getContractAccountSet(); - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerDataSetImpl.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerDataset.java similarity index 62% rename from source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerDataSetImpl.java rename to source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerDataset.java index 4ec9d657..9f840d35 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerDataSetImpl.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerDataset.java @@ -1,33 +1,31 @@ -package com.jd.blockchain.ledger.core.impl; +package com.jd.blockchain.ledger.core; -import com.jd.blockchain.ledger.core.*; import com.jd.blockchain.utils.Transactional; -public class LedgerDataSetImpl implements LedgerDataSet, Transactional { +public class LedgerDataset implements LedgerDataQuery, Transactional { - private LedgerAdminAccount adminAccount; + private LedgerAdminDataset adminDataset; private UserAccountSet userAccountSet; private DataAccountSet dataAccountSet; private ContractAccountSet contractAccountSet; - - private boolean readonly; + private boolean readonly; /** * Create new block; + * * @param adminAccount * @param userAccountSet * @param dataAccountSet * @param contractAccountSet * @param readonly */ - public LedgerDataSetImpl(LedgerAdminAccount adminAccount, - UserAccountSet userAccountSet, DataAccountSet dataAccountSet, ContractAccountSet contractAccountSet, - boolean readonly) { - this.adminAccount = adminAccount; + public LedgerDataset(LedgerAdminDataset adminAccount, UserAccountSet userAccountSet, + DataAccountSet dataAccountSet, ContractAccountSet contractAccountSet, boolean readonly) { + this.adminDataset = adminAccount; this.userAccountSet = userAccountSet; this.dataAccountSet = dataAccountSet; this.contractAccountSet = contractAccountSet; @@ -36,8 +34,8 @@ public class LedgerDataSetImpl implements LedgerDataSet, Transactional { } @Override - public LedgerAdminAccount getAdminAccount() { - return adminAccount; + public LedgerAdminDataset getAdminDataset() { + return adminDataset; } @Override @@ -51,13 +49,13 @@ public class LedgerDataSetImpl implements LedgerDataSet, Transactional { } @Override - public ContractAccountSet getContractAccountSet() { + public ContractAccountSet getContractAccountset() { return contractAccountSet; } @Override public boolean isUpdated() { - return adminAccount.isUpdated() || userAccountSet.isUpdated() || dataAccountSet.isUpdated() + return adminDataset.isUpdated() || userAccountSet.isUpdated() || dataAccountSet.isUpdated() || contractAccountSet.isUpdated(); } @@ -70,7 +68,7 @@ public class LedgerDataSetImpl implements LedgerDataSet, Transactional { return; } - adminAccount.commit(); + adminDataset.commit(); userAccountSet.commit(); dataAccountSet.commit(); contractAccountSet.commit(); @@ -78,15 +76,22 @@ public class LedgerDataSetImpl implements LedgerDataSet, Transactional { @Override public void cancel() { - adminAccount.cancel(); + adminDataset.cancel(); userAccountSet.cancel(); dataAccountSet.cancel(); contractAccountSet.cancel(); } - @Override public boolean isReadonly() { return readonly; } + void setReadonly() { + this.readonly = true; + this.adminDataset.setReadonly(); + this.userAccountSet.setReadonly(); + this.dataAccountSet.setReadonly(); + this.contractAccountSet.setReadonly(); + } + } \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerEditor.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerEditor.java index 46c21655..466dd30a 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerEditor.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerEditor.java @@ -11,7 +11,7 @@ import com.jd.blockchain.ledger.TransactionRequest; *

* * {@link LedgerEditor} 以上一个区块作为数据编辑的起点;
- * 对账本数据({@link #getDataSet()})的批量更改可以作为一个交易({@link LedgerTransaction})整体提交暂存,形成暂存点; + * 对账本数据({@link #getDataset()})的批量更改可以作为一个交易({@link LedgerTransaction})整体提交暂存,形成暂存点; *
* * @author huanghaiquan @@ -33,11 +33,25 @@ public interface LedgerEditor { */ long getBlockHeight(); + /** + * 最新的账本数据集; + * + * @return + */ + LedgerDataset getLedgerDataset(); + + /** + * 最新的交易集合; + * + * @return + */ + TransactionSet getTransactionSet(); + /** * 开始新事务;
* * 方法返回之前,将会校验交易请求的用户签名列表和节点签名列表,并在后续对数据集 - * {@link LedgerTransactionContext#getDataSet()} 的操作时,校验这些用户和节点是否具备权限;
+ * {@link LedgerTransactionContext#getDataset()} 的操作时,校验这些用户和节点是否具备权限;
* * 校验失败将引发异常 {@link LedgerException}; *

@@ -52,7 +66,8 @@ public interface LedgerEditor { * * * - * 注:方法不解析、不执行交易中的操作;

+ * 注:方法不解析、不执行交易中的操作; + *

* * @param txRequest 交易请求; * @return diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitPermission.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitProposal.java similarity index 92% rename from source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitPermission.java rename to source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitProposal.java index 7ca9e15c..2baaacbd 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitPermission.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitProposal.java @@ -13,8 +13,8 @@ import com.jd.blockchain.ledger.LedgerInitOperation; * @author huanghaiquan * */ -@DataContract(code = DataCodes.METADATA_INIT_PERMISSION) -public interface LedgerInitPermission { +@DataContract(code = DataCodes.METADATA_INIT_PROPOSAL) +public interface LedgerInitProposal { /** * 做出许可的参与方 ID; diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitPermissionData.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitProposalData.java similarity index 68% rename from source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitPermissionData.java rename to source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitProposalData.java index ead25a56..4fa95cb7 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitPermissionData.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitProposalData.java @@ -2,7 +2,7 @@ package com.jd.blockchain.ledger.core; import com.jd.blockchain.crypto.SignatureDigest; -public class LedgerInitPermissionData implements LedgerInitPermission { +public class LedgerInitProposalData implements LedgerInitProposal { private int participantId; @@ -11,10 +11,11 @@ public class LedgerInitPermissionData implements LedgerInitPermission { /** * a private contructor for deserialize; */ - private LedgerInitPermissionData() { + @SuppressWarnings("unused") + private LedgerInitProposalData() { } - public LedgerInitPermissionData(int participantId, SignatureDigest initTxSignature) { + public LedgerInitProposalData(int participantId, SignatureDigest initTxSignature) { this.participantId = participantId; this.transactionSignature = initTxSignature; } diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitializer.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitializer.java new file mode 100644 index 00000000..ca159135 --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerInitializer.java @@ -0,0 +1,215 @@ +package com.jd.blockchain.ledger.core; + +import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.SignatureDigest; +import com.jd.blockchain.ledger.BlockchainIdentity; +import com.jd.blockchain.ledger.BlockchainIdentityData; +import com.jd.blockchain.ledger.DigitalSignature; +import com.jd.blockchain.ledger.LedgerBlock; +import com.jd.blockchain.ledger.LedgerInitException; +import com.jd.blockchain.ledger.LedgerInitOperation; +import com.jd.blockchain.ledger.LedgerInitSetting; +import com.jd.blockchain.ledger.ParticipantNode; +import com.jd.blockchain.ledger.RoleInitSettings; +import com.jd.blockchain.ledger.RolesConfigureOperation; +import com.jd.blockchain.ledger.SecurityInitSettings; +import com.jd.blockchain.ledger.TransactionBuilder; +import com.jd.blockchain.ledger.TransactionContent; +import com.jd.blockchain.ledger.TransactionRequest; +import com.jd.blockchain.ledger.UserAuthInitSettings; +import com.jd.blockchain.ledger.UserAuthorizeOperation; +import com.jd.blockchain.ledger.UserRegisterOperation; +import com.jd.blockchain.service.TransactionBatchResultHandle; +import com.jd.blockchain.storage.service.KVStorageService; +import com.jd.blockchain.transaction.SignatureUtils; +import com.jd.blockchain.transaction.TxBuilder; +import com.jd.blockchain.transaction.TxRequestBuilder; + +public class LedgerInitializer { + + private static final FullPermissionedSecurityManager FULL_PERMISSION_SECURITY_MANAGER = new FullPermissionedSecurityManager(); + + private static final LedgerDataQuery EMPTY_LEDGER_DATA_QUERY = new EmptyLedgerDataset(); + + private static final OperationHandleRegisteration DEFAULT_OP_HANDLE_REG = new DefaultOperationHandleRegisteration(); + + private LedgerService EMPTY_LEDGERS = new LedgerManager(); + + private LedgerInitSetting initSetting; + + private TransactionContent initTxContent; + + private volatile LedgerBlock genesisBlock; + + private volatile LedgerEditor ledgerEditor; + + private volatile boolean committed = false; + + private volatile boolean canceled = false; + + private TransactionBatchResultHandle txResultsHandle; + + /** + * 初始化生成的账本hash;
+ * + * 在成功执行 {@link #prepareLedger(KVStorageService, DigitalSignature...)} 之前总是返回 + * null; + * + * @return + */ + public HashDigest getLedgerHash() { + return genesisBlock == null ? null : genesisBlock.getHash(); + } + + /** + * @param initSetting + * @param initTxContent + */ + private LedgerInitializer(LedgerInitSetting initSetting, TransactionContent initTxContent) { + this.initSetting = initSetting; + this.initTxContent = initTxContent; + } + + public TransactionContent getTransactionContent() { + return initTxContent; + } + + private static SecurityInitSettings createDefaultSecurityInitSettings() { + // TODO throw new IllegalStateException("Not implemented!"); + return null; + } + +// public static LedgerInitializer create(LedgerInitSetting initSetting) { +// return create(initSetting, createDefaultSecurityInitSettings()); +// } + + public static LedgerInitializer create(LedgerInitSetting initSetting, SecurityInitSettings securityInitSettings) { + // 生成创世交易; + TransactionContent initTxContent = buildGenesisTransaction(initSetting, securityInitSettings); + + return new LedgerInitializer(initSetting, initTxContent); + } + + /** + * 根据初始化配置,生成创始交易; + *

+ * + * “创世交易”按顺序由以下操作组成:
+ * (1) 账本初始化 {@link LedgerInitOperation}:此操作仅用于锚定了原始的交易配置,对应的 + * {@link OperationHandle} 执行空操作,由“创世交易”其余的操作来表达对账本的实际修改;
+ * (2) 注册用户 {@link UserRegisterOperation}:有一项或者多项;
+ * (3) 配置角色 {@link RolesConfigureOperation}:有一项或者多项;
+ * (4) 授权用户 {@link UserAuthorizeOperation}:有一项或者多项;
+ * + * @param initSetting + * @param securityInitSettings + * @return + */ + public static TransactionContent buildGenesisTransaction(LedgerInitSetting initSetting, + SecurityInitSettings securityInitSettings) { + // 账本初始化交易的账本 hash 为 null; + TransactionBuilder initTxBuilder = new TxBuilder(null); + + // 定义账本初始化操作; + initTxBuilder.ledgers().create(initSetting); + + // TODO: 注册参与方; 目前由 LedgerInitSetting 定义,在 LedgerAdminDataset 中解释执行; + + //  注册用户; + for (ParticipantNode p : initSetting.getConsensusParticipants()) { + // TODO:暂时只支持注册用户的初始化操作; + BlockchainIdentity superUserId = new BlockchainIdentityData(p.getPubKey()); + initTxBuilder.users().register(superUserId); + } + + // 配置角色; + for (RoleInitSettings roleSettings : securityInitSettings.getRoles()) { + initTxBuilder.security().roles().configure(roleSettings.getRoleName()) + .enable(roleSettings.getLedgerPermissions()).enable(roleSettings.getTransactionPermissions()); + } + + // 授权用户; + for (UserAuthInitSettings userAuthSettings : securityInitSettings.getUserAuthorizations()) { + initTxBuilder.security().authorziations().forUser(userAuthSettings.getUserAddress()) + .authorize(userAuthSettings.getRoles()) + .setPolicy(userAuthSettings.getPolicy()); + } + + // 账本初始化配置声明的创建时间来初始化交易时间戳;注:不能用本地时间,因为共识节点之间的本地时间系统不一致; + return initTxBuilder.prepareContent(initSetting.getCreatedTime()); + } + + public SignatureDigest signTransaction(PrivKey privKey) { + return SignatureUtils.sign(initTxContent, privKey); + } + + /** + * 准备创建账本; + * + * @param storageService 存储服务; + * @param nodeSignatures 节点签名列表; + * @return + */ + public LedgerBlock prepareLedger(KVStorageService storageService, DigitalSignature... nodeSignatures) { + if (genesisBlock != null) { + throw new LedgerInitException("The ledger has been prepared!"); + } + // 生成账本; + this.ledgerEditor = createLedgerEditor(this.initSetting, storageService); + this.genesisBlock = prepareLedger(ledgerEditor, nodeSignatures); + + return genesisBlock; + } + + public void commit() { + if (committed) { + throw new LedgerInitException("The ledger has been committed!"); + } + if (canceled) { + throw new LedgerInitException("The ledger has been canceled!"); + } + committed = true; + this.txResultsHandle.commit(); + } + + public void cancel() { + if (canceled) { + throw new LedgerInitException("The ledger has been canceled!"); + } + if (committed) { + throw new LedgerInitException("The ledger has been committed!"); + } + this.ledgerEditor.cancel(); + } + + public static LedgerEditor createLedgerEditor(LedgerInitSetting initSetting, KVStorageService storageService) { + LedgerEditor genesisBlockEditor = LedgerTransactionalEditor.createEditor(initSetting, + LedgerManage.LEDGER_PREFIX, storageService.getExPolicyKVStorage(), + storageService.getVersioningKVStorage()); + return genesisBlockEditor; + } + + /** + * 初始化账本数据,返回创始区块; + * + * @param ledgerEditor + * @return + */ + private LedgerBlock prepareLedger(LedgerEditor ledgerEditor, DigitalSignature... nodeSignatures) { + // 初始化时,自动将参与方注册为账本的用户; + TxRequestBuilder txReqBuilder = new TxRequestBuilder(this.initTxContent); + txReqBuilder.addNodeSignature(nodeSignatures); + + TransactionRequest txRequest = txReqBuilder.buildRequest(); + + TransactionBatchProcessor txProcessor = new TransactionBatchProcessor(FULL_PERMISSION_SECURITY_MANAGER, + ledgerEditor, EMPTY_LEDGER_DATA_QUERY, DEFAULT_OP_HANDLE_REG, EMPTY_LEDGERS); + + txProcessor.schedule(txRequest); + + txResultsHandle = txProcessor.prepare(); + return txResultsHandle.getBlock(); + } + +} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerManage.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerManage.java index 0e2ae587..65f8738b 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerManage.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerManage.java @@ -12,19 +12,21 @@ import com.jd.blockchain.storage.service.KVStorageService; */ public interface LedgerManage extends LedgerService { + static final String LEDGER_PREFIX = "LDG://"; + LedgerRepository register(HashDigest ledgerHash, KVStorageService storageService); void unregister(HashDigest ledgerHash); - /** - * 创建新账本; - * - * @param initSetting - * 初始化配置; - * @param initPermissions - * 参与者的初始化授权列表;与参与者列表一致; - * @return - */ - LedgerEditor newLedger(LedgerInitSetting initSetting, KVStorageService storageService); +// /** +// * 创建新账本; +// * +// * @param initSetting +// * 初始化配置; +// * @param initPermissions +// * 参与者的初始化授权列表;与参与者列表一致; +// * @return +// */ +// LedgerEditor newLedger(LedgerInitSetting initSetting, KVStorageService storageService); } \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerManager.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerManager.java similarity index 84% rename from source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerManager.java rename to source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerManager.java index 19dfee44..2e66b7ca 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerManager.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerManager.java @@ -1,4 +1,4 @@ -package com.jd.blockchain.ledger.core.impl; +package com.jd.blockchain.ledger.core; import java.util.HashMap; import java.util.Map; @@ -9,11 +9,6 @@ import com.jd.blockchain.crypto.CryptoProvider; import com.jd.blockchain.crypto.HashDigest; import com.jd.blockchain.ledger.CryptoSetting; import com.jd.blockchain.ledger.LedgerException; -import com.jd.blockchain.ledger.LedgerInitSetting; -import com.jd.blockchain.ledger.core.LedgerConsts; -import com.jd.blockchain.ledger.core.LedgerEditor; -import com.jd.blockchain.ledger.core.LedgerManage; -import com.jd.blockchain.ledger.core.LedgerRepository; import com.jd.blockchain.storage.service.ExPolicyKVStorage; import com.jd.blockchain.storage.service.KVStorageService; import com.jd.blockchain.storage.service.VersioningKVStorage; @@ -27,8 +22,6 @@ import com.jd.blockchain.utils.codec.Base58Utils; */ public class LedgerManager implements LedgerManage { - private static final String LEDGER_PREFIX = "LDG://"; - // @Autowired // private ExistentialKVStorage exPolicyStorage; // @@ -69,7 +62,7 @@ public class LedgerManager implements LedgerManage { ledgerVersioningStorage); // 校验 crypto service provider ; - CryptoSetting cryptoSetting = ledgerRepo.getAdminAccount().getSetting().getCryptoSetting(); + CryptoSetting cryptoSetting = ledgerRepo.getAdminInfo().getSettings().getCryptoSetting(); checkCryptoSetting(cryptoSetting, ledgerHash); // 创建账本上下文; @@ -142,18 +135,18 @@ public class LedgerManager implements LedgerManage { } } - /* - * (non-Javadoc) - * - * @see com.jd.blockchain.ledger.core.LedgerManager#newLedger(com.jd.blockchain. - * ledger.core.ConsensusConfig, com.jd.blockchain.ledger.core.CryptoConfig) - */ - @Override - public LedgerEditor newLedger(LedgerInitSetting initSetting, KVStorageService storageService) { - LedgerEditor genesisBlockEditor = LedgerTransactionalEditor.createEditor(initSetting, LEDGER_PREFIX, - storageService.getExPolicyKVStorage(), storageService.getVersioningKVStorage()); - return genesisBlockEditor; - } +// /* +// * (non-Javadoc) +// * +// * @see com.jd.blockchain.ledger.core.LedgerManager#newLedger(com.jd.blockchain. +// * ledger.core.ConsensusConfig, com.jd.blockchain.ledger.core.CryptoConfig) +// */ +// @Override +// public LedgerEditor newLedger(LedgerInitSetting initSetting, KVStorageService storageService) { +// LedgerEditor genesisBlockEditor = LedgerTransactionalEditor.createEditor(initSetting, LEDGER_PREFIX, +// storageService.getExPolicyKVStorage(), storageService.getVersioningKVStorage()); +// return genesisBlockEditor; +// } static String getLedgerStoragePrefix(HashDigest ledgerHash) { String base58LedgerHash = Base58Utils.encode(ledgerHash.toBytes()); diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerQueryService.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerQueryService.java similarity index 84% rename from source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerQueryService.java rename to source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerQueryService.java index 226be047..0b85c8c6 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerQueryService.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerQueryService.java @@ -1,19 +1,25 @@ -package com.jd.blockchain.ledger.core.impl; +package com.jd.blockchain.ledger.core; import java.util.ArrayList; import java.util.List; import com.jd.blockchain.contract.ContractException; import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.*; -import com.jd.blockchain.ledger.core.ContractAccountSet; -import com.jd.blockchain.ledger.core.DataAccount; -import com.jd.blockchain.ledger.core.DataAccountSet; -import com.jd.blockchain.ledger.core.LedgerAdministration; -import com.jd.blockchain.ledger.core.LedgerRepository; -import com.jd.blockchain.ledger.core.LedgerService; -import com.jd.blockchain.ledger.core.TransactionSet; -import com.jd.blockchain.ledger.core.UserAccountSet; +import com.jd.blockchain.ledger.AccountHeader; +import com.jd.blockchain.ledger.BytesValue; +import com.jd.blockchain.ledger.ContractInfo; +import com.jd.blockchain.ledger.KVDataEntry; +import com.jd.blockchain.ledger.KVDataObject; +import com.jd.blockchain.ledger.KVDataVO; +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.TransactionState; +import com.jd.blockchain.ledger.UserInfo; import com.jd.blockchain.transaction.BlockchainQueryService; import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.QueryUtil; @@ -42,15 +48,23 @@ public class LedgerQueryService implements BlockchainQueryService { ledgerInfo.setLatestBlockHeight(ledger.getLatestBlockHeight()); return ledgerInfo; } + + @Override + public LedgerAdminInfo getLedgerAdminInfo(HashDigest ledgerHash) { + LedgerRepository ledger = ledgerService.getLedger(ledgerHash); + LedgerBlock block = ledger.getLatestBlock(); + LedgerAdminInfo administration = ledger.getAdminInfo(block); + return administration; + } @Override public ParticipantNode[] getConsensusParticipants(HashDigest ledgerHash) { - return ledgerAdministration(ledgerHash).getParticipants(); + return getLedgerAdminInfo(ledgerHash).getParticipants(); } @Override public LedgerMetadata getLedgerMetadata(HashDigest ledgerHash) { - return ledgerAdministration(ledgerHash).getMetadata(); + return getLedgerAdminInfo(ledgerHash).getMetadata(); } @Override @@ -93,7 +107,7 @@ public class LedgerQueryService implements BlockchainQueryService { public long getDataAccountCount(HashDigest ledgerHash, long height) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getBlock(height); - DataAccountSet dataAccountSet = ledger.getDataAccountSet(block); + DataAccountQuery dataAccountSet = ledger.getDataAccountSet(block); return dataAccountSet.getTotalCount(); } @@ -101,7 +115,7 @@ public class LedgerQueryService implements BlockchainQueryService { public long getDataAccountCount(HashDigest ledgerHash, HashDigest blockHash) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getBlock(blockHash); - DataAccountSet dataAccountSet = ledger.getDataAccountSet(block); + DataAccountQuery dataAccountSet = ledger.getDataAccountSet(block); return dataAccountSet.getTotalCount(); } @@ -109,7 +123,7 @@ public class LedgerQueryService implements BlockchainQueryService { public long getDataAccountTotalCount(HashDigest ledgerHash) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getLatestBlock(); - DataAccountSet dataAccountSet = ledger.getDataAccountSet(block); + DataAccountQuery dataAccountSet = ledger.getDataAccountSet(block); return dataAccountSet.getTotalCount(); } @@ -117,7 +131,7 @@ public class LedgerQueryService implements BlockchainQueryService { public long getUserCount(HashDigest ledgerHash, long height) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getBlock(height); - UserAccountSet userAccountSet = ledger.getUserAccountSet(block); + UserAccountQuery userAccountSet = ledger.getUserAccountSet(block); return userAccountSet.getTotalCount(); } @@ -125,7 +139,7 @@ public class LedgerQueryService implements BlockchainQueryService { public long getUserCount(HashDigest ledgerHash, HashDigest blockHash) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getBlock(blockHash); - UserAccountSet userAccountSet = ledger.getUserAccountSet(block); + UserAccountQuery userAccountSet = ledger.getUserAccountSet(block); return userAccountSet.getTotalCount(); } @@ -133,7 +147,7 @@ public class LedgerQueryService implements BlockchainQueryService { public long getUserTotalCount(HashDigest ledgerHash) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getLatestBlock(); - UserAccountSet userAccountSet = ledger.getUserAccountSet(block); + UserAccountQuery userAccountSet = ledger.getUserAccountSet(block); return userAccountSet.getTotalCount(); } @@ -141,7 +155,7 @@ public class LedgerQueryService implements BlockchainQueryService { public long getContractCount(HashDigest ledgerHash, long height) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getBlock(height); - ContractAccountSet contractAccountSet = ledger.getContractAccountSet(block); + ContractAccountQuery contractAccountSet = ledger.getContractAccountSet(block); return contractAccountSet.getTotalCount(); } @@ -149,7 +163,7 @@ public class LedgerQueryService implements BlockchainQueryService { public long getContractCount(HashDigest ledgerHash, HashDigest blockHash) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getBlock(blockHash); - ContractAccountSet contractAccountSet = ledger.getContractAccountSet(block); + ContractAccountQuery contractAccountSet = ledger.getContractAccountSet(block); return contractAccountSet.getTotalCount(); } @@ -157,7 +171,7 @@ public class LedgerQueryService implements BlockchainQueryService { public long getContractTotalCount(HashDigest ledgerHash) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getLatestBlock(); - ContractAccountSet contractAccountSet = ledger.getContractAccountSet(block); + ContractAccountQuery contractAccountSet = ledger.getContractAccountSet(block); return contractAccountSet.getTotalCount(); } @@ -240,7 +254,7 @@ public class LedgerQueryService implements BlockchainQueryService { public UserInfo getUser(HashDigest ledgerHash, String address) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getLatestBlock(); - UserAccountSet userAccountSet = ledger.getUserAccountSet(block); + UserAccountQuery userAccountSet = ledger.getUserAccountSet(block); return userAccountSet.getUser(address); } @@ -249,7 +263,7 @@ public class LedgerQueryService implements BlockchainQueryService { public AccountHeader getDataAccount(HashDigest ledgerHash, String address) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getLatestBlock(); - DataAccountSet dataAccountSet = ledger.getDataAccountSet(block); + DataAccountQuery dataAccountSet = ledger.getDataAccountSet(block); return dataAccountSet.getDataAccount(Bytes.fromBase58(address)); } @@ -260,7 +274,7 @@ public class LedgerQueryService implements BlockchainQueryService { } LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getLatestBlock(); - DataAccountSet dataAccountSet = ledger.getDataAccountSet(block); + DataAccountQuery dataAccountSet = ledger.getDataAccountSet(block); DataAccount dataAccount = dataAccountSet.getDataAccount(Bytes.fromBase58(address)); KVDataEntry[] entries = new KVDataEntry[keys.length]; @@ -308,7 +322,7 @@ public class LedgerQueryService implements BlockchainQueryService { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getLatestBlock(); - DataAccountSet dataAccountSet = ledger.getDataAccountSet(block); + DataAccountQuery dataAccountSet = ledger.getDataAccountSet(block); DataAccount dataAccount = dataAccountSet.getDataAccount(Bytes.fromBase58(address)); KVDataEntry[] entries = new KVDataEntry[keys.length]; @@ -339,7 +353,7 @@ public class LedgerQueryService implements BlockchainQueryService { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getLatestBlock(); - DataAccountSet dataAccountSet = ledger.getDataAccountSet(block); + DataAccountQuery dataAccountSet = ledger.getDataAccountSet(block); DataAccount dataAccount = dataAccountSet.getDataAccount(Bytes.fromBase58(address)); int pages[] = QueryUtil.calFromIndexAndCount(fromIndex, count, (int) dataAccount.getDataEntriesTotalCount()); @@ -351,7 +365,7 @@ public class LedgerQueryService implements BlockchainQueryService { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getLatestBlock(); - DataAccountSet dataAccountSet = ledger.getDataAccountSet(block); + DataAccountQuery dataAccountSet = ledger.getDataAccountSet(block); DataAccount dataAccount = dataAccountSet.getDataAccount(Bytes.fromBase58(address)); return dataAccount.getDataEntriesTotalCount(); @@ -361,7 +375,7 @@ public class LedgerQueryService implements BlockchainQueryService { public ContractInfo getContract(HashDigest ledgerHash, String address) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getLatestBlock(); - ContractAccountSet contractAccountSet = ledger.getContractAccountSet(block); + ContractAccountQuery contractAccountSet = ledger.getContractAccountSet(block); return contractAccountSet.getContract(Bytes.fromBase58(address)); } @@ -369,7 +383,7 @@ public class LedgerQueryService implements BlockchainQueryService { public AccountHeader[] getUsers(HashDigest ledgerHash, int fromIndex, int count) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getLatestBlock(); - UserAccountSet userAccountSet = ledger.getUserAccountSet(block); + UserAccountQuery userAccountSet = ledger.getUserAccountSet(block); int pages[] = QueryUtil.calFromIndexAndCount(fromIndex, count, (int) userAccountSet.getTotalCount()); return userAccountSet.getAccounts(pages[0], pages[1]); } @@ -378,7 +392,7 @@ public class LedgerQueryService implements BlockchainQueryService { public AccountHeader[] getDataAccounts(HashDigest ledgerHash, int fromIndex, int count) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getLatestBlock(); - DataAccountSet dataAccountSet = ledger.getDataAccountSet(block); + DataAccountQuery dataAccountSet = ledger.getDataAccountSet(block); int pages[] = QueryUtil.calFromIndexAndCount(fromIndex, count, (int) dataAccountSet.getTotalCount()); return dataAccountSet.getAccounts(pages[0], pages[1]); } @@ -387,15 +401,9 @@ public class LedgerQueryService implements BlockchainQueryService { public AccountHeader[] getContractAccounts(HashDigest ledgerHash, int fromIndex, int count) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getLatestBlock(); - ContractAccountSet contractAccountSet = ledger.getContractAccountSet(block); + ContractAccountQuery contractAccountSet = ledger.getContractAccountSet(block); int pages[] = QueryUtil.calFromIndexAndCount(fromIndex, count, (int) contractAccountSet.getTotalCount()); return contractAccountSet.getAccounts(pages[0], pages[1]); } - private LedgerAdministration ledgerAdministration(HashDigest ledgerHash) { - LedgerRepository ledger = ledgerService.getLedger(ledgerHash); - LedgerBlock block = ledger.getLatestBlock(); - LedgerAdministration administration = ledger.getAdminAccount(block); - return administration; - } } diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerRepository.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerRepository.java index faa23138..a8790ab0 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerRepository.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerRepository.java @@ -3,6 +3,7 @@ package com.jd.blockchain.ledger.core; import java.io.Closeable; import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.ledger.LedgerAdminInfo; import com.jd.blockchain.ledger.LedgerBlock; public interface LedgerRepository extends Closeable { @@ -51,23 +52,23 @@ public interface LedgerRepository extends Closeable { */ LedgerBlock getBlock(long height); - LedgerAdministration getAdminInfo(); + LedgerAdminInfo getAdminInfo(); + + LedgerAdminInfo getAdminInfo(LedgerBlock block); LedgerBlock getBlock(HashDigest hash); - LedgerDataSet getDataSet(LedgerBlock block); + LedgerDataQuery getDataSet(LedgerBlock block); TransactionSet getTransactionSet(LedgerBlock block); - LedgerAdminAccount getAdminAccount(LedgerBlock block); + UserAccountQuery getUserAccountSet(LedgerBlock block); - UserAccountSet getUserAccountSet(LedgerBlock block); + DataAccountQuery getDataAccountSet(LedgerBlock block); - DataAccountSet getDataAccountSet(LedgerBlock block); + ContractAccountQuery getContractAccountSet(LedgerBlock block); - ContractAccountSet getContractAccountSet(LedgerBlock block); - - default LedgerDataSet getDataSet() { + default LedgerDataQuery getDataSet() { return getDataSet(getLatestBlock()); } @@ -75,19 +76,15 @@ public interface LedgerRepository extends Closeable { return getTransactionSet(getLatestBlock()); } - default LedgerAdminAccount getAdminAccount() { - return getAdminAccount(getLatestBlock()); - } - - default UserAccountSet getUserAccountSet() { + default UserAccountQuery getUserAccountSet() { return getUserAccountSet(getLatestBlock()); } - default DataAccountSet getDataAccountSet() { + default DataAccountQuery getDataAccountSet() { return getDataAccountSet(getLatestBlock()); } - default ContractAccountSet getContractAccountSet() { + default ContractAccountQuery getContractAccountSet() { return getContractAccountSet(getLatestBlock()); } diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerRepositoryImpl.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerRepositoryImpl.java similarity index 56% rename from source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerRepositoryImpl.java rename to source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerRepositoryImpl.java index 1fe559b7..55c9d6d6 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerRepositoryImpl.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerRepositoryImpl.java @@ -1,23 +1,17 @@ -package com.jd.blockchain.ledger.core.impl; +package com.jd.blockchain.ledger.core; import com.jd.blockchain.binaryproto.BinaryProtocol; import com.jd.blockchain.crypto.Crypto; import com.jd.blockchain.crypto.HashDigest; import com.jd.blockchain.crypto.HashFunction; -import com.jd.blockchain.ledger.*; -import com.jd.blockchain.ledger.core.AccountAccessPolicy; -import com.jd.blockchain.ledger.core.ContractAccountSet; -import com.jd.blockchain.ledger.core.DataAccountSet; -import com.jd.blockchain.ledger.core.LedgerAdminAccount; -import com.jd.blockchain.ledger.core.LedgerAdministration; -import com.jd.blockchain.ledger.core.LedgerConsts; -import com.jd.blockchain.ledger.core.LedgerDataSet; -import com.jd.blockchain.ledger.core.LedgerEditor; -import com.jd.blockchain.ledger.core.LedgerRepository; -import com.jd.blockchain.ledger.core.LedgerTransactionContext; -import com.jd.blockchain.ledger.core.SettingContext; -import com.jd.blockchain.ledger.core.TransactionSet; -import com.jd.blockchain.ledger.core.UserAccountSet; +import com.jd.blockchain.ledger.BlockBody; +import com.jd.blockchain.ledger.CryptoSetting; +import com.jd.blockchain.ledger.LedgerAdminInfo; +import com.jd.blockchain.ledger.LedgerBlock; +import com.jd.blockchain.ledger.LedgerDataSnapshot; +import com.jd.blockchain.ledger.LedgerInitSetting; +import com.jd.blockchain.ledger.LedgerSettings; +import com.jd.blockchain.ledger.TransactionRequest; import com.jd.blockchain.storage.service.ExPolicyKVStorage; import com.jd.blockchain.storage.service.VersioningKVStorage; import com.jd.blockchain.utils.Bytes; @@ -36,7 +30,7 @@ import com.jd.blockchain.utils.codec.Base58Utils; * @author huanghaiquan * */ -public class LedgerRepositoryImpl implements LedgerRepository { +class LedgerRepositoryImpl implements LedgerRepository { private static final Bytes LEDGER_PREFIX = Bytes.fromString("IDX" + LedgerConsts.KEY_SEPERATOR); @@ -80,6 +74,8 @@ public class LedgerRepositoryImpl implements LedgerRepository { if (getLatestBlockHeight() < 0) { throw new RuntimeException("Ledger doesn't exist!"); } + + retrieveLatestState(); } /* @@ -110,25 +106,27 @@ public class LedgerRepositoryImpl implements LedgerRepository { @Override public LedgerBlock getLatestBlock() { - LedgerState state = getLatestState(); - return state.block; + return latestState.block; } - private LedgerState getLatestState() { - LedgerState state = latestState; - if (state == null) { - LedgerBlock latestBlock = innerGetBlock(innerGetLatestBlockHeight()); - state = new LedgerState(latestBlock); - latestState = state; - } - return state; + /** + * 重新检索加载最新的状态; + * + * @return + */ + private LedgerState retrieveLatestState() { + LedgerBlock latestBlock = innerGetBlock(innerGetLatestBlockHeight()); + LedgerDataset ledgerDataset = innerGetLedgerDataset(latestBlock); + TransactionSet txSet = loadTransactionSet(latestBlock.getTransactionSetHash(), + ledgerDataset.getAdminDataset().getSettings().getCryptoSetting(), keyPrefix, exPolicyStorage, + versioningStorage, true); + this.latestState = new LedgerState(latestBlock, ledgerDataset, txSet); + return latestState; } @Override public LedgerBlock retrieveLatestBlock() { - LedgerBlock latestBlock = innerGetBlock(innerGetLatestBlockHeight()); - latestState = new LedgerState(latestBlock); - return latestBlock; + return retrieveLatestState().block; } @Override @@ -187,7 +185,7 @@ public class LedgerRepositoryImpl implements LedgerRepository { if (height < 0) { return null; } - return innerGetBlock(getBlockHash(height)); + return innerGetBlock(innerGetBlockHash(height)); } @Override @@ -209,26 +207,18 @@ public class LedgerRepositoryImpl implements LedgerRepository { throw new RuntimeException("Block hash not equals to it's storage key!"); } - // verify hash; - // boolean requiredVerifyHash = - // adminAccount.getMetadata().getSetting().getCryptoSetting().getAutoVerifyHash(); - // TODO: 未实现从配置中加载是否校验 Hash 的设置; - if (SettingContext.queryingSettings().verifyHash()) { - byte[] blockBodyBytes = null; - if (block.getHeight() == 0) { - // 计算创世区块的 hash 时,不包括 ledgerHash 字段; - block.setLedgerHash(null); - blockBodyBytes = BinaryProtocol.encode(block, BlockBody.class); - // 恢复; - block.setLedgerHash(block.getHash()); - } else { - blockBodyBytes = BinaryProtocol.encode(block, BlockBody.class); - } - HashFunction hashFunc = Crypto.getHashFunction(blockHash.getAlgorithm()); - boolean pass = hashFunc.verify(blockHash, blockBodyBytes); - if (!pass) { - throw new RuntimeException("Block hash verification fail!"); - } + // verify block hash; + byte[] blockBodyBytes = null; + if (block.getHeight() == 0) { + // 计算创世区块的 hash 时,不包括 ledgerHash 字段; + blockBodyBytes = BinaryProtocol.encode(block, BlockBody.class); + } else { + blockBodyBytes = BinaryProtocol.encode(block, BlockBody.class); + } + HashFunction hashFunc = Crypto.getHashFunction(blockHash.getAlgorithm()); + boolean pass = hashFunc.verify(blockHash, blockBodyBytes); + if (!pass) { + throw new RuntimeException("Block hash verification fail!"); } // verify height; @@ -243,9 +233,18 @@ public class LedgerRepositoryImpl implements LedgerRepository { return block; } + /** + * 获取最新区块的账本参数; + * + * @return + */ + private LedgerSettings getLatestSettings() { + return getAdminInfo().getSettings(); + } + @Override - public LedgerAdministration getAdminInfo() { - return getAdminAccount(getLatestBlock()); + public LedgerAdminInfo getAdminInfo() { + return getAdminInfo(getLatestBlock()); } private LedgerBlock deserialize(byte[] blockBytes) { @@ -255,140 +254,96 @@ public class LedgerRepositoryImpl implements LedgerRepository { @Override public TransactionSet getTransactionSet(LedgerBlock block) { long height = getLatestBlockHeight(); - TransactionSet transactionSet = null; if (height == block.getHeight()) { - // 缓存读; - LedgerState state = getLatestState(); - transactionSet = state.transactionSet; - if (transactionSet == null) { - LedgerAdminAccount adminAccount = getAdminAccount(block); - transactionSet = loadTransactionSet(block.getTransactionSetHash(), - adminAccount.getMetadata().getSetting().getCryptoSetting(), keyPrefix, exPolicyStorage, - versioningStorage, true); - state.transactionSet = transactionSet; - } - return transactionSet; + // 从缓存中返回最新区块的数据集; + return latestState.getTransactionSet(); } - LedgerAdminAccount adminAccount = getAdminAccount(block); + LedgerAdminInfo adminAccount = getAdminInfo(block); // All of existing block is readonly; - return loadTransactionSet(block.getTransactionSetHash(), - adminAccount.getMetadata().getSetting().getCryptoSetting(), keyPrefix, exPolicyStorage, - versioningStorage, true); + return loadTransactionSet(block.getTransactionSetHash(), adminAccount.getSettings().getCryptoSetting(), + keyPrefix, exPolicyStorage, versioningStorage, true); } @Override - public LedgerAdminAccount getAdminAccount(LedgerBlock block) { + public LedgerAdminDataset getAdminInfo(LedgerBlock block) { long height = getLatestBlockHeight(); - LedgerAdminAccount adminAccount = null; if (height == block.getHeight()) { - // 缓存读; - LedgerState state = getLatestState(); - adminAccount = state.adminAccount; - if (adminAccount == null) { - adminAccount = new LedgerAdminAccount(block.getAdminAccountHash(), keyPrefix, exPolicyStorage, - versioningStorage, true); - state.adminAccount = adminAccount; - } - return adminAccount; + return latestState.getAdminDataset(); } - return new LedgerAdminAccount(block.getAdminAccountHash(), keyPrefix, exPolicyStorage, versioningStorage, true); + return createAdminDataset(block); + } + + private LedgerAdminDataset createAdminDataset(LedgerBlock block) { + return new LedgerAdminDataset(block.getAdminAccountHash(), keyPrefix, exPolicyStorage, versioningStorage, true); } @Override - public UserAccountSet getUserAccountSet(LedgerBlock block) { + public UserAccountQuery getUserAccountSet(LedgerBlock block) { long height = getLatestBlockHeight(); - UserAccountSet userAccountSet = null; if (height == block.getHeight()) { - // 缓存读; - LedgerState state = getLatestState(); - userAccountSet = state.userAccountSet; - if (userAccountSet == null) { - LedgerAdminAccount adminAccount = getAdminAccount(block); - userAccountSet = loadUserAccountSet(block.getUserAccountSetHash(), - adminAccount.getPreviousSetting().getCryptoSetting(), keyPrefix, exPolicyStorage, - versioningStorage, true); - state.userAccountSet = userAccountSet; - } - return userAccountSet; + return latestState.getUserAccountSet(); } - LedgerAdminAccount adminAccount = getAdminAccount(block); - return loadUserAccountSet(block.getUserAccountSetHash(), adminAccount.getPreviousSetting().getCryptoSetting(), - keyPrefix, exPolicyStorage, versioningStorage, true); + LedgerAdminDataset adminAccount = getAdminInfo(block); + return createUserAccountSet(block, adminAccount.getSettings().getCryptoSetting()); + } + + private UserAccountSet createUserAccountSet(LedgerBlock block, CryptoSetting cryptoSetting) { + return loadUserAccountSet(block.getUserAccountSetHash(), cryptoSetting, keyPrefix, exPolicyStorage, + versioningStorage, true); } @Override - public DataAccountSet getDataAccountSet(LedgerBlock block) { + public DataAccountQuery getDataAccountSet(LedgerBlock block) { long height = getLatestBlockHeight(); - DataAccountSet dataAccountSet = null; if (height == block.getHeight()) { - // 缓存读; - LedgerState state = getLatestState(); - dataAccountSet = state.dataAccountSet; - if (dataAccountSet == null) { - LedgerAdminAccount adminAccount = getAdminAccount(block); - dataAccountSet = loadDataAccountSet(block.getDataAccountSetHash(), - adminAccount.getPreviousSetting().getCryptoSetting(), keyPrefix, exPolicyStorage, - versioningStorage, true); - state.dataAccountSet = dataAccountSet; - } - return dataAccountSet; + return latestState.getDataAccountSet(); } - LedgerAdminAccount adminAccount = getAdminAccount(block); - return loadDataAccountSet(block.getDataAccountSetHash(), adminAccount.getPreviousSetting().getCryptoSetting(), - keyPrefix, exPolicyStorage, versioningStorage, true); + LedgerAdminDataset adminAccount = getAdminInfo(block); + return createDataAccountSet(block, adminAccount.getSettings().getCryptoSetting()); + } + + private DataAccountSet createDataAccountSet(LedgerBlock block, CryptoSetting setting) { + return loadDataAccountSet(block.getDataAccountSetHash(), setting, keyPrefix, exPolicyStorage, versioningStorage, + true); } @Override - public ContractAccountSet getContractAccountSet(LedgerBlock block) { + public ContractAccountQuery getContractAccountSet(LedgerBlock block) { long height = getLatestBlockHeight(); - ContractAccountSet contractAccountSet = null; if (height == block.getHeight()) { - // 缓存读; - LedgerState state = getLatestState(); - contractAccountSet = state.contractAccountSet; - if (contractAccountSet == null) { - LedgerAdminAccount adminAccount = getAdminAccount(block); - contractAccountSet = loadContractAccountSet(block.getContractAccountSetHash(), - adminAccount.getPreviousSetting().getCryptoSetting(), keyPrefix, exPolicyStorage, - versioningStorage, true); - state.contractAccountSet = contractAccountSet; - } - return contractAccountSet; + return latestState.getContractAccountSet(); } - LedgerAdminAccount adminAccount = getAdminAccount(block); - return loadContractAccountSet(block.getContractAccountSetHash(), - adminAccount.getPreviousSetting().getCryptoSetting(), keyPrefix, exPolicyStorage, versioningStorage, - true); + LedgerAdminDataset adminAccount = getAdminInfo(block); + return createContractAccountSet(block, adminAccount.getSettings().getCryptoSetting()); + } + + private ContractAccountSet createContractAccountSet(LedgerBlock block, CryptoSetting cryptoSetting) { + return loadContractAccountSet(block.getContractAccountSetHash(), cryptoSetting, keyPrefix, exPolicyStorage, + versioningStorage, true); } @Override - public LedgerDataSet getDataSet(LedgerBlock block) { + public LedgerDataset getDataSet(LedgerBlock block) { long height = getLatestBlockHeight(); - LedgerDataSet ledgerDataSet = null; if (height == block.getHeight()) { - // 缓存读; - LedgerState state = getLatestState(); - ledgerDataSet = state.ledgerDataSet; - if (ledgerDataSet == null) { - ledgerDataSet = innerDataSet(block); - state.ledgerDataSet = ledgerDataSet; - } - return ledgerDataSet; + return latestState.getLedgerDataset(); } // All of existing block is readonly; - return innerDataSet(block); + return innerGetLedgerDataset(block); } - private LedgerDataSet innerDataSet(LedgerBlock block) { - LedgerAdminAccount adminAccount = getAdminAccount(block); - UserAccountSet userAccountSet = getUserAccountSet(block); - DataAccountSet dataAccountSet = getDataAccountSet(block); - ContractAccountSet contractAccountSet = getContractAccountSet(block); - return new LedgerDataSetImpl(adminAccount, userAccountSet, dataAccountSet, contractAccountSet, true); + private LedgerDataset innerGetLedgerDataset(LedgerBlock block) { + LedgerAdminDataset adminDataset = createAdminDataset(block); + CryptoSetting cryptoSetting = adminDataset.getSettings().getCryptoSetting(); + + UserAccountSet userAccountSet = createUserAccountSet(block, cryptoSetting); + DataAccountSet dataAccountSet = createDataAccountSet(block, cryptoSetting); + ContractAccountSet contractAccountSet = createContractAccountSet(block, cryptoSetting); + return new LedgerDataset(adminDataset, userAccountSet, dataAccountSet, contractAccountSet, true); } @Override @@ -401,9 +356,8 @@ public class LedgerRepositoryImpl implements LedgerRepository { "A new block is in process, cann't create another one until it finish by committing or canceling."); } LedgerBlock previousBlock = getLatestBlock(); - LedgerTransactionalEditor editor = LedgerTransactionalEditor.createEditor(previousBlock, - getAdminInfo().getMetadata().getSetting(), keyPrefix, exPolicyStorage, - versioningStorage); + LedgerTransactionalEditor editor = LedgerTransactionalEditor.createEditor(previousBlock, getLatestSettings(), + keyPrefix, exPolicyStorage, versioningStorage); NewBlockCommittingMonitor committingMonitor = new NewBlockCommittingMonitor(editor, this); this.nextBlockEditor = committingMonitor; return committingMonitor; @@ -426,64 +380,39 @@ public class LedgerRepositoryImpl implements LedgerRepository { } static Bytes encodeLedgerIndexKey(HashDigest ledgerHash) { - // return LEDGER_PREFIX + Base58Utils.encode(ledgerHash.toBytes()); - // return new Bytes(ledgerHash.toBytes()).concatTo(LEDGER_PREFIX); return LEDGER_PREFIX.concat(ledgerHash); } static Bytes encodeBlockStorageKey(HashDigest blockHash) { - // String key = ByteArray.toBase58(blockHash.toBytes()); - // return BLOCK_PREFIX + key; - return BLOCK_PREFIX.concat(blockHash); } - static LedgerDataSetImpl newDataSet(LedgerInitSetting initSetting, String keyPrefix, + static LedgerDataset newDataSet(LedgerInitSetting initSetting, String keyPrefix, ExPolicyKVStorage ledgerExStorage, VersioningKVStorage ledgerVerStorage) { - LedgerAdminAccount adminAccount = new LedgerAdminAccount(initSetting, keyPrefix, ledgerExStorage, + LedgerAdminDataset adminAccount = new LedgerAdminDataset(initSetting, keyPrefix, ledgerExStorage, ledgerVerStorage); String usersetKeyPrefix = keyPrefix + USER_SET_PREFIX; String datasetKeyPrefix = keyPrefix + DATA_SET_PREFIX; String contractsetKeyPrefix = keyPrefix + CONTRACT_SET_PREFIX; - // String txsetKeyPrefix = keyPrefix + TRANSACTION_SET_PREFIX; - - // UserAccountSet userAccountSet = new - // UserAccountSet(adminAccount.getSetting().getCryptoSetting(), - // PrefixAppender.prefix(USER_SET_PREFIX, ledgerExStorage), - // PrefixAppender.prefix(USER_SET_PREFIX, ledgerVerStorage), - // DEFAULT_ACCESS_POLICY); - UserAccountSet userAccountSet = new UserAccountSet(adminAccount.getSetting().getCryptoSetting(), + + UserAccountSet userAccountSet = new UserAccountSet(adminAccount.getSettings().getCryptoSetting(), usersetKeyPrefix, ledgerExStorage, ledgerVerStorage, DEFAULT_ACCESS_POLICY); - // DataAccountSet dataAccountSet = new - // DataAccountSet(adminAccount.getSetting().getCryptoSetting(), - // PrefixAppender.prefix(DATA_SET_PREFIX, ledgerExStorage), - // PrefixAppender.prefix(DATA_SET_PREFIX, ledgerVerStorage), - // DEFAULT_ACCESS_POLICY); - DataAccountSet dataAccountSet = new DataAccountSet(adminAccount.getSetting().getCryptoSetting(), + DataAccountSet dataAccountSet = new DataAccountSet(adminAccount.getSettings().getCryptoSetting(), datasetKeyPrefix, ledgerExStorage, ledgerVerStorage, DEFAULT_ACCESS_POLICY); - // ContractAccountSet contractAccountSet = new - // ContractAccountSet(adminAccount.getSetting().getCryptoSetting(), - // PrefixAppender.prefix(CONTRACT_SET_PREFIX, ledgerExStorage), - // PrefixAppender.prefix(CONTRACT_SET_PREFIX, ledgerVerStorage), - // DEFAULT_ACCESS_POLICY); - ContractAccountSet contractAccountSet = new ContractAccountSet(adminAccount.getSetting().getCryptoSetting(), + ContractAccountSet contractAccountSet = new ContractAccountSet(adminAccount.getSettings().getCryptoSetting(), contractsetKeyPrefix, ledgerExStorage, ledgerVerStorage, DEFAULT_ACCESS_POLICY); - LedgerDataSetImpl newDataSet = new LedgerDataSetImpl(adminAccount, userAccountSet, dataAccountSet, + LedgerDataset newDataSet = new LedgerDataset(adminAccount, userAccountSet, dataAccountSet, contractAccountSet, false); return newDataSet; } - static TransactionSet newTransactionSet(LedgerSetting ledgerSetting, String keyPrefix, + static TransactionSet newTransactionSet(LedgerSettings ledgerSetting, String keyPrefix, ExPolicyKVStorage ledgerExStorage, VersioningKVStorage ledgerVerStorage) { - // TransactionSet transactionSet = new - // TransactionSet(ledgerSetting.getCryptoSetting(), - // PrefixAppender.prefix(TRANSACTION_SET_PREFIX, ledgerExStorage), - // PrefixAppender.prefix(TRANSACTION_SET_PREFIX, ledgerVerStorage)); String txsetKeyPrefix = keyPrefix + TRANSACTION_SET_PREFIX; @@ -492,13 +421,11 @@ public class LedgerRepositoryImpl implements LedgerRepository { return transactionSet; } - static LedgerDataSetImpl loadDataSet(LedgerDataSnapshot dataSnapshot, String keyPrefix, + static LedgerDataset loadDataSet(LedgerDataSnapshot dataSnapshot, CryptoSetting cryptoSetting, String keyPrefix, ExPolicyKVStorage ledgerExStorage, VersioningKVStorage ledgerVerStorage, boolean readonly) { - LedgerAdminAccount adminAccount = new LedgerAdminAccount(dataSnapshot.getAdminAccountHash(), keyPrefix, + LedgerAdminDataset adminAccount = new LedgerAdminDataset(dataSnapshot.getAdminAccountHash(), keyPrefix, ledgerExStorage, ledgerVerStorage, readonly); - CryptoSetting cryptoSetting = adminAccount.getPreviousSetting().getCryptoSetting(); - UserAccountSet userAccountSet = loadUserAccountSet(dataSnapshot.getUserAccountSetHash(), cryptoSetting, keyPrefix, ledgerExStorage, ledgerVerStorage, readonly); @@ -508,7 +435,7 @@ public class LedgerRepositoryImpl implements LedgerRepository { ContractAccountSet contractAccountSet = loadContractAccountSet(dataSnapshot.getContractAccountSetHash(), cryptoSetting, keyPrefix, ledgerExStorage, ledgerVerStorage, readonly); - LedgerDataSetImpl dataset = new LedgerDataSetImpl(adminAccount, userAccountSet, dataAccountSet, + LedgerDataset dataset = new LedgerDataset(adminAccount, userAccountSet, dataAccountSet, contractAccountSet, readonly); return dataset; @@ -517,10 +444,6 @@ public class LedgerRepositoryImpl implements LedgerRepository { static UserAccountSet loadUserAccountSet(HashDigest userAccountSetHash, CryptoSetting cryptoSetting, String keyPrefix, ExPolicyKVStorage ledgerExStorage, VersioningKVStorage ledgerVerStorage, boolean readonly) { - // return new UserAccountSet(userAccountSetHash, cryptoSetting, - // PrefixAppender.prefix(USER_SET_PREFIX, ledgerExStorage), - // PrefixAppender.prefix(USER_SET_PREFIX, ledgerVerStorage), readonly, - // DEFAULT_ACCESS_POLICY); String usersetKeyPrefix = keyPrefix + USER_SET_PREFIX; return new UserAccountSet(userAccountSetHash, cryptoSetting, usersetKeyPrefix, ledgerExStorage, @@ -530,10 +453,6 @@ public class LedgerRepositoryImpl implements LedgerRepository { static DataAccountSet loadDataAccountSet(HashDigest dataAccountSetHash, CryptoSetting cryptoSetting, String keyPrefix, ExPolicyKVStorage ledgerExStorage, VersioningKVStorage ledgerVerStorage, boolean readonly) { - // return new DataAccountSet(dataAccountSetHash, cryptoSetting, - // PrefixAppender.prefix(DATA_SET_PREFIX, ledgerExStorage, - // PrefixAppender.prefix(DATA_SET_PREFIX, ledgerVerStorage), readonly, - // DEFAULT_ACCESS_POLICY); String datasetKeyPrefix = keyPrefix + DATA_SET_PREFIX; return new DataAccountSet(dataAccountSetHash, cryptoSetting, datasetKeyPrefix, ledgerExStorage, @@ -543,10 +462,6 @@ public class LedgerRepositoryImpl implements LedgerRepository { static ContractAccountSet loadContractAccountSet(HashDigest contractAccountSetHash, CryptoSetting cryptoSetting, String keyPrefix, ExPolicyKVStorage ledgerExStorage, VersioningKVStorage ledgerVerStorage, boolean readonly) { - // return new ContractAccountSet(contractAccountSetHash, cryptoSetting, - // PrefixAppender.prefix(CONTRACT_SET_PREFIX, ledgerExStorage, - // PrefixAppender.prefix(CONTRACT_SET_PREFIX, ledgerVerStorage), readonly, - // DEFAULT_ACCESS_POLICY); String contractsetKeyPrefix = keyPrefix + CONTRACT_SET_PREFIX; return new ContractAccountSet(contractAccountSetHash, cryptoSetting, contractsetKeyPrefix, ledgerExStorage, @@ -555,9 +470,6 @@ public class LedgerRepositoryImpl implements LedgerRepository { static TransactionSet loadTransactionSet(HashDigest txsetHash, CryptoSetting cryptoSetting, String keyPrefix, ExPolicyKVStorage ledgerExStorage, VersioningKVStorage ledgerVerStorage, boolean readonly) { - // return new TransactionSet(txsetHash, cryptoSetting, - // PrefixAppender.prefix(TRANSACTION_SET_PREFIX, ledgerExStorage), - // PrefixAppender.prefix(TRANSACTION_SET_PREFIX, ledgerVerStorage), readonly); String txsetKeyPrefix = keyPrefix + TRANSACTION_SET_PREFIX; return new TransactionSet(txsetHash, cryptoSetting, txsetKeyPrefix, ledgerExStorage, ledgerVerStorage, @@ -586,6 +498,16 @@ public class LedgerRepositoryImpl implements LedgerRepository { return editor.getBlockHeight(); } + @Override + public LedgerDataset getLedgerDataset() { + return editor.getLedgerDataset(); + } + + @Override + public TransactionSet getTransactionSet() { + return editor.getTransactionSet(); + } + @Override public LedgerTransactionContext newTransaction(TransactionRequest txRequest) { return editor.newTransaction(txRequest); @@ -601,7 +523,8 @@ public class LedgerRepositoryImpl implements LedgerRepository { try { editor.commit(); LedgerBlock latestBlock = editor.getCurrentBlock(); - ledgerRepo.latestState = new LedgerState(latestBlock); + ledgerRepo.latestState = new LedgerState(latestBlock, editor.getLedgerDataset(), + editor.getTransactionSet()); } finally { ledgerRepo.nextBlockEditor = null; } @@ -628,20 +551,39 @@ public class LedgerRepositoryImpl implements LedgerRepository { private final LedgerBlock block; - private volatile LedgerAdminAccount adminAccount; + private final TransactionSet transactionSet; - private volatile UserAccountSet userAccountSet; + private final LedgerDataset ledgerDataset; - private volatile DataAccountSet dataAccountSet; + public LedgerState(LedgerBlock block, LedgerDataset ledgerDataset, TransactionSet transactionSet) { + this.block = block; + this.ledgerDataset = ledgerDataset; + this.transactionSet = transactionSet; - private volatile ContractAccountSet contractAccountSet; + } - private volatile TransactionSet transactionSet; + public LedgerAdminDataset getAdminDataset() { + return ledgerDataset.getAdminDataset(); + } - private volatile LedgerDataSet ledgerDataSet; + public LedgerDataset getLedgerDataset() { + return ledgerDataset; + } - public LedgerState(LedgerBlock block) { - this.block = block; + public ContractAccountQuery getContractAccountSet() { + return ledgerDataset.getContractAccountset(); + } + + public DataAccountQuery getDataAccountSet() { + return ledgerDataset.getDataAccountSet(); + } + + public UserAccountQuery getUserAccountSet() { + return ledgerDataset.getUserAccountSet(); + } + + public TransactionSet getTransactionSet() { + return transactionSet; } } diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerSecurityManager.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerSecurityManager.java new file mode 100644 index 00000000..ac819e39 --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerSecurityManager.java @@ -0,0 +1,20 @@ +package com.jd.blockchain.ledger.core; + +import java.util.Set; + +import com.jd.blockchain.utils.Bytes; + +public interface LedgerSecurityManager { + + String DEFAULT_ROLE = "DEFAULT"; + + /** + * 创建一项与指定的终端用户和节点参与方相关的安全策略; + * + * @param endpoints 终端用户的地址列表; + * @param nodes 节点参与方的地址列表; + * @return 一项安全策略; + */ + SecurityPolicy createSecurityPolicy(Set endpoints, Set nodes); + +} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerSecurityManagerImpl.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerSecurityManagerImpl.java new file mode 100644 index 00000000..e0987732 --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerSecurityManagerImpl.java @@ -0,0 +1,396 @@ +package com.jd.blockchain.ledger.core; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import com.jd.blockchain.ledger.LedgerPermission; +import com.jd.blockchain.ledger.LedgerSecurityException; +import com.jd.blockchain.ledger.ParticipantDataQuery; +import com.jd.blockchain.ledger.ParticipantDoesNotExistException; +import com.jd.blockchain.ledger.RolePrivilegeSettings; +import com.jd.blockchain.ledger.RolePrivileges; +import com.jd.blockchain.ledger.RolesPolicy; +import com.jd.blockchain.ledger.TransactionPermission; +import com.jd.blockchain.ledger.UserDoesNotExistException; +import com.jd.blockchain.ledger.UserRoles; +import com.jd.blockchain.ledger.UserRolesSettings; +import com.jd.blockchain.utils.Bytes; + +/** + * 账本安全管理器; + * + * @author huanghaiquan + * + */ +public class LedgerSecurityManagerImpl implements LedgerSecurityManager { + + private RolePrivilegeSettings rolePrivilegeSettings; + + private UserRolesSettings userRolesSettings; + + // 用户的权限配置 + private Map userPrivilegesCache = new ConcurrentHashMap<>(); + + private Map userRolesCache = new ConcurrentHashMap<>(); + private Map rolesPrivilegeCache = new ConcurrentHashMap<>(); + + private ParticipantDataQuery participantsQuery; + private UserAccountQuery userAccountsQuery; + + public LedgerSecurityManagerImpl(RolePrivilegeSettings rolePrivilegeSettings, UserRolesSettings userRolesSettings, + ParticipantDataQuery participantsQuery, UserAccountQuery userAccountsQuery) { + this.rolePrivilegeSettings = rolePrivilegeSettings; + this.userRolesSettings = userRolesSettings; + this.participantsQuery = participantsQuery; + this.userAccountsQuery = userAccountsQuery; + } + + @Override + public SecurityPolicy createSecurityPolicy(Set endpoints, Set nodes) { + Map endpointPrivilegeMap = new HashMap<>(); + Map nodePrivilegeMap = new HashMap<>(); + + for (Bytes userAddress : endpoints) { + UserRolesPrivileges userPrivileges = getUserRolesPrivilegs(userAddress); + endpointPrivilegeMap.put(userAddress, userPrivileges); + } + + for (Bytes userAddress : nodes) { + UserRolesPrivileges userPrivileges = getUserRolesPrivilegs(userAddress); + nodePrivilegeMap.put(userAddress, userPrivileges); + } + + return new UserRolesSecurityPolicy(endpointPrivilegeMap, nodePrivilegeMap, participantsQuery, userAccountsQuery); + } + + private UserRolesPrivileges getUserRolesPrivilegs(Bytes userAddress) { + UserRolesPrivileges userPrivileges = userPrivilegesCache.get(userAddress); + if (userPrivileges != null) { + return userPrivileges; + } + + UserRoles userRoles = null; + + List privilegesList = new ArrayList<>(); + + // 加载用户的角色列表; + userRoles = userRolesCache.get(userAddress); + if (userRoles == null) { + userRoles = userRolesSettings.getUserRoles(userAddress); + if (userRoles != null) { + userRolesCache.put(userAddress, userRoles); + } + } + + // 计算用户的综合权限; + if (userRoles != null) { + String[] roles = userRoles.getRoles(); + RolePrivileges privilege = null; + for (String role : roles) { + // 先从缓存读取,如果没有再从原始数据源进行加载; + privilege = rolesPrivilegeCache.get(role); + if (privilege == null) { + privilege = rolePrivilegeSettings.getRolePrivilege(role); + if (privilege == null) { + // 略过不存在的无效角色; + continue; + } + rolesPrivilegeCache.put(role, privilege); + } + privilegesList.add(privilege); + } + } + // 如果用户未被授权任何角色,则采用默认角色的权限; + if (privilegesList.size() == 0) { + RolePrivileges privilege = getDefaultRolePrivilege(); + privilegesList.add(privilege); + } + + if (userRoles == null) { + userPrivileges = new UserRolesPrivileges(userAddress, RolesPolicy.UNION, privilegesList); + } else { + userPrivileges = new UserRolesPrivileges(userAddress, userRoles.getPolicy(), privilegesList); + } + + userPrivilegesCache.put(userAddress, userPrivileges); + return userPrivileges; + } + + private RolePrivileges getDefaultRolePrivilege() { + RolePrivileges privileges = rolesPrivilegeCache.get(DEFAULT_ROLE); + if (privileges == null) { + privileges = rolePrivilegeSettings.getRolePrivilege(DEFAULT_ROLE); + if (privileges == null) { + throw new LedgerSecurityException( + "This ledger is missing the default role-privilege settings for the users who don't have a role!"); + } + } + return privileges; + } + + private class UserRolesSecurityPolicy implements SecurityPolicy { + + /** + * 终端用户的权限表; + */ + private Map endpointPrivilegeMap = new HashMap<>(); + + /** + * 节点参与方的权限表; + */ + private Map nodePrivilegeMap = new HashMap<>(); + + private ParticipantDataQuery participantsQuery; + + private UserAccountQuery userAccountsQuery; + + public UserRolesSecurityPolicy(Map endpointPrivilegeMap, + Map nodePrivilegeMap, ParticipantDataQuery participantsQuery, + UserAccountQuery userAccountsQuery) { + this.endpointPrivilegeMap = endpointPrivilegeMap; + this.nodePrivilegeMap = nodePrivilegeMap; + this.participantsQuery = participantsQuery; + this.userAccountsQuery = userAccountsQuery; + } + + @Override + public boolean isEndpointEnable(LedgerPermission permission, MultiIDsPolicy midPolicy) { + if (MultiIDsPolicy.AT_LEAST_ONE == midPolicy) { + // 至少一个; + for (UserRolesPrivileges p : endpointPrivilegeMap.values()) { + if (p.getLedgerPrivileges().isEnable(permission)) { + return true; + } + } + return false; + } else if (MultiIDsPolicy.ALL == midPolicy) { + // 全部; + for (UserRolesPrivileges p : endpointPrivilegeMap.values()) { + if (!p.getLedgerPrivileges().isEnable(permission)) { + return false; + } + } + return true; + } else { + throw new IllegalArgumentException("Unsupported MultiIdsPolicy[" + midPolicy + "]!"); + } + } + + @Override + public boolean isEndpointEnable(TransactionPermission permission, MultiIDsPolicy midPolicy) { + if (MultiIDsPolicy.AT_LEAST_ONE == midPolicy) { + // 至少一个; + for (UserRolesPrivileges p : endpointPrivilegeMap.values()) { + if (p.getTransactionPrivileges().isEnable(permission)) { + return true; + } + } + return false; + } else if (MultiIDsPolicy.ALL == midPolicy) { + // 全部; + for (UserRolesPrivileges p : endpointPrivilegeMap.values()) { + if (!p.getTransactionPrivileges().isEnable(permission)) { + return false; + } + } + return true; + } else { + throw new IllegalArgumentException("Unsupported MultiIdsPolicy[" + midPolicy + "]!"); + } + } + + @Override + public boolean isNodeEnable(LedgerPermission permission, MultiIDsPolicy midPolicy) { + if (MultiIDsPolicy.AT_LEAST_ONE == midPolicy) { + // 至少一个; + for (UserRolesPrivileges p : nodePrivilegeMap.values()) { + if (p.getLedgerPrivileges().isEnable(permission)) { + return true; + } + } + return false; + } else if (MultiIDsPolicy.ALL == midPolicy) { + // 全部; + for (UserRolesPrivileges p : nodePrivilegeMap.values()) { + if (!p.getLedgerPrivileges().isEnable(permission)) { + return false; + } + } + return true; + } else { + throw new IllegalArgumentException("Unsupported MultiIdsPolicy[" + midPolicy + "]!"); + } + } + + @Override + public boolean isNodeEnable(TransactionPermission permission, MultiIDsPolicy midPolicy) { + if (MultiIDsPolicy.AT_LEAST_ONE == midPolicy) { + // 至少一个; + for (UserRolesPrivileges p : nodePrivilegeMap.values()) { + if (p.getTransactionPrivileges().isEnable(permission)) { + return true; + } + } + return false; + } else if (MultiIDsPolicy.ALL == midPolicy) { + // 全部; + for (UserRolesPrivileges p : nodePrivilegeMap.values()) { + if (!p.getTransactionPrivileges().isEnable(permission)) { + return false; + } + } + return true; + } else { + throw new IllegalArgumentException("Unsupported MultiIdsPolicy[" + midPolicy + "]!"); + } + } + + @Override + public void checkEndpointPermission(LedgerPermission permission, MultiIDsPolicy midPolicy) + throws LedgerSecurityException { + if (!isEndpointEnable(permission, midPolicy)) { + throw new LedgerSecurityException(String.format( + "The security policy [Permission=%s, Policy=%s] for endpoints rejected the current operation!", + permission, midPolicy)); + } + } + + @Override + public void checkEndpointPermission(TransactionPermission permission, MultiIDsPolicy midPolicy) + throws LedgerSecurityException { + if (!isEndpointEnable(permission, midPolicy)) { + throw new LedgerSecurityException(String.format( + "The security policy [Permission=%s, Policy=%s] for endpoints rejected the current operation!", + permission, midPolicy)); + } + } + + @Override + public void checkNodePermission(LedgerPermission permission, MultiIDsPolicy midPolicy) + throws LedgerSecurityException { + if (!isNodeEnable(permission, midPolicy)) { + throw new LedgerSecurityException(String.format( + "The security policy [Permission=%s, Policy=%s] for nodes rejected the current operation!", + permission, midPolicy)); + } + } + + @Override + public void checkNodePermission(TransactionPermission permission, MultiIDsPolicy midPolicy) + throws LedgerSecurityException { + if (!isNodeEnable(permission, midPolicy)) { + throw new LedgerSecurityException(String.format( + "The security policy [Permission=%s, Policy=%s] for nodes rejected the current operation!", + permission, midPolicy)); + } + } + + @Override + public Set getEndpoints() { + return endpointPrivilegeMap.keySet(); + } + + @Override + public Set getNodes() { + return nodePrivilegeMap.keySet(); + } + + @Override + public boolean isEndpointValid(MultiIDsPolicy midPolicy) { + if (MultiIDsPolicy.AT_LEAST_ONE == midPolicy) { + // 至少一个; + for (Bytes address : getEndpoints()) { + if (userAccountsQuery.contains(address)) { + return true; + } + } + return false; + } else if (MultiIDsPolicy.ALL == midPolicy) { + // 全部; + for (Bytes address : getEndpoints()) { + if (!userAccountsQuery.contains(address)) { + return false; + } + } + return true; + } else { + throw new IllegalArgumentException("Unsupported MultiIdsPolicy[" + midPolicy + "]!"); + } + } + + @Override + public boolean isNodeValid(MultiIDsPolicy midPolicy) { + if (MultiIDsPolicy.AT_LEAST_ONE == midPolicy) { + // 至少一个; + for (Bytes address : getNodes()) { + if (participantsQuery.contains(address)) { + return true; + } + } + return false; + } else if (MultiIDsPolicy.ALL == midPolicy) { + // 全部; + for (Bytes address : getNodes()) { + if (!participantsQuery.contains(address)) { + return false; + } + } + return true; + } else { + throw new IllegalArgumentException("Unsupported MultiIdsPolicy[" + midPolicy + "]!"); + } + } + + @Override + public void checkEndpointValidity(MultiIDsPolicy midPolicy) throws LedgerSecurityException { + if (MultiIDsPolicy.AT_LEAST_ONE == midPolicy) { + // 至少一个; + for (Bytes address : getEndpoints()) { + if (userAccountsQuery.contains(address)) { + return; + } + } + throw new UserDoesNotExistException("All endpoint signers were not registered!"); + } else if (MultiIDsPolicy.ALL == midPolicy) { + // 全部; + for (Bytes address : getEndpoints()) { + if (!userAccountsQuery.contains(address)) { + throw new UserDoesNotExistException("The endpoint signer[" + address + "] was not registered!"); + } + } + return; + } else { + throw new IllegalArgumentException("Unsupported MultiIdsPolicy[" + midPolicy + "]!"); + } + } + + @Override + public void checkNodeValidity(MultiIDsPolicy midPolicy) throws LedgerSecurityException { + if (MultiIDsPolicy.AT_LEAST_ONE == midPolicy) { + // 至少一个; + for (Bytes address : getNodes()) { + if (participantsQuery.contains(address)) { + return; + } + } + throw new ParticipantDoesNotExistException("All node signers were not registered as participant!"); + } else if (MultiIDsPolicy.ALL == midPolicy) { + // 全部; + for (Bytes address : getNodes()) { + if (!participantsQuery.contains(address)) { + throw new ParticipantDoesNotExistException( + "The node signer[" + address + "] was not registered as participant!"); + } + } + } else { + throw new IllegalArgumentException("Unsupported MultiIdsPolicy[" + midPolicy + "]!"); + } + } + + } + +} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerTransactionContext.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerTransactionContext.java index a4feb79e..b06721e6 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerTransactionContext.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerTransactionContext.java @@ -13,11 +13,18 @@ import java.util.List; public interface LedgerTransactionContext { /** - * 账本数据; + * 账本数据集合; * * @return */ - LedgerDataSet getDataSet(); + LedgerDataset getDataset(); + + /** + * 事务集合; + * + * @return + */ + TransactionSet getTransactionSet(); /** * 交易请求; diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerTransactionData.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerTransactionData.java similarity index 99% rename from source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerTransactionData.java rename to source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerTransactionData.java index 432c24e1..516f338f 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerTransactionData.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerTransactionData.java @@ -1,4 +1,4 @@ -package com.jd.blockchain.ledger.core.impl; +package com.jd.blockchain.ledger.core; import com.jd.blockchain.crypto.HashDigest; import com.jd.blockchain.ledger.DigitalSignature; diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerTransactionalEditor.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerTransactionalEditor.java similarity index 84% rename from source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerTransactionalEditor.java rename to source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerTransactionalEditor.java index c4b696c0..ea7bb7ed 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerTransactionalEditor.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/LedgerTransactionalEditor.java @@ -1,4 +1,4 @@ -package com.jd.blockchain.ledger.core.impl; +package com.jd.blockchain.ledger.core; import java.util.List; @@ -8,29 +8,19 @@ import com.jd.blockchain.crypto.HashDigest; import com.jd.blockchain.ledger.BlockBody; import com.jd.blockchain.ledger.BlockRollbackException; import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.ledger.DigitalSignature; import com.jd.blockchain.ledger.IllegalTransactionException; import com.jd.blockchain.ledger.LedgerBlock; import com.jd.blockchain.ledger.LedgerDataSnapshot; import com.jd.blockchain.ledger.LedgerInitSetting; -import com.jd.blockchain.ledger.LedgerSetting; +import com.jd.blockchain.ledger.LedgerSettings; import com.jd.blockchain.ledger.LedgerTransaction; import com.jd.blockchain.ledger.OperationResult; -import com.jd.blockchain.ledger.TransactionContent; import com.jd.blockchain.ledger.TransactionRequest; import com.jd.blockchain.ledger.TransactionRollbackException; import com.jd.blockchain.ledger.TransactionState; -import com.jd.blockchain.ledger.core.LedgerDataSet; -import com.jd.blockchain.ledger.core.LedgerEditor; -import com.jd.blockchain.ledger.core.LedgerTransactionContext; -import com.jd.blockchain.ledger.core.SettingContext; -import com.jd.blockchain.ledger.core.TransactionSet; import com.jd.blockchain.storage.service.ExPolicyKVStorage; import com.jd.blockchain.storage.service.VersioningKVStorage; import com.jd.blockchain.storage.service.utils.BufferedKVStorage; -import com.jd.blockchain.transaction.SignatureUtils; -import com.jd.blockchain.transaction.TxBuilder; -import com.jd.blockchain.transaction.TxRequestBuilder; import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.codec.Base58Utils; @@ -70,10 +60,8 @@ public class LedgerTransactionalEditor implements LedgerEditor { private BufferedKVStorage baseStorage; /** - * 上一个交易的上下文; + * 上一个交易产生的账本快照; */ -// private LedgerTransactionContextImpl previousTxCtx; - private TxSnapshot previousTxSnapshot; /** @@ -81,6 +69,16 @@ public class LedgerTransactionalEditor implements LedgerEditor { */ private volatile LedgerTransactionContextImpl currentTxCtx; + /** + * 最后提交的账本数据集; + */ + private volatile LedgerDataset latestLedgerDataset; + + /** + * 最后提交的交易集合; + */ + private volatile TransactionSet latestTransactionSet; + /** * @param ledgerHash * @param cryptoSetting @@ -115,7 +113,7 @@ public class LedgerTransactionalEditor implements LedgerEditor { * @param verifyTx 是否校验交易请求;当外部调用者在调用前已经实施了验证时,将次参数设置为 false 能够提升性能; * @return */ - public static LedgerTransactionalEditor createEditor(LedgerBlock previousBlock, LedgerSetting ledgerSetting, + public static LedgerTransactionalEditor createEditor(LedgerBlock previousBlock, LedgerSettings ledgerSetting, String ledgerKeyPrefix, ExPolicyKVStorage ledgerExStorage, VersioningKVStorage ledgerVerStorage) { // new block; HashDigest ledgerHash = previousBlock.getLedgerHash(); @@ -160,6 +158,10 @@ public class LedgerTransactionalEditor implements LedgerEditor { private void commitTxSnapshot(TxSnapshot snapshot) { previousTxSnapshot = snapshot; + latestLedgerDataset = currentTxCtx.getDataset(); + latestLedgerDataset.setReadonly(); + latestTransactionSet = currentTxCtx.getTransactionSet(); + latestTransactionSet.setReadonly(); currentTxCtx = null; } @@ -181,13 +183,23 @@ public class LedgerTransactionalEditor implements LedgerEditor { return ledgerHash; } + @Override + public LedgerDataset getLedgerDataset() { + return latestLedgerDataset; + } + + @Override + public TransactionSet getTransactionSet() { + return latestTransactionSet; + } + /** * 检查当前账本是否是指定交易请求的账本; * * @param txRequest * @return */ - private boolean isRequestedLedger(TransactionRequest txRequest) { + private boolean isRequestMatched(TransactionRequest txRequest) { HashDigest reqLedgerHash = txRequest.getTransactionContent().getLedgerHash(); if (ledgerHash == reqLedgerHash) { return true; @@ -198,49 +210,19 @@ public class LedgerTransactionalEditor implements LedgerEditor { return ledgerHash.equals(reqLedgerHash); } - private boolean verifyTxContent(TransactionRequest request) { - TransactionContent txContent = request.getTransactionContent(); - if (!TxBuilder.verifyTxContentHash(txContent, txContent.getHash())) { - return false; - } - DigitalSignature[] endpointSignatures = request.getEndpointSignatures(); - if (endpointSignatures != null) { - for (DigitalSignature signature : endpointSignatures) { - if (!SignatureUtils.verifyHashSignature(txContent.getHash(), signature.getDigest(), - signature.getPubKey())) { - return false; - } - } - } - DigitalSignature[] nodeSignatures = request.getNodeSignatures(); - if (nodeSignatures != null) { - for (DigitalSignature signature : nodeSignatures) { - if (!SignatureUtils.verifyHashSignature(txContent.getHash(), signature.getDigest(), - signature.getPubKey())) { - return false; - } - } - } - return true; - } - + /** + * 注:此方法不验证交易完整性和签名有效性,仅仅设计为进行交易记录的管理;调用者应在此方法之外进行数据完整性和签名有效性的检查; + */ @Override public synchronized LedgerTransactionContext newTransaction(TransactionRequest txRequest) { - if (SettingContext.txSettings().verifyLedger() && !isRequestedLedger(txRequest)) { +// if (SettingContext.txSettings().verifyLedger() && !isRequestMatched(txRequest)) { + if (!isRequestMatched(txRequest)) { throw new IllegalTransactionException( "Transaction request is dispatched to a wrong ledger! --[TxHash=" + txRequest.getTransactionContent().getHash() + "]!", TransactionState.IGNORED_BY_WRONG_LEDGER); } - // TODO: 把验签和创建交易并行化; - if (SettingContext.txSettings().verifySignature() && !verifyTxContent(txRequest)) { - // 抛弃哈希和签名校验失败的交易请求; - throw new IllegalTransactionException( - "Wrong transaction signature! --[TxHash=" + txRequest.getTransactionContent().getHash() + "]!", - TransactionState.IGNORED_BY_WRONG_CONTENT_SIGNATURE); - } - if (currentTxCtx != null) { throw new IllegalStateException( "Unable to open another new transaction before the current transaction is completed! --[TxHash=" @@ -253,7 +235,7 @@ public class LedgerTransactionalEditor implements LedgerEditor { // init storage of new transaction; BufferedKVStorage txBufferedStorage = new BufferedKVStorage(baseStorage, baseStorage, false); - LedgerDataSetImpl txDataset = null; + LedgerDataset txDataset = null; TransactionSet txset = null; if (previousTxSnapshot == null) { // load the starting point of the new transaction; @@ -262,18 +244,18 @@ public class LedgerTransactionalEditor implements LedgerEditor { GenesisSnapshot snpht = (GenesisSnapshot) startingPoint; txDataset = LedgerRepositoryImpl.newDataSet(snpht.initSetting, ledgerKeyPrefix, txBufferedStorage, txBufferedStorage); - txset = LedgerRepositoryImpl.newTransactionSet(txDataset.getAdminAccount().getSetting(), + txset = LedgerRepositoryImpl.newTransactionSet(txDataset.getAdminDataset().getSettings(), ledgerKeyPrefix, txBufferedStorage, txBufferedStorage); } else if (startingPoint instanceof TxSnapshot) { // 新的区块; // TxSnapshot; reload dataset and txset; TxSnapshot snpht = (TxSnapshot) startingPoint; // load dataset; - txDataset = LedgerRepositoryImpl.loadDataSet(snpht.dataSnapshot, ledgerKeyPrefix, txBufferedStorage, - txBufferedStorage, false); + txDataset = LedgerRepositoryImpl.loadDataSet(snpht.dataSnapshot, cryptoSetting, ledgerKeyPrefix, + txBufferedStorage, txBufferedStorage, false); // load txset; - txset = LedgerRepositoryImpl.loadTransactionSet(snpht.txsetHash, this.cryptoSetting, ledgerKeyPrefix, + txset = LedgerRepositoryImpl.loadTransactionSet(snpht.txsetHash, cryptoSetting, ledgerKeyPrefix, txBufferedStorage, txBufferedStorage, false); } else { // Unreachable; @@ -283,11 +265,11 @@ public class LedgerTransactionalEditor implements LedgerEditor { } else { // Reuse previous object to optimize performance; // load dataset; - txDataset = LedgerRepositoryImpl.loadDataSet(previousTxSnapshot.dataSnapshot, ledgerKeyPrefix, - txBufferedStorage, txBufferedStorage, false); + txDataset = LedgerRepositoryImpl.loadDataSet(previousTxSnapshot.dataSnapshot, cryptoSetting, + ledgerKeyPrefix, txBufferedStorage, txBufferedStorage, false); // load txset; - txset = LedgerRepositoryImpl.loadTransactionSet(previousTxSnapshot.txsetHash, this.cryptoSetting, + txset = LedgerRepositoryImpl.loadTransactionSet(previousTxSnapshot.txsetHash, cryptoSetting, ledgerKeyPrefix, txBufferedStorage, txBufferedStorage, false); } @@ -476,28 +458,6 @@ public class LedgerTransactionalEditor implements LedgerEditor { } -// /** -// * 账本的数据上下文; -// * -// * @author huanghaiquan -// * -// */ -// private static class LedgerDataContext { -// -// protected LedgerDataSetImpl dataset; -// -// protected TransactionSet txset; -// -// protected BufferedKVStorage storage; -// -// public LedgerDataContext(LedgerDataSetImpl dataset, TransactionSet txset, BufferedKVStorage storage) { -// this.dataset = dataset; -// this.txset = txset; -// this.storage = storage; -// } -// -// } - /** * 交易的上下文; * @@ -510,7 +470,7 @@ public class LedgerTransactionalEditor implements LedgerEditor { private TransactionRequest txRequest; - private LedgerDataSetImpl dataset; + private LedgerDataset dataset; private TransactionSet txset; @@ -524,7 +484,7 @@ public class LedgerTransactionalEditor implements LedgerEditor { private HashDigest txRootHash; - private LedgerTransactionContextImpl(TransactionRequest txRequest, LedgerDataSetImpl dataset, + private LedgerTransactionContextImpl(TransactionRequest txRequest, LedgerDataset dataset, TransactionSet txset, BufferedKVStorage storage, LedgerTransactionalEditor editor) { this.txRequest = txRequest; this.dataset = dataset; @@ -534,10 +494,15 @@ public class LedgerTransactionalEditor implements LedgerEditor { } @Override - public LedgerDataSet getDataSet() { + public LedgerDataset getDataset() { return dataset; } + @Override + public TransactionSet getTransactionSet() { + return txset; + } + @Override public TransactionRequest getTransactionRequest() { return txRequest; @@ -620,8 +585,8 @@ public class LedgerTransactionalEditor implements LedgerEditor { private TransactionStagedSnapshot takeDataSnapshot() { TransactionStagedSnapshot txDataSnapshot = new TransactionStagedSnapshot(); - txDataSnapshot.setAdminAccountHash(dataset.getAdminAccount().getHash()); - txDataSnapshot.setContractAccountSetHash(dataset.getContractAccountSet().getRootHash()); + txDataSnapshot.setAdminAccountHash(dataset.getAdminDataset().getHash()); + txDataSnapshot.setContractAccountSetHash(dataset.getContractAccountset().getRootHash()); txDataSnapshot.setDataAccountSetHash(dataset.getDataAccountSet().getRootHash()); txDataSnapshot.setUserAccountSetHash(dataset.getUserAccountSet().getRootHash()); return txDataSnapshot; diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleDataEntry.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleDataEntry.java index 527e7115..3dd99df0 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleDataEntry.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleDataEntry.java @@ -1,5 +1,6 @@ package com.jd.blockchain.ledger.core; +import com.jd.blockchain.ledger.MerkleProof; import com.jd.blockchain.storage.service.VersioningKVEntry; public interface MerkleDataEntry { 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 59ebd13f..16927b97 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 @@ -3,11 +3,14 @@ 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.VersioningKVEntry; 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.Bytes; import com.jd.blockchain.utils.Transactional; import com.jd.blockchain.utils.io.BytesUtils; @@ -62,12 +65,9 @@ public class MerkleDataSet implements Transactional, MerkleProvable { /** * 创建一个新的 MerkleDataSet; * - * @param setting - * 密码设置; - * @param exPolicyStorage - * 默克尔树的存储; - * @param versioningStorage - * 数据的存储; + * @param setting 密码设置; + * @param exPolicyStorage 默克尔树的存储; + * @param versioningStorage 数据的存储; */ public MerkleDataSet(CryptoSetting setting, String keyPrefix, ExPolicyKVStorage exPolicyStorage, VersioningKVStorage versioningStorage) { @@ -126,6 +126,10 @@ public class MerkleDataSet implements Transactional, MerkleProvable { return readonly; } + void setReadonly() { + this.readonly = true; + } + public long getDataCount() { return merkleTree.getDataCount(); } @@ -150,8 +154,27 @@ public class MerkleDataSet implements Transactional, MerkleProvable { return values; } + public VersioningKVEntry[] getLatestDataEntries(int 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!"); + } + VersioningKVEntry[] values = new VersioningKVEntry[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; + } + /** * get the data at the specific index; + * * @param fromIndex * @return */ @@ -163,6 +186,7 @@ public class MerkleDataSet implements Transactional, MerkleProvable { /** * get the key at the specific index; + * * @param fromIndex * @return */ @@ -171,7 +195,6 @@ public class MerkleDataSet implements Transactional, MerkleProvable { return dataNode.getKey().toUTF8String(); } - /** * Create or update the value associated the specified key if the version * checking is passed.
@@ -183,12 +206,9 @@ public class MerkleDataSet implements Transactional, MerkleProvable { * 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. + * @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;
@@ -210,12 +230,9 @@ public class MerkleDataSet implements Transactional, MerkleProvable { * 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. + * @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;
@@ -404,12 +421,22 @@ public class MerkleDataSet implements Transactional, MerkleProvable { return getDataEntry(Bytes.fromString(key)); } + /** + * + * @param key + * @return Null if the key doesn't exist! + */ public VersioningKVEntry getDataEntry(Bytes key) { long latestVersion = getMerkleVersion(key); if (latestVersion < 0) { return null; } - return valueStorage.getEntry(key, latestVersion); + Bytes dataKey = encodeDataKey(key); + byte[] value = valueStorage.get(dataKey, latestVersion); + if (value == null) { + return null; + } + return new VersioningKVData(key, latestVersion, value); } public VersioningKVEntry getDataEntry(Bytes key, long version) { @@ -420,7 +447,12 @@ public class MerkleDataSet implements Transactional, MerkleProvable { return null; } version = version < 0 ? latestVersion : version; - return valueStorage.getEntry(key, version); + Bytes dataKey = encodeDataKey(key); + byte[] value = valueStorage.get(dataKey, version); + if (value == null) { + return null; + } + return new VersioningKVData(key, version, value); } public MerkleDataEntry getMerkleEntry(Bytes key, long version) { diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleProvable.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleProvable.java index 2f93bad7..f778279f 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleProvable.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleProvable.java @@ -1,6 +1,7 @@ package com.jd.blockchain.ledger.core; import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.ledger.MerkleProof; import com.jd.blockchain.utils.Bytes; public interface MerkleProvable { diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleTree.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleTree.java index 7c3c077c..d86facba 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleTree.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleTree.java @@ -20,6 +20,9 @@ import com.jd.blockchain.crypto.HashDigest; import com.jd.blockchain.crypto.HashFunction; import com.jd.blockchain.ledger.CryptoSetting; import com.jd.blockchain.ledger.LedgerException; +import com.jd.blockchain.ledger.MerkleDataNode; +import com.jd.blockchain.ledger.MerkleNode; +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.utils.Bytes; diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MultiIDsPolicy.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MultiIDsPolicy.java new file mode 100644 index 00000000..20f1caab --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MultiIDsPolicy.java @@ -0,0 +1,21 @@ +package com.jd.blockchain.ledger.core; + +/** + * 多重身份的校验策略; + * + * @author huanghaiquan + * + */ +public enum MultiIDsPolicy { + + /** + * 至少有一个都能通过; + */ + AT_LEAST_ONE, + + /** + * 每一个都能通过; + */ + ALL + +} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/OpeningAccessPolicy.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/OpeningAccessPolicy.java similarity index 82% rename from source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/OpeningAccessPolicy.java rename to source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/OpeningAccessPolicy.java index 14c5b9b4..6628aad3 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/OpeningAccessPolicy.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/OpeningAccessPolicy.java @@ -1,8 +1,7 @@ -package com.jd.blockchain.ledger.core.impl; +package com.jd.blockchain.ledger.core; import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.ledger.AccountHeader; -import com.jd.blockchain.ledger.core.AccountAccessPolicy; import com.jd.blockchain.utils.Bytes; /** diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/OperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/OperationHandle.java index e1a0f567..763ea51a 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/OperationHandle.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/OperationHandle.java @@ -2,8 +2,6 @@ package com.jd.blockchain.ledger.core; import com.jd.blockchain.ledger.BytesValue; import com.jd.blockchain.ledger.Operation; -import com.jd.blockchain.ledger.core.impl.OperationHandleContext; - public interface OperationHandle { @@ -13,42 +11,22 @@ public interface OperationHandle { * @param operationType * @return */ - boolean support(Class operationType); + Class getOperationType(); /** * 同步解析和执行操作; * * - * @param op - * 操作实例; - * @param newBlockDataset - * 需要修改的新区块的数据集; - * @param requestContext - * 交易请求上下文; - * @param previousBlockDataset - * 新区块的前一个区块的数据集;即未提交新区块之前的经过共识的账本最新数据集; + * @param op 操作实例; + * @param newBlockDataset 需要修改的新区块的数据集; + * @param requestContext 交易请求上下文; + * @param previousBlockDataset 新区块的前一个区块的数据集;即未提交新区块之前的经过共识的账本最新数据集;注:此数据集是只读的; * - * @return 操作执行结果 + * @param handleContext 操作上下文;` + * @param ledgerService + * @return */ - BytesValue process(Operation op, LedgerDataSet newBlockDataset, TransactionRequestContext requestContext, - LedgerDataSet previousBlockDataset, OperationHandleContext handleContext, LedgerService ledgerService); + BytesValue process(Operation op, LedgerDataset newBlockDataset, TransactionRequestExtension requestContext, + LedgerDataQuery previousBlockDataset, OperationHandleContext handleContext, LedgerService ledgerService); -// /** -// * 异步解析和执行操作; -// * TODO 未来规划实现 -// * -// * -// * @param op -// * 操作实例; -// * @param newBlockDataset -// * 需要修改的新区块的数据集; -// * @param requestContext -// * 交易请求上下文; -// * @param previousBlockDataset -// * 新区块的前一个区块的数据集;即未提交新区块之前的经过共识的账本最新数据集; -// * -// * @return 操作执行结果 -// */ -// AsyncFuture asyncProcess(Operation op, LedgerDataSet newBlockDataset, TransactionRequestContext requestContext, -// LedgerDataSet previousBlockDataset, OperationHandleContext handleContext, LedgerService ledgerService); } diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/OperationHandleContext.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/OperationHandleContext.java new file mode 100644 index 00000000..1d837f15 --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/OperationHandleContext.java @@ -0,0 +1,15 @@ +package com.jd.blockchain.ledger.core; + +import com.jd.blockchain.ledger.Operation; + +/** + * 在交易处理过程中,提供对多种交易操作处理器互相调用的机制; + * + * @author huanghaiquan + * + */ +public interface OperationHandleContext { + + void handle(Operation operation); + +} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/OperationHandleRegisteration.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/OperationHandleRegisteration.java new file mode 100644 index 00000000..1b783eb0 --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/OperationHandleRegisteration.java @@ -0,0 +1,9 @@ +package com.jd.blockchain.ledger.core; + +import com.jd.blockchain.ledger.Operation; + +public interface OperationHandleRegisteration { + + OperationHandle getHandle(Class operationType); + +} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/P2PRealm.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/P2PRealm.java deleted file mode 100644 index c7480e07..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/P2PRealm.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.jd.blockchain.ledger.core; - - -/** - * @author hhq - * @version 1.0 - * @created 14-6��-2018 12:13:33 - */ -public class P2PRealm { - - public Peer m_Peer; - - public P2PRealm(){ - - } - - public void finalize() throws Throwable { - - } - -} \ 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 b7918b51..45078129 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 @@ -2,6 +2,7 @@ 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; /** @@ -13,7 +14,7 @@ import com.jd.blockchain.ledger.ParticipantNodeState; public class ParticipantCertData implements ParticipantNode { private int id; - private String address; + private Bytes address; private String name; private PubKey pubKey; private ParticipantNodeState participantNodeState; @@ -29,14 +30,14 @@ public class ParticipantCertData implements ParticipantNode { this.participantNodeState = participantNode.getParticipantNodeState(); } - public ParticipantCertData(String address, String name, PubKey pubKey) { + public ParticipantCertData(Bytes address, String name, PubKey pubKey) { this.address = address; this.name = name; this.pubKey = pubKey; } @Override - public String getAddress() { + public Bytes getAddress() { return address; } diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ParticipantDataSet.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ParticipantDataset.java similarity index 81% rename from source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ParticipantDataSet.java rename to source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ParticipantDataset.java index 44f82e21..dbc077a8 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ParticipantDataSet.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/ParticipantDataset.java @@ -4,14 +4,16 @@ import com.jd.blockchain.binaryproto.BinaryProtocol; import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.crypto.HashDigest; import com.jd.blockchain.ledger.ParticipantNode; +import com.jd.blockchain.ledger.ParticipantDataQuery; 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; -public class ParticipantDataSet implements Transactional, MerkleProvable { +public class ParticipantDataset implements Transactional, MerkleProvable, ParticipantDataQuery { static { DataContractRegistry.register(ParticipantNode.class); @@ -19,12 +21,12 @@ public class ParticipantDataSet implements Transactional, MerkleProvable { private MerkleDataSet dataset; - public ParticipantDataSet(CryptoSetting cryptoSetting, String prefix, ExPolicyKVStorage exPolicyStorage, + public ParticipantDataset(CryptoSetting cryptoSetting, String prefix, ExPolicyKVStorage exPolicyStorage, VersioningKVStorage verStorage) { dataset = new MerkleDataSet(cryptoSetting, prefix, exPolicyStorage, verStorage); } - public ParticipantDataSet(HashDigest merkleRootHash, CryptoSetting cryptoSetting, String prefix, + public ParticipantDataset(HashDigest merkleRootHash, CryptoSetting cryptoSetting, String prefix, ExPolicyKVStorage exPolicyStorage, VersioningKVStorage verStorage, boolean readonly) { dataset = new MerkleDataSet(merkleRootHash, cryptoSetting, prefix, exPolicyStorage, verStorage, readonly); } @@ -54,6 +56,7 @@ public class ParticipantDataSet implements Transactional, MerkleProvable { dataset.cancel(); } + @Override public long getParticipantCount() { return dataset.getDataCount(); } @@ -92,9 +95,15 @@ public class ParticipantDataSet implements Transactional, MerkleProvable { } } - private Bytes encodeKey(String address) { - // return id + ""; - return Bytes.fromString(address); + private Bytes encodeKey(Bytes address) { + return address; + } + + @Override + public boolean contains(Bytes address) { + Bytes key = encodeKey(address); + long latestVersion = dataset.getVersion(key); + return latestVersion > -1; } /** @@ -106,7 +115,8 @@ public class ParticipantDataSet implements Transactional, MerkleProvable { * @param address * @return */ - public ParticipantNode getParticipant(String address) { + @Override + public ParticipantNode getParticipant(Bytes address) { Bytes key = encodeKey(address); byte[] bytes = dataset.getValue(key); if (bytes == null) { @@ -114,11 +124,12 @@ public class ParticipantDataSet implements Transactional, MerkleProvable { } return BinaryProtocol.decode(bytes); } - + + @Override public ParticipantNode[] getParticipants() { - byte[][] bytes = dataset.getLatestValues(0, (int)dataset.getDataCount()); + byte[][] bytes = dataset.getLatestValues(0, (int) dataset.getDataCount()); ParticipantNode[] pns = new ParticipantNode[bytes.length]; - + for (int i = 0; i < pns.length; i++) { pns[i] = BinaryProtocol.decode(bytes[i]); } diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/PermissionService.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/PermissionService.java index b3b9a7c2..78be086b 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/PermissionService.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/PermissionService.java @@ -1,7 +1,5 @@ package com.jd.blockchain.ledger.core; -import java.util.SortedSet; - public interface PermissionService { boolean checkLedgerPermission(); diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/PrivilegeDataSet.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/PrivilegeDataSet.java deleted file mode 100644 index 9bdc3f3b..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/PrivilegeDataSet.java +++ /dev/null @@ -1,21 +0,0 @@ -//package com.jd.blockchain.ledger.core; -// -//import com.jd.blockchain.crypto.hash.HashDigest; -//import com.jd.blockchain.ledger.data.DigitalSignatureBlob; -// -//import my.utils.io.ExistentialKVStorage; -//import my.utils.io.VersioningKVStorage; -// -//public class PrivilegeDataSet extends GenericMerkleDataSet { -// -// public PrivilegeDataSet(CryptoSetting setting, ExistentialKVStorage merkleTreeStorage, VersioningKVStorage dataStorage) { -// this(null, setting, merkleTreeStorage, dataStorage, false); -// } -// -// public PrivilegeDataSet(HashDigest rootHash, CryptoSetting setting, ExistentialKVStorage merkleTreeStorage, -// VersioningKVStorage dataStorage, boolean readonly) { -// super(rootHash, setting, merkleTreeStorage, dataStorage, readonly, Authorization.class, AuthorizationVO.class, -// DigitalSignatureBlob.class); -// } -// -//} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/RolePrivilegeDataset.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/RolePrivilegeDataset.java new file mode 100644 index 00000000..14673435 --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/RolePrivilegeDataset.java @@ -0,0 +1,293 @@ +package com.jd.blockchain.ledger.core; + +import com.jd.blockchain.binaryproto.BinaryProtocol; +import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.ledger.CryptoSetting; +import com.jd.blockchain.ledger.LedgerException; +import com.jd.blockchain.ledger.LedgerPermission; +import com.jd.blockchain.ledger.LedgerPrivilege; +import com.jd.blockchain.ledger.MerkleProof; +import com.jd.blockchain.ledger.PrivilegeSet; +import com.jd.blockchain.ledger.Privileges; +import com.jd.blockchain.ledger.RolePrivilegeSettings; +import com.jd.blockchain.ledger.RolePrivileges; +import com.jd.blockchain.ledger.TransactionPermission; +import com.jd.blockchain.ledger.TransactionPrivilege; +import com.jd.blockchain.storage.service.ExPolicyKVStorage; +import com.jd.blockchain.storage.service.VersioningKVEntry; +import com.jd.blockchain.storage.service.VersioningKVStorage; +import com.jd.blockchain.utils.Bytes; +import com.jd.blockchain.utils.Transactional; + +public class RolePrivilegeDataset implements Transactional, MerkleProvable, RolePrivilegeSettings { + + private MerkleDataSet dataset; + + public RolePrivilegeDataset(CryptoSetting cryptoSetting, String prefix, ExPolicyKVStorage exPolicyStorage, + VersioningKVStorage verStorage) { + dataset = new MerkleDataSet(cryptoSetting, prefix, exPolicyStorage, verStorage); + } + + public RolePrivilegeDataset(HashDigest merkleRootHash, CryptoSetting cryptoSetting, String prefix, + ExPolicyKVStorage exPolicyStorage, VersioningKVStorage verStorage, boolean readonly) { + dataset = new MerkleDataSet(merkleRootHash, cryptoSetting, prefix, exPolicyStorage, verStorage, readonly); + } + + @Override + public HashDigest getRootHash() { + return dataset.getRootHash(); + } + + @Override + public MerkleProof getProof(Bytes key) { + return dataset.getProof(key); + } + + @Override + public boolean isUpdated() { + return dataset.isUpdated(); + } + + @Override + public void commit() { + dataset.commit(); + } + + @Override + public void cancel() { + dataset.cancel(); + } + + @Override + public long getRoleCount() { + return dataset.getDataCount(); + } + + @Override + public long addRolePrivilege(String roleName, Privileges privileges) { + return addRolePrivilege(roleName, privileges.getLedgerPrivilege(), privileges.getTransactionPrivilege()); + } + + @Override + public long addRolePrivilege(String roleName, LedgerPrivilege ledgerPrivilege, TransactionPrivilege txPrivilege) { + RolePrivileges roleAuth = new RolePrivileges(roleName, -1, ledgerPrivilege, txPrivilege); + long nv = setRolePrivilege(roleAuth); + if (nv < 0) { + throw new LedgerException("Role[" + roleName + "] already exist!"); + } + return nv; + } + + @Override + public long addRolePrivilege(String roleName, LedgerPermission[] ledgerPermissions, + TransactionPermission[] txPermissions) { + LedgerPrivilege ledgerPrivilege = new LedgerPrivilege(); + for (LedgerPermission lp : ledgerPermissions) { + ledgerPrivilege.enable(lp); + } + TransactionPrivilege txPrivilege = new TransactionPrivilege(); + for (TransactionPermission tp : txPermissions) { + txPrivilege.enable(tp); + } + return addRolePrivilege(roleName, ledgerPrivilege, txPrivilege); + } + + /** + * 设置角色权限;
+ * 如果版本校验不匹配,则返回 -1; + * + * @param roleAuth + * @return + */ + private long setRolePrivilege(RolePrivileges roleAuth) { + if (roleAuth.getRoleName().length() > MAX_ROLE_NAME_LENGTH) { + throw new LedgerException("Too long role name!"); + } + Bytes key = encodeKey(roleAuth.getRoleName()); + byte[] privilegeBytes = BinaryProtocol.encode(roleAuth, PrivilegeSet.class); + return dataset.setValue(key, privilegeBytes, roleAuth.getVersion()); + } + + /** + * 更新角色权限;
+ * 如果指定的角色不存在,或者版本不匹配,则引发 {@link LedgerException} 异常; + * + * @param participant + */ + @Override + public void updateRolePrivilege(RolePrivileges roleAuth) { + long nv = setRolePrivilege(roleAuth); + if (nv < 0) { + throw new LedgerException("Update to RoleAuthorization[" + roleAuth.getRoleName() + + "] failed due to wrong version[" + roleAuth.getVersion() + "] !"); + } + } + + /** + * 授权角色指定的权限;
+ * 如果角色不存在,则返回 -1; + * + * @param roleName 角色; + * @param permissions 权限列表; + * @return + */ + @Override + public long enablePermissions(String roleName, LedgerPermission... permissions) { + RolePrivileges roleAuth = getRolePrivilege(roleName); + if (roleAuth == null) { + return -1; + } + roleAuth.getLedgerPrivilege().enable(permissions); + return setRolePrivilege(roleAuth); + } + + /** + * 授权角色指定的权限;
+ * 如果角色不存在,则返回 -1; + * + * @param roleName 角色; + * @param permissions 权限列表; + * @return + */ + @Override + public long enablePermissions(String roleName, TransactionPermission... permissions) { + RolePrivileges roleAuth = getRolePrivilege(roleName); + if (roleAuth == null) { + return -1; + } + roleAuth.getTransactionPrivilege().enable(permissions); + return setRolePrivilege(roleAuth); + } + + /** + * 禁止角色指定的权限;
+ * 如果角色不存在,则返回 -1; + * + * @param roleName 角色; + * @param permissions 权限列表; + * @return + */ + @Override + public long disablePermissions(String roleName, LedgerPermission... permissions) { + RolePrivileges roleAuth = getRolePrivilege(roleName); + if (roleAuth == null) { + return -1; + } + roleAuth.getLedgerPrivilege().disable(permissions); + return setRolePrivilege(roleAuth); + } + + /** + * 禁止角色指定的权限;
+ * 如果角色不存在,则返回 -1; + * + * @param roleName 角色; + * @param permissions 权限列表; + * @return + */ + @Override + public long disablePermissions(String roleName, TransactionPermission... permissions) { + RolePrivileges roleAuth = getRolePrivilege(roleName); + if (roleAuth == null) { + return -1; + } + roleAuth.getTransactionPrivilege().disable(permissions); + return setRolePrivilege(roleAuth); + } + + /** + * 授权角色指定的权限;
+ * 如果角色不存在,则返回 -1; + * + * @param roleName + * @param ledgerPermissions + * @param txPermissions + * @return + */ + @Override + public long enablePermissions(String roleName, LedgerPermission[] ledgerPermissions, + TransactionPermission[] txPermissions) { + RolePrivileges roleAuth = getRolePrivilege(roleName); + if (roleAuth == null) { + return -1; + } + roleAuth.getLedgerPrivilege().enable(ledgerPermissions); + roleAuth.getTransactionPrivilege().enable(txPermissions); + return setRolePrivilege(roleAuth); + } + + /** + * 禁用角色指定的权限;
+ * 如果角色不存在,则返回 -1; + * + * @param roleName + * @param ledgerPermissions + * @param txPermissions + * @return + */ + @Override + public long disablePermissions(String roleName, LedgerPermission[] ledgerPermissions, + TransactionPermission[] txPermissions) { + RolePrivileges roleAuth = getRolePrivilege(roleName); + if (roleAuth == null) { + return -1; + } + roleAuth.getLedgerPrivilege().disable(ledgerPermissions); + roleAuth.getTransactionPrivilege().disable(txPermissions); + return setRolePrivilege(roleAuth); + } + + private Bytes encodeKey(String address) { + // return id + ""; + return Bytes.fromString(address); + } + + /** + * 查询角色权限; + * + *
+ * 如果不存在,则返回 null; + * + * @param address + * @return + */ + @Override + public RolePrivileges getRolePrivilege(String roleName) { + // 只返回最新版本; + Bytes key = encodeKey(roleName); + VersioningKVEntry kv = dataset.getDataEntry(key); + if (kv == null) { + return null; + } + PrivilegeSet privilege = BinaryProtocol.decode(kv.getValue()); + return new RolePrivileges(roleName, kv.getVersion(), privilege); + } + + @Override + public RolePrivileges[] getRolePrivileges(int index, int count) { + VersioningKVEntry[] kvEntries = dataset.getLatestDataEntries(index, count); + RolePrivileges[] pns = new RolePrivileges[kvEntries.length]; + PrivilegeSet privilege; + for (int i = 0; i < pns.length; i++) { + privilege = BinaryProtocol.decode(kvEntries[i].getValue()); + pns[i] = new RolePrivileges(kvEntries[i].getKey().toUTF8String(), kvEntries[i].getVersion(), privilege); + } + return pns; + } + + @Override + public RolePrivileges[] getRolePrivileges() { + return getRolePrivileges(0, (int) getRoleCount()); + } + + @Override + public boolean isReadonly() { + return dataset.isReadonly(); + } + + @Override + public boolean contains(String roleName) { + Bytes key = encodeKey(roleName); + return dataset.getVersion(key) > -1; + } +} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/SecurityContext.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/SecurityContext.java new file mode 100644 index 00000000..d3ad83ba --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/SecurityContext.java @@ -0,0 +1,38 @@ +package com.jd.blockchain.ledger.core; + +import java.util.Set; + +import com.jd.blockchain.ledger.BlockchainIdentity; +import com.jd.blockchain.ledger.LedgerPermission; +import com.jd.blockchain.ledger.LedgerSecurityException; +import com.jd.blockchain.ledger.TransactionPermission; + +public class SecurityContext { + + private static ThreadLocal policyHolder = new ThreadLocal(); + + public static void setContextUsersPolicy(SecurityPolicy policy) { + policyHolder.set(policy); + } + + public static SecurityPolicy removeContextUsersPolicy() { + SecurityPolicy p = policyHolder.get(); + policyHolder.remove(); + return p; + } + + public static SecurityPolicy getContextUsersPolicy() { + return policyHolder.get(); + } + + /** + * 把上下文安全策略切换为指定的策略,并执行参数指定的 {@link Runnable} 操作,当操作完成后恢复原来的上下文策略; + * + * @param contextUsersPolicy + * @param runnable + */ + public static void switchContextUsersPolicy(SecurityPolicy contextUsersPolicy, Runnable runnable) { + + } + +} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/SecurityPolicy.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/SecurityPolicy.java new file mode 100644 index 00000000..17d487dd --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/SecurityPolicy.java @@ -0,0 +1,142 @@ +package com.jd.blockchain.ledger.core; + +import java.util.Set; + +import com.jd.blockchain.ledger.LedgerPermission; +import com.jd.blockchain.ledger.LedgerSecurityException; +import com.jd.blockchain.ledger.TransactionPermission; +import com.jd.blockchain.ledger.TransactionRequest; +import com.jd.blockchain.utils.Bytes; + +/** + * 针对特定交易请求的账本安全策略; + * + * @author huanghaiquan + * + */ +public interface SecurityPolicy { + + /** + * 签署交易的终端用户的地址列表;(来自{@link TransactionRequest#getEndpointSignatures()}) + * + * @return + */ + Set getEndpoints(); + + /** + * 签署交易的节点参与方的地址列表(来自{@link TransactionRequest#getNodeSignatures()}) + * + * @return + */ + Set getNodes(); + + /** + * 终端身份是否合法; + * + * @param midPolicy + * @return + */ + boolean isEndpointValid(MultiIDsPolicy midPolicy); + + /** + * 节点身份是否合法; + * + * @param midPolicy + * @return + */ + boolean isNodeValid(MultiIDsPolicy midPolicy); + + /** + * 检查签署交易的终端用户(来自{@link TransactionRequest#getEndpointSignatures()})是否被授权了参数指定的权限;
+ * + * @param permission 要检查的权限; + * @param midPolicy 针对多个签名用户的权限策略; + * @return 返回 true 表示获得授权; 返回 false 表示未获得授权; + */ + boolean isEndpointEnable(LedgerPermission permission, MultiIDsPolicy midPolicy); + + /** + * 检查签署交易的终端用户(来自{@link TransactionRequest#getEndpointSignatures()})是否被授权了参数指定的权限;
+ * + * @param permission 要检查的权限; + * @param midPolicy 针对多个签名用户的权限策略; + * @return 返回 true 表示获得授权; 返回 false 表示未获得授权; + */ + boolean isEndpointEnable(TransactionPermission permission, MultiIDsPolicy midPolicy); + + /** + * 检查签署交易的节点参与方(来自{@link TransactionRequest#getNodeSignatures()})是否被授权了参数指定的权限;
+ * + * @param permission 要检查的权限; + * @param midPolicy 针对多个签名用户的权限策略; + * @return 返回 true 表示获得授权; 返回 false 表示未获得授权; + */ + boolean isNodeEnable(LedgerPermission permission, MultiIDsPolicy midPolicy); + + /** + * 检查签署交易的节点参与方(来自{@link TransactionRequest#getNodeSignatures()})是否被授权了参数指定的权限;
+ * + * @param permission 要检查的权限; + * @param midPolicy 针对多个签名用户的权限策略; + * @return 返回 true 表示获得授权; 返回 false 表示未获得授权; + */ + boolean isNodeEnable(TransactionPermission permission, MultiIDsPolicy midPolicy); + + /** + * 检查终端身份的合法性; + * + * @param midPolicy + * @throws LedgerSecurityException + */ + void checkEndpointValidity(MultiIDsPolicy midPolicy) throws LedgerSecurityException; + + /** + * 检查节点身份的合法性; + * + * @param midPolicy + * @throws LedgerSecurityException + */ + void checkNodeValidity(MultiIDsPolicy midPolicy) throws LedgerSecurityException; + + /** + * 检查签署交易的终端用户(来自{@link TransactionRequest#getEndpointSignatures()})是否被授权了参数指定的权限;
+ * 如果未获授权,方法将引发 {@link LedgerSecurityException} 异常; + * + * @param permission 要检查的权限; + * @param midPolicy 针对多个签名用户的权限策略; + * @throws LedgerSecurityException + */ + void checkEndpointPermission(LedgerPermission permission, MultiIDsPolicy midPolicy) throws LedgerSecurityException; + + /** + * 检查签署交易的终端用户(来自{@link TransactionRequest#getEndpointSignatures()})是否被授权了参数指定的权限;
+ * 如果未获授权,方法将引发 {@link LedgerSecurityException} 异常; + * + * @param permission + * @param midPolicy + * @throws LedgerSecurityException + */ + void checkEndpointPermission(TransactionPermission permission, MultiIDsPolicy midPolicy) + throws LedgerSecurityException; + + /** + * 检查签署交易的节点参与方(来自{@link TransactionRequest#getNodeSignatures()})是否被授权了参数指定的权限;
+ * 如果未获授权,方法将引发 {@link LedgerSecurityException} 异常; + * + * @param permission + * @param midPolicy + * @throws LedgerSecurityException + */ + void checkNodePermission(LedgerPermission permission, MultiIDsPolicy midPolicy) throws LedgerSecurityException; + + /** + * 检查签署交易的节点参与方(来自{@link TransactionRequest#getNodeSignatures()})是否被授权了参数指定的权限;
+ * 如果未获授权,方法将引发 {@link LedgerSecurityException} 异常; + * + * @param permission + * @param midPolicy + * @throws LedgerSecurityException + */ + void checkNodePermission(TransactionPermission permission, MultiIDsPolicy midPolicy) throws LedgerSecurityException; + +} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/SettingContext.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/SettingContext.java index 516b2acf..f464db7f 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/SettingContext.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/SettingContext.java @@ -1,51 +1,51 @@ -package com.jd.blockchain.ledger.core; - -public class SettingContext { - - private static final TxSettingContext txSettings = new TxSettingContext(); - - private static final QueryingSettingContext queryingSettings = new QueryingSettingContext(); - - public static TxSettingContext txSettings() { - return txSettings; - } - - public static QueryingSettingContext queryingSettings() { - return queryingSettings; - } - - /** - * 与交易处理相关的设置; - * @author huanghaiquan - * - */ - public static class TxSettingContext { - - public boolean verifyLedger() { - return true; - } - - public boolean verifySignature() { - return true; - } - - } - - /** - * 与账本查询相关的设置; - * @author huanghaiquan - * - */ - public static class QueryingSettingContext { - - /** - * 查询区块等具有 hash 标识符的对象时是否重新校验哈希; - * @return - */ - public boolean verifyHash() { - return false; - } - - } - -} +//package com.jd.blockchain.ledger.core; +// +//public class SettingContext { +// +// private static final TxSettingContext txSettings = new TxSettingContext(); +// +// private static final QueryingSettingContext queryingSettings = new QueryingSettingContext(); +// +// public static TxSettingContext txSettings() { +// return txSettings; +// } +// +// public static QueryingSettingContext queryingSettings() { +// return queryingSettings; +// } +// +// /** +// * 与交易处理相关的设置; +// * @author huanghaiquan +// * +// */ +// public static class TxSettingContext { +// +// public boolean verifyLedger() { +// return true; +// } +// +// public boolean verifySignature() { +// return true; +// } +// +// } +// +// /** +// * 与账本查询相关的设置; +// * @author huanghaiquan +// * +// */ +// public static class QueryingSettingContext { +// +// /** +// * 查询区块等具有 hash 标识符的对象时是否重新校验哈希; +// * @return +// */ +// public boolean verifyHash() { +// return false; +// } +// +// } +// +//} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/TransactionBatchProcessor.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionBatchProcessor.java similarity index 65% rename from source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/TransactionBatchProcessor.java rename to source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionBatchProcessor.java index aa8fcf93..cab2a4e2 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/TransactionBatchProcessor.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionBatchProcessor.java @@ -1,6 +1,7 @@ -package com.jd.blockchain.ledger.core.impl; +package com.jd.blockchain.ledger.core; import java.util.ArrayList; +import java.util.Collection; import java.util.Iterator; import java.util.List; @@ -15,35 +16,37 @@ import com.jd.blockchain.ledger.DataAccountDoesNotExistException; import com.jd.blockchain.ledger.IllegalTransactionException; import com.jd.blockchain.ledger.LedgerBlock; import com.jd.blockchain.ledger.LedgerException; +import com.jd.blockchain.ledger.LedgerPermission; +import com.jd.blockchain.ledger.LedgerSecurityException; import com.jd.blockchain.ledger.Operation; import com.jd.blockchain.ledger.OperationResult; import com.jd.blockchain.ledger.OperationResultData; +import com.jd.blockchain.ledger.ParticipantDoesNotExistException; +import com.jd.blockchain.ledger.TransactionContent; import com.jd.blockchain.ledger.TransactionRequest; import com.jd.blockchain.ledger.TransactionResponse; import com.jd.blockchain.ledger.TransactionRollbackException; import com.jd.blockchain.ledger.TransactionState; import com.jd.blockchain.ledger.UserDoesNotExistException; -import com.jd.blockchain.ledger.core.LedgerDataSet; -import com.jd.blockchain.ledger.core.LedgerEditor; -import com.jd.blockchain.ledger.core.LedgerService; -import com.jd.blockchain.ledger.core.LedgerTransactionContext; -import com.jd.blockchain.ledger.core.OperationHandle; -import com.jd.blockchain.ledger.core.TransactionRequestContext; +import com.jd.blockchain.ledger.core.TransactionRequestExtension.Credential; import com.jd.blockchain.service.TransactionBatchProcess; import com.jd.blockchain.service.TransactionBatchResult; import com.jd.blockchain.service.TransactionBatchResultHandle; +import com.jd.blockchain.transaction.SignatureUtils; +import com.jd.blockchain.transaction.TxBuilder; import com.jd.blockchain.transaction.TxResponseMessage; -import com.jd.blockchain.utils.Bytes; public class TransactionBatchProcessor implements TransactionBatchProcess { private static final Logger LOGGER = LoggerFactory.getLogger(TransactionBatchProcessor.class); + private LedgerSecurityManager securityManager; + private LedgerService ledgerService; private LedgerEditor newBlockEditor; - private LedgerDataSet previousBlockDataset; + private LedgerDataQuery ledgerQueryer; private OperationHandleRegisteration opHandles; @@ -57,14 +60,15 @@ public class TransactionBatchProcessor implements TransactionBatchProcess { private TransactionBatchResult batchResult; /** - * @param newBlockEditor 新区块的数据编辑器; - * @param previousBlockDataset 新区块的前一个区块的数据集;即未提交新区块之前的经过共识的账本最新数据集; - * @param opHandles 操作处理对象注册表; + * @param newBlockEditor 新区块的数据编辑器; + * @param ledgerQueryer 账本查询器,只包含新区块的前一个区块的数据集;即未提交新区块之前的经过共识的账本最新数据集; + * @param opHandles 操作处理对象注册表; */ - public TransactionBatchProcessor(LedgerEditor newBlockEditor, LedgerDataSet previousBlockDataset, - OperationHandleRegisteration opHandles, LedgerService ledgerService) { + public TransactionBatchProcessor(LedgerSecurityManager securityManager, LedgerEditor newBlockEditor, + LedgerDataQuery ledgerQueryer, OperationHandleRegisteration opHandles, LedgerService ledgerService) { + this.securityManager = securityManager; this.newBlockEditor = newBlockEditor; - this.previousBlockDataset = previousBlockDataset; + this.ledgerQueryer = ledgerQueryer; this.opHandles = opHandles; this.ledgerService = ledgerService; } @@ -82,12 +86,26 @@ public class TransactionBatchProcessor implements TransactionBatchProcess { try { LOGGER.debug("Start handling transaction... --[BlockHeight={}][RequestHash={}][TxHash={}]", newBlockEditor.getBlockHeight(), request.getHash(), request.getTransactionContent().getHash()); + + TransactionRequestExtension reqExt = new TransactionRequestExtensionImpl(request); + + // 初始化交易的用户安全策略; + SecurityPolicy securityPolicy = securityManager.createSecurityPolicy(reqExt.getEndpointAddresses(), + reqExt.getNodeAddresses()); + SecurityContext.setContextUsersPolicy(securityPolicy); + + // 安全校验; + checkSecurity(securityPolicy); + + // 验证交易请求; + checkRequest(reqExt); + // 创建交易上下文; // 此调用将会验证交易签名,验签失败将会抛出异常,同时,不记录签名错误的交易到链上; LedgerTransactionContext txCtx = newBlockEditor.newTransaction(request); // 处理交易; - resp = handleTx(request, txCtx); + resp = handleTx(reqExt, txCtx); LOGGER.debug("Complete handling transaction. --[BlockHeight={}][RequestHash={}][TxHash={}]", newBlockEditor.getBlockHeight(), request.getHash(), request.getTransactionContent().getHash()); @@ -99,10 +117,9 @@ public class TransactionBatchProcessor implements TransactionBatchProcess { "Ignore transaction caused by IllegalTransactionException! --[BlockHeight=%s][RequestHash=%s][TxHash=%s] --%s", newBlockEditor.getBlockHeight(), request.getHash(), request.getTransactionContent().getHash(), e.getMessage()), e); - + } catch (BlockRollbackException e) { - // 抛弃发生处理异常的交易请求; -// resp = discard(request, TransactionState.IGNORED_BY_BLOCK_FULL_ROLLBACK); + // 发生区块级别的处理异常,向上重新抛出异常进行处理,整个区块可能被丢弃; LOGGER.error(String.format( "Ignore transaction caused by BlockRollbackException! --[BlockHeight=%s][RequestHash=%s][TxHash=%s] --%s", newBlockEditor.getBlockHeight(), request.getHash(), request.getTransactionContent().getHash(), @@ -116,12 +133,79 @@ public class TransactionBatchProcessor implements TransactionBatchProcess { newBlockEditor.getBlockHeight(), request.getHash(), request.getTransactionContent().getHash(), e.getMessage()), e); + } finally { + // 清空交易的用户安全策略; + SecurityContext.removeContextUsersPolicy(); } responseList.add(resp); return resp; } + /** + * 执行安全验证; + */ + private void checkSecurity(SecurityPolicy securityPolicy) { + // 验证节点和终端身份的合法性; + // 多重身份签署的必须全部身份都合法; + securityPolicy.checkEndpointValidity(MultiIDsPolicy.ALL); + securityPolicy.checkNodeValidity(MultiIDsPolicy.ALL); + + // 验证参与方节点是否具有核准交易的权限; + securityPolicy.checkNodePermission(LedgerPermission.APPROVE_TX, MultiIDsPolicy.AT_LEAST_ONE); + } + + private void checkRequest(TransactionRequestExtension reqExt) { + // TODO: 把验签和创建交易并行化; + checkTxContentHash(reqExt); + checkEndpointSignatures(reqExt); + checkNodeSignatures(reqExt); + } + + private void checkTxContentHash(TransactionRequestExtension requestExt) { + TransactionContent txContent = requestExt.getTransactionContent(); + if (!TxBuilder.verifyTxContentHash(txContent, txContent.getHash())) { + // 由于哈希校验失败,引发IllegalTransactionException,使外部调用抛弃此交易请求; + throw new IllegalTransactionException( + "Wrong transaction content hash! --[TxHash=" + requestExt.getTransactionContent().getHash() + "]!", + TransactionState.IGNORED_BY_WRONG_CONTENT_SIGNATURE); + } + } + + private void checkNodeSignatures(TransactionRequestExtension request) { + TransactionContent txContent = request.getTransactionContent(); + Collection nodes = request.getNodes(); + if (nodes != null) { + for (Credential node : nodes) { + if (!SignatureUtils.verifyHashSignature(txContent.getHash(), node.getSignature().getDigest(), + node.getPubKey())) { + // 由于签名校验失败,引发IllegalTransactionException,使外部调用抛弃此交易请求; + throw new IllegalTransactionException( + String.format("Wrong transaction node signature! --[Tx Hash=%s][Node Signer=%s]!", + request.getTransactionContent().getHash(), node.getAddress()), + TransactionState.IGNORED_BY_WRONG_CONTENT_SIGNATURE); + } + } + } + } + + private void checkEndpointSignatures(TransactionRequestExtension request) { + TransactionContent txContent = request.getTransactionContent(); + Collection endpoints = request.getEndpoints(); + if (endpoints != null) { + for (Credential endpoint : endpoints) { + if (!SignatureUtils.verifyHashSignature(txContent.getHash(), endpoint.getSignature().getDigest(), + endpoint.getPubKey())) { + // 由于签名校验失败,引发IllegalTransactionException,使外部调用抛弃此交易请求; + throw new IllegalTransactionException( + String.format("Wrong transaction endpoint signature! --[Tx Hash=%s][Endpoint Signer=%s]!", + request.getTransactionContent().getHash(), endpoint.getAddress()), + TransactionState.IGNORED_BY_WRONG_CONTENT_SIGNATURE); + } + } + } + } + /** * 处理交易;
* @@ -131,23 +215,11 @@ public class TransactionBatchProcessor implements TransactionBatchProcess { * @param txCtx * @return */ - private TransactionResponse handleTx(TransactionRequest request, LedgerTransactionContext txCtx) { + private TransactionResponse handleTx(TransactionRequestExtension request, LedgerTransactionContext txCtx) { TransactionState result; List operationResults = new ArrayList<>(); try { - LedgerDataSet dataset = txCtx.getDataSet(); - TransactionRequestContext reqCtx = new TransactionRequestContextImpl(request); - // TODO: 验证签名者的有效性; - for (Bytes edpAddr : reqCtx.getEndpoints()) { - if (!previousBlockDataset.getUserAccountSet().contains(edpAddr)) { - throw new LedgerException("The endpoint signer[" + edpAddr + "] was not registered!"); - } - } - for (Bytes edpAddr : reqCtx.getNodes()) { - if (!previousBlockDataset.getUserAccountSet().contains(edpAddr)) { - throw new LedgerException("The node signer[" + edpAddr + "] was not registered!"); - } - } + LedgerDataset dataset = txCtx.getDataset(); // 执行操作; Operation[] ops = request.getTransactionContent().getOperations(); @@ -157,14 +229,14 @@ public class TransactionBatchProcessor implements TransactionBatchProcess { // assert; Instance of operation are one of User related operations or // DataAccount related operations; OperationHandle hdl = opHandles.getHandle(operation.getClass()); - hdl.process(operation, dataset, reqCtx, previousBlockDataset, this, ledgerService); + hdl.process(operation, dataset, request, ledgerQueryer, this, ledgerService); } }; OperationHandle opHandle; int opIndex = 0; for (Operation op : ops) { opHandle = opHandles.getHandle(op.getClass()); - BytesValue opResult = opHandle.process(op, dataset, reqCtx, previousBlockDataset, handleContext, + BytesValue opResult = opHandle.process(op, dataset, request, ledgerQueryer, handleContext, ledgerService); if (opResult != null) { operationResults.add(new OperationResultData(opIndex, opResult)); @@ -183,6 +255,7 @@ public class TransactionBatchProcessor implements TransactionBatchProcess { newBlockEditor.getBlockHeight(), request.getHash(), request.getTransactionContent().getHash(), e.getMessage()), e); } catch (BlockRollbackException e) { + // 回滚整个区块; result = TransactionState.IGNORED_BY_BLOCK_FULL_ROLLBACK; txCtx.rollback(); LOGGER.error( @@ -201,17 +274,27 @@ public class TransactionBatchProcessor implements TransactionBatchProcess { result = TransactionState.USER_DOES_NOT_EXIST; } else if (e instanceof ContractDoesNotExistException) { result = TransactionState.CONTRACT_DOES_NOT_EXIST; + } else if (e instanceof ParticipantDoesNotExistException) { + result = TransactionState.PARTICIPANT_DOES_NOT_EXIST; } txCtx.discardAndCommit(result, operationResults); LOGGER.error(String.format( - "Due to ledger exception, the data changes resulting from the transaction will be rolled back and the results of the transaction will be committed! --[BlockHeight=%s][RequestHash=%s][TxHash=%s] --%s", + "Due to ledger exception, the data changes resulting from transaction execution will be rolled back and the results of the transaction will be committed! --[BlockHeight=%s][RequestHash=%s][TxHash=%s] --%s", + newBlockEditor.getBlockHeight(), request.getHash(), request.getTransactionContent().getHash(), + e.getMessage()), e); + } catch (LedgerSecurityException e) { + // TODO: 识别更详细的异常类型以及执行对应的处理; + result = TransactionState.REJECTED_BY_SECURITY_POLICY; + txCtx.discardAndCommit(result, operationResults); + LOGGER.error(String.format( + "Due to ledger security exception, the data changes resulting from transaction execution will be rolled back and the results of the transaction will be committed! --[BlockHeight=%s][RequestHash=%s][TxHash=%s] --%s", newBlockEditor.getBlockHeight(), request.getHash(), request.getTransactionContent().getHash(), e.getMessage()), e); } catch (Exception e) { result = TransactionState.SYSTEM_ERROR; txCtx.discardAndCommit(TransactionState.SYSTEM_ERROR, operationResults); LOGGER.error(String.format( - "Due to system exception, the data changes resulting from the transaction will be rolled back and the results of the transaction will be committed! --[BlockHeight=%s][RequestHash=%s][TxHash=%s] --%s", + "Due to system exception, the data changes resulting from transaction execution will be rolled back and the results of the transaction will be committed! --[BlockHeight=%s][RequestHash=%s][TxHash=%s] --%s", newBlockEditor.getBlockHeight(), request.getHash(), request.getTransactionContent().getHash(), e.getMessage()), e); } diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/TransactionEngineImpl.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionEngineImpl.java similarity index 63% rename from source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/TransactionEngineImpl.java rename to source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionEngineImpl.java index bf2470e4..928997fd 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/TransactionEngineImpl.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionEngineImpl.java @@ -1,16 +1,12 @@ -package com.jd.blockchain.ledger.core.impl; +package com.jd.blockchain.ledger.core; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.LedgerBlock; import org.springframework.beans.factory.annotation.Autowired; -import com.jd.blockchain.ledger.core.LedgerDataSet; -import com.jd.blockchain.ledger.core.LedgerEditor; -import com.jd.blockchain.ledger.core.LedgerRepository; -import com.jd.blockchain.ledger.core.LedgerService; +import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.ledger.LedgerBlock; import com.jd.blockchain.service.TransactionBatchProcess; import com.jd.blockchain.service.TransactionEngine; @@ -44,9 +40,15 @@ public class TransactionEngineImpl implements TransactionEngine { LedgerBlock ledgerBlock = ledgerRepo.getLatestBlock(); LedgerEditor newBlockEditor = ledgerRepo.createNextBlock(); - LedgerDataSet previousBlockDataset = ledgerRepo.getDataSet(ledgerBlock); - batch = new InnerTransactionBatchProcessor(ledgerHash, newBlockEditor, previousBlockDataset, opHdlRegs, - ledgerService, ledgerBlock.getHeight()); + LedgerDataQuery previousBlockDataset = ledgerRepo.getDataSet(ledgerBlock); + + LedgerAdminDataQuery previousAdminDataset = previousBlockDataset.getAdminDataset(); + LedgerSecurityManager securityManager = new LedgerSecurityManagerImpl( + previousAdminDataset.getAdminInfo().getRolePrivileges(), + previousAdminDataset.getAdminInfo().getUserRoles(), previousAdminDataset.getParticipantDataset(), + previousBlockDataset.getUserAccountSet()); + batch = new InnerTransactionBatchProcessor(ledgerHash, securityManager, newBlockEditor, previousBlockDataset, + opHdlRegs, ledgerService, ledgerBlock.getHeight()); batchs.put(ledgerHash, batch); return batch; } @@ -69,19 +71,15 @@ public class TransactionEngineImpl implements TransactionEngine { /** * 创建交易批处理器; * - * @param ledgerHash - * 账本哈希; - * @param newBlockEditor - * 新区块的数据编辑器; - * @param previousBlockDataset - * 新区块的前一个区块的数据集;即未提交新区块之前的经过共识的账本最新数据集; - * @param opHandles - * 操作处理对象注册表; + * @param ledgerHash 账本哈希; + * @param newBlockEditor 新区块的数据编辑器; + * @param previousBlockDataset 新区块的前一个区块的数据集;即未提交新区块之前的经过共识的账本最新数据集; + * @param opHandles 操作处理对象注册表; */ - public InnerTransactionBatchProcessor(HashDigest ledgerHash, LedgerEditor newBlockEditor, - LedgerDataSet previousBlockDataset, OperationHandleRegisteration opHandles, - LedgerService ledgerService, long blockHeight) { - super(newBlockEditor, previousBlockDataset, opHandles, ledgerService); + public InnerTransactionBatchProcessor(HashDigest ledgerHash, LedgerSecurityManager securityManager, + LedgerEditor newBlockEditor, LedgerDataQuery previousBlockDataset, + OperationHandleRegisteration opHandles, LedgerService ledgerService, long blockHeight) { + super(securityManager, newBlockEditor, previousBlockDataset, opHandles, ledgerService); this.ledgerHash = ledgerHash; this.blockHeight = blockHeight; } diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionRequestContext.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionRequestContext.java deleted file mode 100644 index 324c4e0e..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionRequestContext.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.jd.blockchain.ledger.core; - -import java.util.Set; - -import com.jd.blockchain.ledger.DigitalSignature; -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.utils.Bytes; - -/** - * 交易请求上下文; - * - * @author huanghaiquan - * - */ -public interface TransactionRequestContext { - - /** - * 交易请求; - * - * @return - */ - TransactionRequest getRequest(); - - /** - * 签名发起请求的终端用户的地址列表; - * - * @return - */ - Set getEndpoints(); - - /** - * 签名发起请求的节点的地址列表; - * - * @return - */ - Set getNodes(); - - /** - * 请求的终端发起人列表中是否包含指定地址的终端用户; - * - * @param address - * @return - */ - boolean containsEndpoint(Bytes address); - - /** - * 请求的经手节点列表中是否包含指定地址的节点; - * - * @param address - * @return - */ - boolean containsNode(Bytes address); - - /** - * 获取交易请求中指定地址的终端的签名; - * - * @param address - * @return - */ - DigitalSignature getEndpointSignature(Bytes address); - - /** - * 获取交易请求中指定地址的节点的签名; - * - * @param address - * @return - */ - DigitalSignature getNodeSignature(Bytes address); - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionRequestExtension.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionRequestExtension.java new file mode 100644 index 00000000..ec6b1122 --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionRequestExtension.java @@ -0,0 +1,115 @@ +package com.jd.blockchain.ledger.core; + +import java.util.Collection; +import java.util.Set; + +import com.jd.blockchain.crypto.PubKey; +import com.jd.blockchain.ledger.BlockchainIdentity; +import com.jd.blockchain.ledger.BlockchainIdentityData; +import com.jd.blockchain.ledger.DigitalSignature; +import com.jd.blockchain.ledger.TransactionRequest; +import com.jd.blockchain.utils.Bytes; + +/** + * 交易请求上下文; + * + * @author huanghaiquan + * + */ +public interface TransactionRequestExtension extends TransactionRequest { + +// /** +// * 交易请求; +// * +// * @return +// */ +// TransactionRequest getRequest(); + + /** + * 签名发起请求的终端用户的地址列表; + * + * @return + */ + Set getEndpointAddresses(); + + /** + * 签名发起请求的终端用户列表; + * + * @return + */ + Collection getEndpoints(); + + /** + * 签名发起请求的节点的地址列表; + * + * @return + */ + Set getNodeAddresses(); + + /** + * 签名发起请求的节点列表; + * + * @return + */ + Collection getNodes(); + + /** + * 请求的终端发起人列表中是否包含指定地址的终端用户; + * + * @param address + * @return + */ + boolean containsEndpoint(Bytes address); + + /** + * 请求的经手节点列表中是否包含指定地址的节点; + * + * @param address + * @return + */ + boolean containsNode(Bytes address); + + /** + * 获取交易请求中指定地址的终端的签名; + * + * @param address + * @return + */ + DigitalSignature getEndpointSignature(Bytes address); + + /** + * 获取交易请求中指定地址的节点的签名; + * + * @param address + * @return + */ + DigitalSignature getNodeSignature(Bytes address); + + public static class Credential { + + private final BlockchainIdentity identity; + + private final DigitalSignature signature; + + Credential(DigitalSignature signature) { + this.identity = new BlockchainIdentityData(signature.getPubKey()); + this.signature = signature; + } + + public Bytes getAddress() { + return identity.getAddress(); + } + + public PubKey getPubKey() { + return identity.getPubKey(); + } + + public BlockchainIdentity getIdentity() { + return identity; + } + + public DigitalSignature getSignature() { + return signature; + } + } +} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionRequestExtensionImpl.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionRequestExtensionImpl.java new file mode 100644 index 00000000..1d93fbbe --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionRequestExtensionImpl.java @@ -0,0 +1,108 @@ +package com.jd.blockchain.ledger.core; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.ledger.DigitalSignature; +import com.jd.blockchain.ledger.TransactionContent; +import com.jd.blockchain.ledger.TransactionRequest; +import com.jd.blockchain.utils.Bytes; + +/** + * 交易请求的扩展信息; + * + * @author huanghaiquan + * + */ +public class TransactionRequestExtensionImpl implements TransactionRequestExtension { + + private TransactionRequest request; + + private Map endpointSignatures = new HashMap<>(); + + private Map nodeSignatures = new HashMap<>(); + + public TransactionRequestExtensionImpl(TransactionRequest request) { + this.request = request; + resolveSigners(); + } + + private void resolveSigners() { + if (request.getEndpointSignatures() != null) { + for (DigitalSignature signature : request.getEndpointSignatures()) { + Credential cred = new Credential(signature); + endpointSignatures.put(cred.getIdentity().getAddress(), cred); + } + } + if (request.getEndpointSignatures() != null) { + for (DigitalSignature signature : request.getNodeSignatures()) { + Credential cred = new Credential(signature); + nodeSignatures.put(cred.getIdentity().getAddress(), cred); + } + } + } + + @Override + public Set getEndpointAddresses() { + return endpointSignatures.keySet(); + } + + @Override + public Set getNodeAddresses() { + return nodeSignatures.keySet(); + } + + @Override + public Collection getEndpoints() { + return endpointSignatures.values(); + } + + @Override + public Collection getNodes() { + return nodeSignatures.values(); + } + + @Override + public boolean containsEndpoint(Bytes address) { + return endpointSignatures.containsKey(address); + } + + @Override + public boolean containsNode(Bytes address) { + return nodeSignatures.containsKey(address); + } + + @Override + public DigitalSignature getEndpointSignature(Bytes address) { + return endpointSignatures.get(address).getSignature(); + } + + @Override + public DigitalSignature getNodeSignature(Bytes address) { + return nodeSignatures.get(address).getSignature(); + } + + @Override + public HashDigest getHash() { + return request.getHash(); + } + + @Override + public DigitalSignature[] getNodeSignatures() { + return request.getNodeSignatures(); + } + + @Override + public DigitalSignature[] getEndpointSignatures() { + return request.getEndpointSignatures(); + } + + @Override + public TransactionContent getTransactionContent() { + return request.getTransactionContent(); + } + +} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionSet.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionSet.java index 962244e5..24cb6416 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionSet.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionSet.java @@ -6,6 +6,7 @@ import com.jd.blockchain.crypto.HashDigest; import com.jd.blockchain.ledger.CryptoSetting; import com.jd.blockchain.ledger.LedgerException; import com.jd.blockchain.ledger.LedgerTransaction; +import com.jd.blockchain.ledger.MerkleProof; import com.jd.blockchain.ledger.TransactionState; import com.jd.blockchain.storage.service.ExPolicyKVStorage; import com.jd.blockchain.storage.service.VersioningKVStorage; @@ -153,6 +154,10 @@ public class TransactionSet implements Transactional, MerkleProvable { public boolean isReadonly() { return txSet.isReadonly(); } + + void setReadonly() { + txSet.setReadonly(); + } @Override public boolean isUpdated() { diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/TransactionStagedSnapshot.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionStagedSnapshot.java similarity index 96% rename from source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/TransactionStagedSnapshot.java rename to source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionStagedSnapshot.java index 14d8e8a4..cee5487f 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/TransactionStagedSnapshot.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/TransactionStagedSnapshot.java @@ -1,4 +1,4 @@ -package com.jd.blockchain.ledger.core.impl; +package com.jd.blockchain.ledger.core; import com.jd.blockchain.crypto.HashDigest; import com.jd.blockchain.ledger.LedgerDataSnapshot; diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserAccountQuery.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserAccountQuery.java new file mode 100644 index 00000000..3d920b5c --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserAccountQuery.java @@ -0,0 +1,31 @@ +package com.jd.blockchain.ledger.core; + +import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.ledger.AccountHeader; +import com.jd.blockchain.ledger.MerkleProof; +import com.jd.blockchain.utils.Bytes; + +public interface UserAccountQuery { + + AccountHeader[] getAccounts(int fromIndex, int count); + + /** + * 返回用户总数; + * + * @return + */ + long getTotalCount(); + + HashDigest getRootHash(); + + MerkleProof getProof(Bytes key); + + UserAccount getUser(String address); + + UserAccount getUser(Bytes address); + + boolean contains(Bytes address); + + UserAccount getUser(Bytes address, long version); + +} \ 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 d28c15ed..f1e8bbc3 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 @@ -5,6 +5,7 @@ import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.ledger.AccountHeader; 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; @@ -14,7 +15,7 @@ import com.jd.blockchain.utils.Transactional; * @author huanghaiquan * */ -public class UserAccountSet implements Transactional, MerkleProvable { +public class UserAccountSet implements Transactional, MerkleProvable, UserAccountQuery { private AccountSet accountSet; @@ -30,6 +31,7 @@ public class UserAccountSet implements Transactional, MerkleProvable { accessPolicy); } + @Override public AccountHeader[] getAccounts(int fromIndex, int count) { return accountSet.getAccounts(fromIndex,count); } @@ -39,6 +41,7 @@ public class UserAccountSet implements Transactional, MerkleProvable { * * @return */ + @Override public long getTotalCount() { return accountSet.getTotalCount(); } @@ -46,6 +49,10 @@ public class UserAccountSet implements Transactional, MerkleProvable { public boolean isReadonly() { return accountSet.isReadonly(); } + + void setReadonly() { + accountSet.setReadonly(); + } @Override public HashDigest getRootHash() { @@ -57,19 +64,23 @@ public class UserAccountSet implements Transactional, MerkleProvable { return accountSet.getProof(key); } + @Override public UserAccount getUser(String address) { return getUser(Bytes.fromBase58(address)); } + @Override public UserAccount getUser(Bytes address) { BaseAccount baseAccount = accountSet.getAccount(address); return new UserAccount(baseAccount); } + @Override public boolean contains(Bytes address) { return accountSet.contains(address); } + @Override public UserAccount getUser(Bytes address, long version) { BaseAccount baseAccount = accountSet.getAccount(address, version); return new UserAccount(baseAccount); diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserRoleDataset.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserRoleDataset.java new file mode 100644 index 00000000..2f4eb514 --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserRoleDataset.java @@ -0,0 +1,196 @@ +package com.jd.blockchain.ledger.core; + +import java.util.Collection; + +import com.jd.blockchain.binaryproto.BinaryProtocol; +import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.ledger.AuthorizationException; +import com.jd.blockchain.ledger.CryptoSetting; +import com.jd.blockchain.ledger.LedgerException; +import com.jd.blockchain.ledger.MerkleProof; +import com.jd.blockchain.ledger.RoleSet; +import com.jd.blockchain.ledger.RolesPolicy; +import com.jd.blockchain.ledger.UserRoles; +import com.jd.blockchain.ledger.UserRolesSettings; +import com.jd.blockchain.storage.service.ExPolicyKVStorage; +import com.jd.blockchain.storage.service.VersioningKVEntry; +import com.jd.blockchain.storage.service.VersioningKVStorage; +import com.jd.blockchain.utils.Bytes; +import com.jd.blockchain.utils.Transactional; + +/** + * User-Role authorization data set; + * + * @author huanghaiquan + * + */ +public class UserRoleDataset implements Transactional, MerkleProvable, UserRolesSettings { + + private MerkleDataSet dataset; + + public UserRoleDataset(CryptoSetting cryptoSetting, String prefix, ExPolicyKVStorage exPolicyStorage, + VersioningKVStorage verStorage) { + dataset = new MerkleDataSet(cryptoSetting, prefix, exPolicyStorage, verStorage); + } + + public UserRoleDataset(HashDigest merkleRootHash, CryptoSetting cryptoSetting, String prefix, + ExPolicyKVStorage exPolicyStorage, VersioningKVStorage verStorage, boolean readonly) { + dataset = new MerkleDataSet(merkleRootHash, cryptoSetting, prefix, exPolicyStorage, verStorage, readonly); + } + + @Override + public HashDigest getRootHash() { + return dataset.getRootHash(); + } + + @Override + public MerkleProof getProof(Bytes key) { + return dataset.getProof(key); + } + + @Override + public boolean isUpdated() { + return dataset.isUpdated(); + } + + @Override + public void commit() { + dataset.commit(); + } + + @Override + public void cancel() { + dataset.cancel(); + } + + @Override + public long getUserCount() { + return dataset.getDataCount(); + } + + /** + * 加入新的用户角色授权;
+ * + * 如果该用户的授权已经存在,则引发 {@link LedgerException} 异常; + * + * @param userAddress + * @param rolesPolicy + * @param roles + */ + @Override + public void addUserRoles(Bytes userAddress, RolesPolicy rolesPolicy, String... roles) { + UserRoles roleAuth = new UserRoles(userAddress, -1, rolesPolicy); + roleAuth.addRoles(roles); + long nv = setUserRolesAuthorization(roleAuth); + if (nv < 0) { + throw new AuthorizationException("Roles authorization of User[" + userAddress + "] already exists!"); + } + } + + /** + * 加入新的用户角色授权;
+ * + * 如果该用户的授权已经存在,则引发 {@link LedgerException} 异常; + * + * @param userAddress + * @param rolesPolicy + * @param roles + */ + @Override + public void addUserRoles(Bytes userAddress, RolesPolicy rolesPolicy, Collection roles) { + UserRoles roleAuth = new UserRoles(userAddress, -1, rolesPolicy); + roleAuth.addRoles(roles); + long nv = setUserRolesAuthorization(roleAuth); + if (nv < 0) { + throw new AuthorizationException("Roles authorization of User[" + userAddress + "] already exists!"); + } + } + + /** + * 设置用户角色授权;
+ * 如果版本校验不匹配,则返回 -1; + * + * @param userRoles + * @return + */ + private long setUserRolesAuthorization(UserRoles userRoles) { + if (userRoles.getRoleCount() > MAX_ROLES_PER_USER) { + throw new AuthorizationException("The number of roles exceeds the maximum range!"); + } + byte[] rolesetBytes = BinaryProtocol.encode(userRoles, RoleSet.class); + return dataset.setValue(userRoles.getUserAddress(), rolesetBytes, userRoles.getVersion()); + } + + /** + * 更新用户角色授权;
+ * 如果指定用户的授权不存在,或者版本不匹配,则引发 {@link LedgerException} 异常; + * + * @param userRoles + */ + @Override + public void updateUserRoles(UserRoles userRoles) { + long nv = setUserRolesAuthorization(userRoles); + if (nv < 0) { + throw new AuthorizationException("Update to roles of user[" + userRoles.getUserAddress() + + "] failed due to wrong version[" + userRoles.getVersion() + "] !"); + } + } + + /** + * 设置用户的角色;
+ * 如果用户的角色授权不存在,则创建新的授权; + * + * @param userAddress 用户; + * @param policy 角色策略; + * @param roles 角色列表; + * @return + */ + @Override + public long setRoles(Bytes userAddress, RolesPolicy policy, String... roles) { + UserRoles userRoles = getUserRoles(userAddress); + if (userRoles == null) { + userRoles = new UserRoles(userAddress, -1, policy); + } + userRoles.setPolicy(policy); + userRoles.setRoles(roles); + return setUserRolesAuthorization(userRoles); + } + + /** + * 查询角色授权; + * + *
+ * 如果不存在,则返回 null; + * + * @param address + * @return + */ + @Override + public UserRoles getUserRoles(Bytes userAddress) { + // 只返回最新版本; + VersioningKVEntry kv = dataset.getDataEntry(userAddress); + if (kv == null) { + return null; + } + RoleSet roleSet = BinaryProtocol.decode(kv.getValue()); + return new UserRoles(userAddress, kv.getVersion(), roleSet); + } + + @Override + public UserRoles[] getUserRoles() { + VersioningKVEntry[] kvEntries = dataset.getLatestDataEntries(0, (int) dataset.getDataCount()); + UserRoles[] pns = new UserRoles[kvEntries.length]; + RoleSet roleset; + for (int i = 0; i < pns.length; i++) { + roleset = BinaryProtocol.decode(kvEntries[i].getValue()); + pns[i] = new UserRoles(kvEntries[i].getKey(), kvEntries[i].getVersion(), roleset); + } + return pns; + } + + @Override + public boolean isReadonly() { + return dataset.isReadonly(); + } + +} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserRolesPrivileges.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserRolesPrivileges.java new file mode 100644 index 00000000..4a626c70 --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/UserRolesPrivileges.java @@ -0,0 +1,63 @@ +package com.jd.blockchain.ledger.core; + +import java.util.Collection; + +import com.jd.blockchain.ledger.LedgerPermission; +import com.jd.blockchain.ledger.LedgerPrivilege; +import com.jd.blockchain.ledger.PrivilegeBitset; +import com.jd.blockchain.ledger.RolePrivileges; +import com.jd.blockchain.ledger.RolesPolicy; +import com.jd.blockchain.ledger.TransactionPermission; +import com.jd.blockchain.ledger.TransactionPrivilege; +import com.jd.blockchain.utils.Bytes; + +/** + * {@link UserRolesPrivileges} 表示多角色用户的综合权限; + * + * @author huanghaiquan + * + */ +class UserRolesPrivileges { + + private Bytes userAddress; + + private PrivilegeBitset ledgerPrivileges; + + private PrivilegeBitset transactionPrivileges; + + public UserRolesPrivileges(Bytes userAddress, RolesPolicy policy, Collection privilegesList) { + this.userAddress = userAddress; + LedgerPrivilege[] ledgerPrivileges = privilegesList.stream().map(p -> p.getLedgerPrivilege()) + .toArray(LedgerPrivilege[]::new); + TransactionPrivilege[] transactionPrivileges = privilegesList.stream().map(p -> p.getTransactionPrivilege()) + .toArray(TransactionPrivilege[]::new); + + this.ledgerPrivileges = ledgerPrivileges[0].clone(); + this.transactionPrivileges = transactionPrivileges[0].clone(); + + if (policy == RolesPolicy.UNION) { + this.ledgerPrivileges.union(ledgerPrivileges, 1, ledgerPrivileges.length - 1); + this.transactionPrivileges.union(transactionPrivileges, 1, transactionPrivileges.length - 1); + + } else if (policy == RolesPolicy.INTERSECT) { + this.ledgerPrivileges.intersect(ledgerPrivileges, 1, ledgerPrivileges.length - 1); + this.transactionPrivileges.intersect(transactionPrivileges, 1, transactionPrivileges.length - 1); + } else { + throw new IllegalStateException("Unsupported roles policy[" + policy.toString() + "]!"); + } + + } + + public Bytes getUserAddress() { + return userAddress; + } + + public PrivilegeBitset getLedgerPrivileges() { + return ledgerPrivileges; + } + + public PrivilegeBitset getTransactionPrivileges() { + return transactionPrivileges; + } + +} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/AbstractLedgerOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/AbstractLedgerOperationHandle.java new file mode 100644 index 00000000..36a2a0ae --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/AbstractLedgerOperationHandle.java @@ -0,0 +1,73 @@ +package com.jd.blockchain.ledger.core.handles; + +import com.jd.blockchain.binaryproto.DataContractRegistry; +import com.jd.blockchain.ledger.BytesValue; +import com.jd.blockchain.ledger.Operation; +import com.jd.blockchain.ledger.TransactionPermission; +import com.jd.blockchain.ledger.core.LedgerDataQuery; +import com.jd.blockchain.ledger.core.LedgerDataset; +import com.jd.blockchain.ledger.core.LedgerService; +import com.jd.blockchain.ledger.core.MultiIDsPolicy; +import com.jd.blockchain.ledger.core.OperationHandle; +import com.jd.blockchain.ledger.core.OperationHandleContext; +import com.jd.blockchain.ledger.core.SecurityContext; +import com.jd.blockchain.ledger.core.SecurityPolicy; +import com.jd.blockchain.ledger.core.TransactionRequestExtension; + +/** + * 执行直接账本操作的处理类; + * + * @author huanghaiquan + * + * @param + */ +public abstract class AbstractLedgerOperationHandle implements OperationHandle { + + static { + DataContractRegistry.register(BytesValue.class); + } + + private final Class SUPPORTED_OPERATION_TYPE; + + public AbstractLedgerOperationHandle(Class supportedOperationType) { + this.SUPPORTED_OPERATION_TYPE = supportedOperationType; + } + +// @Override +// public final boolean support(Class operationType) { +// return SUPPORTED_OPERATION_TYPE.isAssignableFrom(operationType); +// } + + @Override + public Class getOperationType() { + return SUPPORTED_OPERATION_TYPE; + } + + @Override + public final BytesValue process(Operation op, LedgerDataset newBlockDataset, + TransactionRequestExtension requestContext, LedgerDataQuery previousBlockDataset, + OperationHandleContext handleContext, LedgerService ledgerService) { + // 权限校验; + SecurityPolicy securityPolicy = SecurityContext.getContextUsersPolicy(); + securityPolicy.checkEndpointPermission(TransactionPermission.DIRECT_OPERATION, MultiIDsPolicy.AT_LEAST_ONE); + + // 操作账本; + @SuppressWarnings("unchecked") + T concretedOp = (T) op; + doProcess(concretedOp, newBlockDataset, requestContext, previousBlockDataset, handleContext, ledgerService); + + // 账本操作没有返回值; + return null; + } + + /** + * @param op + * @param newBlockDataset + * @param requestContext + * @param previousBlockDataset + * @param handleContext + * @param ledgerService + */ + protected abstract void doProcess(T op, LedgerDataset newBlockDataset, TransactionRequestExtension requestContext, + LedgerDataQuery previousBlockDataset, OperationHandleContext handleContext, LedgerService ledgerService); +} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/handles/AbtractContractEventHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/AbtractContractEventSendOperationHandle.java similarity index 54% rename from source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/handles/AbtractContractEventHandle.java rename to source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/AbtractContractEventSendOperationHandle.java index 40f6e2c2..af1d95b4 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/handles/AbtractContractEventHandle.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/AbtractContractEventSendOperationHandle.java @@ -1,4 +1,4 @@ -package com.jd.blockchain.ledger.core.impl.handles; +package com.jd.blockchain.ledger.core.handles; import org.springframework.stereotype.Service; @@ -8,30 +8,48 @@ import com.jd.blockchain.ledger.BytesValue; import com.jd.blockchain.ledger.ContractEventSendOperation; import com.jd.blockchain.ledger.LedgerException; import com.jd.blockchain.ledger.Operation; +import com.jd.blockchain.ledger.TransactionPermission; import com.jd.blockchain.ledger.core.ContractAccount; -import com.jd.blockchain.ledger.core.ContractAccountSet; -import com.jd.blockchain.ledger.core.LedgerDataSet; +import com.jd.blockchain.ledger.core.ContractAccountQuery; +import com.jd.blockchain.ledger.core.LedgerDataQuery; +import com.jd.blockchain.ledger.core.LedgerDataset; +import com.jd.blockchain.ledger.core.LedgerQueryService; import com.jd.blockchain.ledger.core.LedgerService; +import com.jd.blockchain.ledger.core.MultiIDsPolicy; import com.jd.blockchain.ledger.core.OperationHandle; -import com.jd.blockchain.ledger.core.TransactionRequestContext; -import com.jd.blockchain.ledger.core.impl.LedgerQueryService; -import com.jd.blockchain.ledger.core.impl.OperationHandleContext; +import com.jd.blockchain.ledger.core.OperationHandleContext; +import com.jd.blockchain.ledger.core.SecurityContext; +import com.jd.blockchain.ledger.core.SecurityPolicy; +import com.jd.blockchain.ledger.core.TransactionRequestExtension; @Service -public abstract class AbtractContractEventHandle implements OperationHandle { - +public abstract class AbtractContractEventSendOperationHandle implements OperationHandle { + @Override - public boolean support(Class operationType) { - return ContractEventSendOperation.class.isAssignableFrom(operationType); + public Class getOperationType() { + return ContractEventSendOperation.class; } @Override - public BytesValue process(Operation op, LedgerDataSet dataset, TransactionRequestContext requestContext, - LedgerDataSet previousBlockDataset, OperationHandleContext opHandleContext, LedgerService ledgerService) { + public BytesValue process(Operation op, LedgerDataset newBlockDataset, TransactionRequestExtension requestContext, + LedgerDataQuery previousBlockDataset, OperationHandleContext opHandleContext, LedgerService ledgerService) { + // 权限校验; + SecurityPolicy securityPolicy = SecurityContext.getContextUsersPolicy(); + securityPolicy.checkEndpointPermission(TransactionPermission.CONTRACT_OPERATION, MultiIDsPolicy.AT_LEAST_ONE); + + // 操作账本; ContractEventSendOperation contractOP = (ContractEventSendOperation) op; + + return doProcess(requestContext, contractOP, newBlockDataset, previousBlockDataset, opHandleContext, + ledgerService); + } + + private BytesValue doProcess(TransactionRequestExtension request, ContractEventSendOperation contractOP, + LedgerDataset newBlockDataset, LedgerDataQuery previousBlockDataset, OperationHandleContext opHandleContext, + LedgerService ledgerService) { // 先从账本校验合约的有效性; // 注意:必须在前一个区块的数据集中进行校验,因为那是经过共识的数据;从当前新区块链数据集校验则会带来攻击风险:未经共识的合约得到执行; - ContractAccountSet contractSet = previousBlockDataset.getContractAccountSet(); + ContractAccountQuery contractSet = previousBlockDataset.getContractAccountset(); if (!contractSet.contains(contractOP.getContractAddress())) { throw new LedgerException(String.format("Contract was not registered! --[ContractAddress=%s]", contractOP.getContractAddress())); @@ -50,19 +68,17 @@ public abstract class AbtractContractEventHandle implements OperationHandle { // 创建合约上下文; LocalContractEventContext localContractEventContext = new LocalContractEventContext( - requestContext.getRequest().getTransactionContent().getLedgerHash(), contractOP.getEvent()); - localContractEventContext.setArgs(contractOP.getArgs()).setTransactionRequest(requestContext.getRequest()) + request.getTransactionContent().getLedgerHash(), contractOP.getEvent()); + localContractEventContext.setArgs(contractOP.getArgs()).setTransactionRequest(request) .setLedgerContext(ledgerContext); - // 装载合约; ContractCode contractCode = loadContractCode(contract); // 处理合约事件; return contractCode.processEvent(localContractEventContext); } - - protected abstract ContractCode loadContractCode(ContractAccount contract); + protected abstract ContractCode loadContractCode(ContractAccount contract); } diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/ContractCodeDeployOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/ContractCodeDeployOperationHandle.java new file mode 100644 index 00000000..e054a1e2 --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/ContractCodeDeployOperationHandle.java @@ -0,0 +1,37 @@ +package com.jd.blockchain.ledger.core.handles; + +import com.jd.blockchain.ledger.ContractCodeDeployOperation; +import com.jd.blockchain.ledger.LedgerPermission; +import com.jd.blockchain.ledger.core.LedgerDataQuery; +import com.jd.blockchain.ledger.core.LedgerDataset; +import com.jd.blockchain.ledger.core.LedgerService; +import com.jd.blockchain.ledger.core.MultiIDsPolicy; +import com.jd.blockchain.ledger.core.OperationHandleContext; +import com.jd.blockchain.ledger.core.SecurityContext; +import com.jd.blockchain.ledger.core.SecurityPolicy; +import com.jd.blockchain.ledger.core.TransactionRequestExtension; + +public class ContractCodeDeployOperationHandle extends AbstractLedgerOperationHandle { + public ContractCodeDeployOperationHandle() { + super(ContractCodeDeployOperation.class); + } + + @Override + protected void doProcess(ContractCodeDeployOperation op, LedgerDataset newBlockDataset, + TransactionRequestExtension requestContext, LedgerDataQuery previousBlockDataset, + OperationHandleContext handleContext, LedgerService ledgerService) { + // TODO: 校验合约代码的正确性; + + // TODO: 请求者应该提供合约账户的公钥签名,以确保注册人对注册的地址和公钥具有合法的使用权; + + // 权限校验; + SecurityPolicy securityPolicy = SecurityContext.getContextUsersPolicy(); + securityPolicy.checkEndpointPermission(LedgerPermission.UPGRADE_CONTRACT, MultiIDsPolicy.AT_LEAST_ONE); + + // 操作账本; + ContractCodeDeployOperation contractOP = (ContractCodeDeployOperation) op; + newBlockDataset.getContractAccountset().deploy(contractOP.getContractID().getAddress(), + contractOP.getContractID().getPubKey(), contractOP.getAddressSignature(), contractOP.getChainCode()); + } + +} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/handles/ContractLedgerContext.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/ContractLedgerContext.java similarity index 97% rename from source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/handles/ContractLedgerContext.java rename to source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/ContractLedgerContext.java index 5a673722..0d0d3c3d 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/handles/ContractLedgerContext.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/ContractLedgerContext.java @@ -1,4 +1,4 @@ -package com.jd.blockchain.ledger.core.impl.handles; +package com.jd.blockchain.ledger.core.handles; import java.util.ArrayList; import java.util.List; @@ -6,7 +6,7 @@ import java.util.List; import com.jd.blockchain.contract.LedgerContext; import com.jd.blockchain.crypto.HashDigest; import com.jd.blockchain.ledger.*; -import com.jd.blockchain.ledger.core.impl.OperationHandleContext; +import com.jd.blockchain.ledger.core.OperationHandleContext; import com.jd.blockchain.transaction.BlockchainQueryService; import com.jd.blockchain.transaction.DataAccountKVSetOperationBuilder; import com.jd.blockchain.transaction.DataAccountRegisterOperationBuilder; @@ -38,6 +38,11 @@ public class ContractLedgerContext implements LedgerContext { public LedgerInfo getLedger(HashDigest ledgerHash) { return innerQueryService.getLedger(ledgerHash); } + + @Override + public LedgerAdminInfo getLedgerAdminInfo(HashDigest ledgerHash) { + return innerQueryService.getLedgerAdminInfo(ledgerHash); + } @Override public ParticipantNode[] getConsensusParticipants(HashDigest ledgerHash) { diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/DataAccountKVSetOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/DataAccountKVSetOperationHandle.java new file mode 100644 index 00000000..6661a6d5 --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/DataAccountKVSetOperationHandle.java @@ -0,0 +1,47 @@ +package com.jd.blockchain.ledger.core.handles; + +import com.jd.blockchain.ledger.DataAccountDoesNotExistException; +import com.jd.blockchain.ledger.DataAccountKVSetOperation; +import com.jd.blockchain.ledger.DataAccountKVSetOperation.KVWriteEntry; +import com.jd.blockchain.ledger.DataVersionConflictException; +import com.jd.blockchain.ledger.LedgerPermission; +import com.jd.blockchain.ledger.core.DataAccount; +import com.jd.blockchain.ledger.core.LedgerDataQuery; +import com.jd.blockchain.ledger.core.LedgerDataset; +import com.jd.blockchain.ledger.core.LedgerService; +import com.jd.blockchain.ledger.core.MultiIDsPolicy; +import com.jd.blockchain.ledger.core.OperationHandleContext; +import com.jd.blockchain.ledger.core.SecurityContext; +import com.jd.blockchain.ledger.core.SecurityPolicy; +import com.jd.blockchain.ledger.core.TransactionRequestExtension; +import com.jd.blockchain.utils.Bytes; + +public class DataAccountKVSetOperationHandle extends AbstractLedgerOperationHandle { + public DataAccountKVSetOperationHandle() { + super(DataAccountKVSetOperation.class); + } + + @Override + protected void doProcess(DataAccountKVSetOperation kvWriteOp, LedgerDataset newBlockDataset, + TransactionRequestExtension requestContext, LedgerDataQuery previousBlockDataset, + OperationHandleContext handleContext, LedgerService ledgerService) { + // 权限校验; + SecurityPolicy securityPolicy = SecurityContext.getContextUsersPolicy(); + securityPolicy.checkEndpointPermission(LedgerPermission.WRITE_DATA_ACCOUNT, MultiIDsPolicy.AT_LEAST_ONE); + + // 操作账本; + DataAccount account = newBlockDataset.getDataAccountSet().getDataAccount(kvWriteOp.getAccountAddress()); + if (account == null) { + throw new DataAccountDoesNotExistException("DataAccount doesn't exist!"); + } + KVWriteEntry[] writeSet = kvWriteOp.getWriteSet(); + long v = -1; + for (KVWriteEntry kvw : writeSet) { + v = account.setBytes(Bytes.fromString(kvw.getKey()), kvw.getValue(), kvw.getExpectedVersion()); + if (v < 0) { + throw new DataVersionConflictException(); + } + } + } + +} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/DataAccountRegisterOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/DataAccountRegisterOperationHandle.java new file mode 100644 index 00000000..0c031d5d --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/DataAccountRegisterOperationHandle.java @@ -0,0 +1,36 @@ +package com.jd.blockchain.ledger.core.handles; + +import com.jd.blockchain.ledger.BlockchainIdentity; +import com.jd.blockchain.ledger.DataAccountRegisterOperation; +import com.jd.blockchain.ledger.LedgerPermission; +import com.jd.blockchain.ledger.core.LedgerDataQuery; +import com.jd.blockchain.ledger.core.LedgerDataset; +import com.jd.blockchain.ledger.core.LedgerService; +import com.jd.blockchain.ledger.core.MultiIDsPolicy; +import com.jd.blockchain.ledger.core.OperationHandleContext; +import com.jd.blockchain.ledger.core.SecurityContext; +import com.jd.blockchain.ledger.core.SecurityPolicy; +import com.jd.blockchain.ledger.core.TransactionRequestExtension; + +public class DataAccountRegisterOperationHandle extends AbstractLedgerOperationHandle { + public DataAccountRegisterOperationHandle() { + super(DataAccountRegisterOperation.class); + } + + @Override + protected void doProcess(DataAccountRegisterOperation op, LedgerDataset newBlockDataset, + TransactionRequestExtension requestContext, LedgerDataQuery previousBlockDataset, + OperationHandleContext handleContext, LedgerService ledgerService) { + // TODO: 请求者应该提供数据账户的公钥签名,以更好地确保注册人对该地址和公钥具有合法使用权; + + // 权限校验; + SecurityPolicy securityPolicy = SecurityContext.getContextUsersPolicy(); + securityPolicy.checkEndpointPermission(LedgerPermission.REGISTER_DATA_ACCOUNT, MultiIDsPolicy.AT_LEAST_ONE); + + // 操作账本; + DataAccountRegisterOperation dataAccountRegOp = (DataAccountRegisterOperation) op; + BlockchainIdentity bid = dataAccountRegOp.getAccountID(); + newBlockDataset.getDataAccountSet().register(bid.getAddress(), bid.getPubKey(), null); + } + +} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/handles/JVMContractEventSendOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/JVMContractEventSendOperationHandle.java similarity index 70% rename from source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/handles/JVMContractEventSendOperationHandle.java rename to source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/JVMContractEventSendOperationHandle.java index da4da430..1cdd3fe6 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/handles/JVMContractEventSendOperationHandle.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/JVMContractEventSendOperationHandle.java @@ -1,13 +1,13 @@ -package com.jd.blockchain.ledger.core.impl.handles; +package com.jd.blockchain.ledger.core.handles; + +import static com.jd.blockchain.utils.BaseConstant.CONTRACT_SERVICE_PROVIDER; import com.jd.blockchain.contract.engine.ContractCode; import com.jd.blockchain.contract.engine.ContractEngine; import com.jd.blockchain.contract.engine.ContractServiceProviders; import com.jd.blockchain.ledger.core.ContractAccount; -import static com.jd.blockchain.utils.BaseConstant.CONTRACT_SERVICE_PROVIDER; - -public class JVMContractEventSendOperationHandle extends AbtractContractEventHandle { +public class JVMContractEventSendOperationHandle extends AbtractContractEventSendOperationHandle { private static final ContractEngine JVM_ENGINE; @@ -26,12 +26,4 @@ public class JVMContractEventSendOperationHandle extends AbtractContractEventHan return contractCode; } -// @Override -// public AsyncFuture asyncProcess(Operation op, LedgerDataSet newBlockDataset, -// TransactionRequestContext requestContext, LedgerDataSet previousBlockDataset, -// OperationHandleContext handleContext, LedgerService ledgerService) { -// // TODO Auto-generated method stub -// return null; -// } - } diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/LedgerInitOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/LedgerInitOperationHandle.java new file mode 100644 index 00000000..39862be0 --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/LedgerInitOperationHandle.java @@ -0,0 +1,27 @@ +package com.jd.blockchain.ledger.core.handles; + +import com.jd.blockchain.ledger.BytesValue; +import com.jd.blockchain.ledger.LedgerInitOperation; +import com.jd.blockchain.ledger.Operation; +import com.jd.blockchain.ledger.core.LedgerDataQuery; +import com.jd.blockchain.ledger.core.LedgerDataset; +import com.jd.blockchain.ledger.core.LedgerService; +import com.jd.blockchain.ledger.core.OperationHandle; +import com.jd.blockchain.ledger.core.OperationHandleContext; +import com.jd.blockchain.ledger.core.TransactionRequestExtension; + +public class LedgerInitOperationHandle implements OperationHandle { + + @Override + public Class getOperationType() { + return LedgerInitOperation.class; + } + + @Override + public BytesValue process(Operation op, LedgerDataset newBlockDataset, TransactionRequestExtension requestContext, + LedgerDataQuery previousBlockDataset, OperationHandleContext handleContext, LedgerService ledgerService) { + // 对初始化操作不需要做任何处理; + return null; + } + +} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/handles/ParticipantRegisterOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/ParticipantRegisterOperationHandle.java similarity index 100% rename from source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/handles/ParticipantRegisterOperationHandle.java rename to source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/ParticipantRegisterOperationHandle.java diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/handles/ParticipantStateUpdateOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/ParticipantStateUpdateOperationHandle.java similarity index 100% rename from source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/handles/ParticipantStateUpdateOperationHandle.java rename to source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/ParticipantStateUpdateOperationHandle.java diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/RolesConfigureOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/RolesConfigureOperationHandle.java new file mode 100644 index 00000000..3ae02b4e --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/RolesConfigureOperationHandle.java @@ -0,0 +1,50 @@ +package com.jd.blockchain.ledger.core.handles; + +import com.jd.blockchain.ledger.LedgerPermission; +import com.jd.blockchain.ledger.RolePrivilegeSettings; +import com.jd.blockchain.ledger.RolePrivileges; +import com.jd.blockchain.ledger.RolesConfigureOperation; +import com.jd.blockchain.ledger.RolesConfigureOperation.RolePrivilegeEntry; +import com.jd.blockchain.ledger.core.LedgerDataQuery; +import com.jd.blockchain.ledger.core.LedgerDataset; +import com.jd.blockchain.ledger.core.LedgerService; +import com.jd.blockchain.ledger.core.MultiIDsPolicy; +import com.jd.blockchain.ledger.core.OperationHandleContext; +import com.jd.blockchain.ledger.core.SecurityContext; +import com.jd.blockchain.ledger.core.SecurityPolicy; +import com.jd.blockchain.ledger.core.TransactionRequestExtension; + +public class RolesConfigureOperationHandle extends AbstractLedgerOperationHandle { + public RolesConfigureOperationHandle() { + super(RolesConfigureOperation.class); + } + + @Override + protected void doProcess(RolesConfigureOperation operation, LedgerDataset newBlockDataset, + TransactionRequestExtension request, LedgerDataQuery previousBlockDataset, + OperationHandleContext handleContext, LedgerService ledgerService) { + // 权限校验; + SecurityPolicy securityPolicy = SecurityContext.getContextUsersPolicy(); + securityPolicy.checkEndpointPermission(LedgerPermission.CONFIGURE_ROLES, MultiIDsPolicy.AT_LEAST_ONE); + + // 操作账本; + RolePrivilegeEntry[] rpcfgs = operation.getRoles(); + RolePrivilegeSettings rpSettings = newBlockDataset.getAdminDataset().getRolePrivileges(); + if (rpcfgs != null) { + for (RolePrivilegeEntry rpcfg : rpcfgs) { + RolePrivileges rp = rpSettings.getRolePrivilege(rpcfg.getRoleName()); + if (rp == null) { + rpSettings.addRolePrivilege(rpcfg.getRoleName(), rpcfg.getEnableLedgerPermissions(), + rpcfg.getEnableTransactionPermissions()); + } else { + rp.enable(rpcfg.getEnableLedgerPermissions()); + rp.enable(rpcfg.getEnableTransactionPermissions()); + + rp.disable(rpcfg.getDisableLedgerPermissions()); + rp.disable(rpcfg.getDisableTransactionPermissions()); + } + } + } + } + +} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/UserAuthorizeOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/UserAuthorizeOperationHandle.java new file mode 100644 index 00000000..b9d3614d --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/UserAuthorizeOperationHandle.java @@ -0,0 +1,78 @@ +package com.jd.blockchain.ledger.core.handles; + +import java.util.ArrayList; +import java.util.List; + +import com.jd.blockchain.ledger.LedgerPermission; +import com.jd.blockchain.ledger.RolePrivilegeSettings; +import com.jd.blockchain.ledger.RolesPolicy; +import com.jd.blockchain.ledger.UserAuthorizeOperation; +import com.jd.blockchain.ledger.UserAuthorizeOperation.UserRolesEntry; +import com.jd.blockchain.ledger.UserRoles; +import com.jd.blockchain.ledger.UserRolesSettings; +import com.jd.blockchain.ledger.core.LedgerDataQuery; +import com.jd.blockchain.ledger.core.LedgerDataset; +import com.jd.blockchain.ledger.core.LedgerService; +import com.jd.blockchain.ledger.core.MultiIDsPolicy; +import com.jd.blockchain.ledger.core.OperationHandleContext; +import com.jd.blockchain.ledger.core.SecurityContext; +import com.jd.blockchain.ledger.core.SecurityPolicy; +import com.jd.blockchain.ledger.core.TransactionRequestExtension; +import com.jd.blockchain.utils.Bytes; + +public class UserAuthorizeOperationHandle extends AbstractLedgerOperationHandle { + public UserAuthorizeOperationHandle() { + super(UserAuthorizeOperation.class); + } + + @Override + protected void doProcess(UserAuthorizeOperation operation, LedgerDataset newBlockDataset, + TransactionRequestExtension request, LedgerDataQuery previousBlockDataset, + OperationHandleContext handleContext, LedgerService ledgerService) { + // 权限校验; + SecurityPolicy securityPolicy = SecurityContext.getContextUsersPolicy(); + securityPolicy.checkEndpointPermission(LedgerPermission.CONFIGURE_ROLES, MultiIDsPolicy.AT_LEAST_ONE); + + // 操作账本; + + UserRolesEntry[] urcfgs = operation.getUserRolesAuthorizations(); + UserRolesSettings urSettings = newBlockDataset.getAdminDataset().getUserRoles(); + RolePrivilegeSettings rolesSettings = newBlockDataset.getAdminDataset().getRolePrivileges(); + if (urcfgs != null) { + for (UserRolesEntry urcfg : urcfgs) { + // + String[] authRoles = urcfg.getAuthorizedRoles(); + List validRoles = new ArrayList(); + if (authRoles != null) { + for (String r : authRoles) { + if (rolesSettings.contains(r)) { + validRoles.add(r); + } + } + } + for (Bytes address : urcfg.getUserAddresses()) { + UserRoles ur = urSettings.getUserRoles(address); + if (ur == null) { + // 这是新的授权; + RolesPolicy policy = urcfg.getPolicy(); + if (policy == null) { + policy = RolesPolicy.UNION; + } + urSettings.addUserRoles(address, policy, validRoles); + } else { + // 更改之前的授权; + ur.addRoles(validRoles); + ur.removeRoles(urcfg.getUnauthorizedRoles()); + + // 如果请求中设置了策略,才进行更新; + RolesPolicy policy = urcfg.getPolicy(); + if (policy != null) { + ur.setPolicy(policy); + } + } + } + } + } + } + +} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/UserRegisterOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/UserRegisterOperationHandle.java new file mode 100644 index 00000000..3b8f043d --- /dev/null +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/handles/UserRegisterOperationHandle.java @@ -0,0 +1,38 @@ +package com.jd.blockchain.ledger.core.handles; + +import com.jd.blockchain.ledger.BlockchainIdentity; +import com.jd.blockchain.ledger.LedgerPermission; +import com.jd.blockchain.ledger.UserRegisterOperation; +import com.jd.blockchain.ledger.core.LedgerDataQuery; +import com.jd.blockchain.ledger.core.LedgerDataset; +import com.jd.blockchain.ledger.core.LedgerService; +import com.jd.blockchain.ledger.core.MultiIDsPolicy; +import com.jd.blockchain.ledger.core.OperationHandleContext; +import com.jd.blockchain.ledger.core.SecurityContext; +import com.jd.blockchain.ledger.core.SecurityPolicy; +import com.jd.blockchain.ledger.core.TransactionRequestExtension; +import com.jd.blockchain.utils.Bytes; + +public class UserRegisterOperationHandle extends AbstractLedgerOperationHandle { + public UserRegisterOperationHandle() { + super(UserRegisterOperation.class); + } + + @Override + protected void doProcess(UserRegisterOperation op, LedgerDataset newBlockDataset, + TransactionRequestExtension requestContext, LedgerDataQuery previousBlockDataset, + OperationHandleContext handleContext, LedgerService ledgerService) { + // 权限校验; + SecurityPolicy securityPolicy = SecurityContext.getContextUsersPolicy(); + securityPolicy.checkEndpointPermission(LedgerPermission.REGISTER_USER, MultiIDsPolicy.AT_LEAST_ONE); + + // 操作账本; + UserRegisterOperation userRegOp = (UserRegisterOperation) op; + BlockchainIdentity bid = userRegOp.getUserID(); + + Bytes userAddress = bid.getAddress(); + + newBlockDataset.getUserAccountSet().register(userAddress, bid.getPubKey()); + } + +} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerTransactionContextImpl.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerTransactionContextImpl.java deleted file mode 100644 index c8c09d93..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/LedgerTransactionContextImpl.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jd.blockchain.ledger.core.impl; - -import com.jd.blockchain.ledger.TransactionState; -import com.jd.blockchain.ledger.LedgerTransaction; -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.ledger.core.LedgerDataSet; -import com.jd.blockchain.ledger.core.LedgerTransactionContext; -import com.jd.blockchain.storage.service.utils.BufferedKVStorage; - diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/OperationHandleContext.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/OperationHandleContext.java deleted file mode 100644 index 6e702e0b..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/OperationHandleContext.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jd.blockchain.ledger.core.impl; - -import com.jd.blockchain.ledger.Operation; - -public interface OperationHandleContext { - - void handle(Operation operation); - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/OperationHandleRegisteration.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/OperationHandleRegisteration.java deleted file mode 100644 index 169c5249..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/OperationHandleRegisteration.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.jd.blockchain.ledger.core.impl; - -import com.jd.blockchain.ledger.core.OperationHandle; - -public interface OperationHandleRegisteration { - - OperationHandle getHandle(Class operationType); - -} \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/TransactionRequestContextImpl.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/TransactionRequestContextImpl.java deleted file mode 100644 index ec53360a..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/TransactionRequestContextImpl.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.jd.blockchain.ledger.core.impl; - -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.ledger.DigitalSignature; -import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.ledger.core.TransactionRequestContext; -import com.jd.blockchain.utils.Bytes; - -/** - * @Author zhaogw - * @Date 2018/9/5 14:52 - */ -public class TransactionRequestContextImpl implements TransactionRequestContext { - - private TransactionRequest request; - - private Map endpointSignatures = new HashMap<>(); - - private Map nodeSignatures = new HashMap<>(); - - public TransactionRequestContextImpl(TransactionRequest request) { - this.request = request; - resolveSigners(); - } - - private void resolveSigners() { - if (request.getEndpointSignatures() != null) { - for (DigitalSignature signature : request.getEndpointSignatures()) { - Bytes address = AddressEncoding.generateAddress(signature.getPubKey()); - endpointSignatures.put(address, signature); - } - } - if (request.getEndpointSignatures() != null) { - for (DigitalSignature signature : request.getNodeSignatures()) { - Bytes address = AddressEncoding.generateAddress(signature.getPubKey()); - nodeSignatures.put(address, signature); - } - } - } - - @Override - public TransactionRequest getRequest() { - return request; - } - - @Override - public Set getEndpoints() { - return endpointSignatures.keySet(); - } - - @Override - public Set getNodes() { - return nodeSignatures.keySet(); - } - - @Override - public boolean containsEndpoint(Bytes address) { - return endpointSignatures.containsKey(address); - } - - @Override - public boolean containsNode(Bytes address) { - return nodeSignatures.containsKey(address); - } - - @Override - public DigitalSignature getEndpointSignature(Bytes address) { - return endpointSignatures.get(address); - } - - @Override - public DigitalSignature getNodeSignature(Bytes address) { - return nodeSignatures.get(address); - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/handles/ContractCodeDeployOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/handles/ContractCodeDeployOperationHandle.java deleted file mode 100644 index e18c9304..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/handles/ContractCodeDeployOperationHandle.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.jd.blockchain.ledger.core.impl.handles; - -import org.springframework.stereotype.Service; - -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.ContractCodeDeployOperation; -import com.jd.blockchain.ledger.Operation; -import com.jd.blockchain.ledger.core.LedgerDataSet; -import com.jd.blockchain.ledger.core.LedgerService; -import com.jd.blockchain.ledger.core.OperationHandle; -import com.jd.blockchain.ledger.core.TransactionRequestContext; -import com.jd.blockchain.ledger.core.impl.OperationHandleContext; - -@Service -public class ContractCodeDeployOperationHandle implements OperationHandle { - - @Override - public BytesValue process(Operation op, LedgerDataSet dataset, TransactionRequestContext requestContext, - LedgerDataSet previousBlockDataset, OperationHandleContext handleContext, LedgerService ledgerService) { - ContractCodeDeployOperation contractOP = (ContractCodeDeployOperation) op; - // TODO: 校验合约代码的正确性; - - // TODO: 请求者应该提供合约账户的公钥签名,已确定注册的地址的唯一性; - - dataset.getContractAccountSet().deploy(contractOP.getContractID().getAddress(), - contractOP.getContractID().getPubKey(), contractOP.getAddressSignature(), contractOP.getChainCode()); - - return null; - } - -// @Override -// public AsyncFuture asyncProcess(Operation op, LedgerDataSet newBlockDataset, TransactionRequestContext requestContext, LedgerDataSet previousBlockDataset, OperationHandleContext handleContext, LedgerService ledgerService) { -// return null; -// } - - @Override - public boolean support(Class operationType) { - return ContractCodeDeployOperation.class.isAssignableFrom(operationType); - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/handles/DataAccountKVSetOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/handles/DataAccountKVSetOperationHandle.java deleted file mode 100644 index 75607b51..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/handles/DataAccountKVSetOperationHandle.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.jd.blockchain.ledger.core.impl.handles; - -import org.springframework.stereotype.Service; - -import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.DataAccountDoesNotExistException; -import com.jd.blockchain.ledger.DataAccountKVSetOperation; -import com.jd.blockchain.ledger.DataAccountKVSetOperation.KVWriteEntry; -import com.jd.blockchain.ledger.DataVersionConflictException; -import com.jd.blockchain.ledger.Operation; -import com.jd.blockchain.ledger.core.DataAccount; -import com.jd.blockchain.ledger.core.LedgerDataSet; -import com.jd.blockchain.ledger.core.LedgerService; -import com.jd.blockchain.ledger.core.OperationHandle; -import com.jd.blockchain.ledger.core.TransactionRequestContext; -import com.jd.blockchain.ledger.core.impl.OperationHandleContext; -import com.jd.blockchain.utils.Bytes; - -@Service -public class DataAccountKVSetOperationHandle implements OperationHandle { - static { - DataContractRegistry.register(BytesValue.class); - } - - @Override - public BytesValue process(Operation op, LedgerDataSet dataset, TransactionRequestContext requestContext, - LedgerDataSet previousBlockDataset, OperationHandleContext handleContext, LedgerService ledgerService) { - DataAccountKVSetOperation kvWriteOp = (DataAccountKVSetOperation) op; - DataAccount account = dataset.getDataAccountSet().getDataAccount(kvWriteOp.getAccountAddress()); - if (account == null) { - throw new DataAccountDoesNotExistException("DataAccount doesn't exist!"); - } - KVWriteEntry[] writeSet = kvWriteOp.getWriteSet(); - long v = -1; - for (KVWriteEntry kvw : writeSet) { - v = account.setBytes(Bytes.fromString(kvw.getKey()), kvw.getValue(), kvw.getExpectedVersion()); - if (v < 0) { - throw new DataVersionConflictException(); - } - } - return null; - } - -// @Override -// public AsyncFuture asyncProcess(Operation op, LedgerDataSet newBlockDataset, TransactionRequestContext requestContext, LedgerDataSet previousBlockDataset, OperationHandleContext handleContext, LedgerService ledgerService) { -// return null; -// } - - @Override - public boolean support(Class operationType) { - return DataAccountKVSetOperation.class.isAssignableFrom(operationType); - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/handles/DataAccountRegisterOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/handles/DataAccountRegisterOperationHandle.java deleted file mode 100644 index 69337dfa..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/handles/DataAccountRegisterOperationHandle.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.jd.blockchain.ledger.core.impl.handles; - -import org.springframework.stereotype.Service; - -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.DataAccountRegisterOperation; -import com.jd.blockchain.ledger.Operation; -import com.jd.blockchain.ledger.core.LedgerDataSet; -import com.jd.blockchain.ledger.core.LedgerService; -import com.jd.blockchain.ledger.core.OperationHandle; -import com.jd.blockchain.ledger.core.TransactionRequestContext; -import com.jd.blockchain.ledger.core.impl.OperationHandleContext; - -@Service -public class DataAccountRegisterOperationHandle implements OperationHandle { - - @Override - public BytesValue process(Operation op, LedgerDataSet dataset, TransactionRequestContext requestContext, - LedgerDataSet previousBlockDataset, OperationHandleContext handleContext, LedgerService ledgerService) { - DataAccountRegisterOperation dataAccountRegOp = (DataAccountRegisterOperation) op; - BlockchainIdentity bid = dataAccountRegOp.getAccountID(); - - //TODO: 校验用户身份; - - //TODO: 请求者应该提供数据账户的公钥签名,已确定注册的地址的唯一性; - dataset.getDataAccountSet().register(bid.getAddress(), bid.getPubKey(), null); - - return null; - } - -// @Override -// public AsyncFuture asyncProcess(Operation op, LedgerDataSet newBlockDataset, TransactionRequestContext requestContext, LedgerDataSet previousBlockDataset, OperationHandleContext handleContext, LedgerService ledgerService) { -// return null; -// } - - @Override - public boolean support(Class operationType) { - return DataAccountRegisterOperation.class.isAssignableFrom(operationType); - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/handles/UserRegisterOperationHandle.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/handles/UserRegisterOperationHandle.java deleted file mode 100644 index f583e8cd..00000000 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/impl/handles/UserRegisterOperationHandle.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.jd.blockchain.ledger.core.impl.handles; - -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.BytesValue; -import com.jd.blockchain.ledger.Operation; -import com.jd.blockchain.ledger.UserRegisterOperation; -import com.jd.blockchain.ledger.core.LedgerDataSet; -import com.jd.blockchain.ledger.core.LedgerService; -import com.jd.blockchain.ledger.core.OperationHandle; -import com.jd.blockchain.ledger.core.TransactionRequestContext; -import com.jd.blockchain.ledger.core.impl.OperationHandleContext; -import com.jd.blockchain.utils.Bytes; - - -public class UserRegisterOperationHandle implements OperationHandle { - - @Override - public BytesValue process(Operation op, LedgerDataSet dataset, TransactionRequestContext requestContext, - LedgerDataSet previousBlockDataset, OperationHandleContext handleContext, LedgerService ledgerService) { - - - UserRegisterOperation userRegOp = (UserRegisterOperation) op; - BlockchainIdentity bid = userRegOp.getUserID(); - - Bytes userAddress = bid.getAddress(); - - dataset.getUserAccountSet().register(userAddress, bid.getPubKey()); - - return null; - } - - @Override - public boolean support(Class operationType) { - return UserRegisterOperation.class.isAssignableFrom(operationType); - } - -} diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/serialize/LedgerBlockSerializer.java b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/serialize/LedgerBlockSerializer.java index 65b15129..09cedf9d 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/serialize/LedgerBlockSerializer.java +++ b/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/serialize/LedgerBlockSerializer.java @@ -1,13 +1,12 @@ package com.jd.blockchain.ledger.core.serialize; +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; import com.jd.blockchain.ledger.LedgerBlock; -import java.lang.reflect.Type; - public class LedgerBlockSerializer implements ObjectSerializer { @Override diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerAdminAccountTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerAdminAccountTest.java deleted file mode 100644 index 1293a9d8..00000000 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerAdminAccountTest.java +++ /dev/null @@ -1,221 +0,0 @@ -package test.com.jd.blockchain.ledger; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.Arrays; -import java.util.Random; - -import com.jd.blockchain.ledger.LedgerMetadata; -import org.junit.Test; - -import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.CryptoProvider; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; -import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; -import com.jd.blockchain.crypto.service.sm.SMCryptoService; -import com.jd.blockchain.ledger.BlockchainKeyGenerator; -import com.jd.blockchain.ledger.BlockchainKeypair; -import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.LedgerAdminAccount; -import com.jd.blockchain.ledger.core.LedgerConfiguration; -import com.jd.blockchain.storage.service.utils.MemoryKVStorage; -import com.jd.blockchain.transaction.ConsensusParticipantData; -import com.jd.blockchain.transaction.LedgerInitSettingData; -import com.jd.blockchain.utils.Bytes; -import com.jd.blockchain.utils.io.BytesUtils; -import com.jd.blockchain.utils.net.NetworkAddress; - -public class LedgerAdminAccountTest { - - private static final String[] SUPPORTED_PROVIDERS = { ClassicCryptoService.class.getName(), - SMCryptoService.class.getName() }; - - private Random rand = new Random(); - - @Test - public void test() { - String keyPrefix = ""; - LedgerInitSettingData initSetting = new LedgerInitSettingData(); - ConsensusParticipantData[] parties = new ConsensusParticipantData[5]; - BlockchainKeypair[] bckeys = new BlockchainKeypair[parties.length]; - for (int i = 0; i < parties.length; i++) { - bckeys[i] = BlockchainKeyGenerator.getInstance().generate(); - parties[i] = new ConsensusParticipantData(); - parties[i].setId(i); - parties[i].setAddress(AddressEncoding.generateAddress(bckeys[i].getPubKey()).toBase58()); - parties[i].setHostAddress(new NetworkAddress("192.168.10." + (10 + i), 10010 + 10 * i)); - parties[i].setName("Participant[" + i + "]"); - parties[i].setPubKey(bckeys[i].getPubKey()); - } - ConsensusParticipantData[] parties1 = Arrays.copyOf(parties, 4); - initSetting.setConsensusParticipants(parties1); - - byte[] csSysSettingBytes = new byte[64]; - rand.nextBytes(csSysSettingBytes); - initSetting.setConsensusSettings(new Bytes(csSysSettingBytes)); - initSetting.setConsensusProvider("consensus-provider"); - - CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length]; - for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) { - supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]); - } - - CryptoConfig cryptoSetting = new CryptoConfig(); - cryptoSetting.setSupportedProviders(supportedProviders); - cryptoSetting.setAutoVerifyHash(true); - cryptoSetting.setHashAlgorithm(ClassicAlgorithm.SHA256); - initSetting.setCryptoSetting(cryptoSetting); - - byte[] ledgerSeed = new byte[16]; - rand.nextBytes(ledgerSeed); - initSetting.setLedgerSeed(ledgerSeed); - - MemoryKVStorage testStorage = new MemoryKVStorage(); - - // Create intance with init setting; - LedgerAdminAccount ledgerAdminAccount = new LedgerAdminAccount(initSetting, keyPrefix, testStorage, - testStorage); - - // New created instance is updated until being committed; - assertTrue(ledgerAdminAccount.isUpdated()); - // Hash of account is null until being committed; - assertNull(ledgerAdminAccount.getHash()); - - LedgerMetadata meta = ledgerAdminAccount.getMetadata(); - assertNull(meta.getParticipantsHash()); - - // Commit, and check the storage keys; - ledgerAdminAccount.commit(); - - // New created instance isn't updated after being committed; - assertFalse(ledgerAdminAccount.isUpdated()); - // Hash of account isn't null after being committed; - assertNotNull(ledgerAdminAccount.getHash()); - - meta = ledgerAdminAccount.getMetadata(); - assertNotNull(meta.getParticipantsHash()); - - // ---------------------- - // Reload account from storage with readonly mode, and check the integrity of - // data; - HashDigest adminAccHash = ledgerAdminAccount.getHash(); - LedgerAdminAccount reloadAdminAccount = new LedgerAdminAccount(adminAccHash, keyPrefix, testStorage, - testStorage, true); - - // verify realod settings of admin account; - verifyRealoadingSettings(reloadAdminAccount, adminAccHash, ledgerAdminAccount.getMetadata()); - - // verify the consensus participant list; - verifyReadlingParities(reloadAdminAccount, parties1); - - // It will throw exeception because of this account is readonly; - verifyReadonlyState(reloadAdminAccount); - - // -------------- - // reload again with writing mode; - reloadAdminAccount = new LedgerAdminAccount(adminAccHash, keyPrefix, testStorage, testStorage, false); - LedgerConfiguration newSetting = new LedgerConfiguration(reloadAdminAccount.getPreviousSetting()); - byte[] newCsSettingBytes = new byte[64]; - rand.nextBytes(newCsSettingBytes); - newSetting.setConsensusSetting(new Bytes(newCsSettingBytes)); - newSetting.getCryptoSetting().setAutoVerifyHash(false); - reloadAdminAccount.setLedgerSetting(newSetting); - - reloadAdminAccount.addParticipant(parties[4]); - reloadAdminAccount.commit(); - - // record the new account hash; - HashDigest newAccHash = reloadAdminAccount.getHash(); - LedgerMetadata newMeta = reloadAdminAccount.getMetadata(); - - // load the last version of account and verify again; - reloadAdminAccount = new LedgerAdminAccount(adminAccHash, keyPrefix, testStorage, testStorage, true); - verifyRealoadingSettings(reloadAdminAccount, adminAccHash, ledgerAdminAccount.getMetadata()); - verifyReadlingParities(reloadAdminAccount, parties1); - verifyReadonlyState(reloadAdminAccount); - - // load the hash of new committing; - reloadAdminAccount = new LedgerAdminAccount(newAccHash, keyPrefix, testStorage, testStorage, true); - verifyRealoadingSettings(reloadAdminAccount, newAccHash, newMeta); - verifyReadlingParities(reloadAdminAccount, parties); - verifyReadonlyState(reloadAdminAccount); - - // System.out.println("========= [LedgerAdminAccount Test] Show generated - // storage keys... ======="); - // testStorage.printStoragedKeys(); - } - - private void verifyRealoadingSettings(LedgerAdminAccount actualAccount, HashDigest expHash, - LedgerMetadata expMeta) { - // 验证基本信息; - assertFalse(actualAccount.isUpdated()); - assertTrue(actualAccount.isReadonly()); - - assertEquals(expHash, actualAccount.getHash()); - - // verify metadata; - LedgerMetadata rlmeta = actualAccount.getMetadata(); - assertEquals(expMeta.getParticipantsHash(), rlmeta.getParticipantsHash()); - - assertTrue(BytesUtils.equals(expMeta.getSeed(), rlmeta.getSeed())); - - assertNotNull(rlmeta.getSetting()); - assertTrue(expMeta.getSetting().getConsensusSetting().equals(rlmeta.getSetting().getConsensusSetting())); - assertEquals(expMeta.getSetting().getConsensusProvider(), rlmeta.getSetting().getConsensusProvider()); - - assertEquals(expMeta.getSetting().getCryptoSetting().getAutoVerifyHash(), - rlmeta.getSetting().getCryptoSetting().getAutoVerifyHash()); - assertEquals(expMeta.getSetting().getCryptoSetting().getHashAlgorithm(), - rlmeta.getSetting().getCryptoSetting().getHashAlgorithm()); - } - - private void verifyReadlingParities(LedgerAdminAccount actualAccount, ParticipantNode[] expParties) { - assertEquals(expParties.length, actualAccount.getParticipantCount()); - ParticipantNode[] actualPaticipants = actualAccount.getParticipants(); - assertEquals(expParties.length, actualPaticipants.length); - for (int i = 0; i < actualPaticipants.length; i++) { - ParticipantNode rlParti = actualPaticipants[i]; - assertEquals(expParties[i].getAddress(), rlParti.getAddress()); - assertEquals(expParties[i].getName(), rlParti.getName()); - // assertEquals(expParties[i].getConsensusAddress(), - // rlParti.getConsensusAddress()); - assertEquals(expParties[i].getPubKey(), rlParti.getPubKey()); - } - } - - private void verifyReadonlyState(LedgerAdminAccount actualAccount) { - ConsensusParticipantData newParti = new ConsensusParticipantData(); - newParti.setId((int) actualAccount.getParticipantCount()); - newParti.setHostAddress( - new NetworkAddress("192.168.10." + (10 + newParti.getAddress()), 10010 + 10 * newParti.getId())); - newParti.setName("Participant[" + newParti.getAddress() + "]"); - - BlockchainKeypair newKey = BlockchainKeyGenerator.getInstance().generate(); - newParti.setPubKey(newKey.getPubKey()); - - Throwable ex = null; - try { - actualAccount.addParticipant(newParti); - } catch (Exception e) { - ex = e; - } - assertNotNull(ex); - - ex = null; - try { - LedgerConfiguration newLedgerSetting = new LedgerConfiguration(actualAccount.getSetting()); - actualAccount.setLedgerSetting(newLedgerSetting); - } catch (Exception e) { - ex = e; - } - assertNotNull(ex); - } - -} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/AccountSetTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/AccountSetTest.java similarity index 96% rename from source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/AccountSetTest.java rename to source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/AccountSetTest.java index 5b69b118..d3e565a5 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/AccountSetTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/AccountSetTest.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger; +package test.com.jd.blockchain.ledger.core; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -17,7 +17,7 @@ import com.jd.blockchain.ledger.BlockchainKeypair; import com.jd.blockchain.ledger.core.AccountSet; import com.jd.blockchain.ledger.core.BaseAccount; import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.impl.OpeningAccessPolicy; +import com.jd.blockchain.ledger.core.OpeningAccessPolicy; import com.jd.blockchain.storage.service.utils.MemoryKVStorage; public class AccountSetTest { diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/BaseAccountTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/BaseAccountTest.java similarity index 98% rename from source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/BaseAccountTest.java rename to source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/BaseAccountTest.java index 4a641b7d..d02f9b11 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/BaseAccountTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/BaseAccountTest.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger; +package test.com.jd.blockchain.ledger.core; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/ContractInvokingHandle.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/ContractInvokingHandle.java similarity index 84% rename from source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/ContractInvokingHandle.java rename to source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/ContractInvokingHandle.java index ef354223..2bd98895 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/ContractInvokingHandle.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/ContractInvokingHandle.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger; +package test.com.jd.blockchain.ledger.core; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -6,10 +6,10 @@ import java.util.concurrent.ConcurrentHashMap; import com.jd.blockchain.contract.engine.ContractCode; import com.jd.blockchain.contract.jvm.InstantiatedContractCode; import com.jd.blockchain.ledger.core.ContractAccount; -import com.jd.blockchain.ledger.core.impl.handles.AbtractContractEventHandle; +import com.jd.blockchain.ledger.core.handles.AbtractContractEventSendOperationHandle; import com.jd.blockchain.utils.Bytes; -public class ContractInvokingHandle extends AbtractContractEventHandle { +public class ContractInvokingHandle extends AbtractContractEventSendOperationHandle { private Map contractInstances = new ConcurrentHashMap(); diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/ContractInvokingTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/ContractInvokingTest.java similarity index 82% rename from source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/ContractInvokingTest.java rename to source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/ContractInvokingTest.java index 2753761e..c05c3f1b 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/ContractInvokingTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/ContractInvokingTest.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger; +package test.com.jd.blockchain.ledger.core; import static com.jd.blockchain.transaction.ContractReturnValue.decode; import static org.junit.Assert.assertArrayEquals; @@ -6,6 +6,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.times; @@ -14,30 +15,56 @@ import static org.mockito.Mockito.when; import java.util.Random; -import com.jd.blockchain.ledger.*; import org.junit.Test; import org.mockito.Mockito; import com.jd.blockchain.binaryproto.BinaryProtocol; import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.core.LedgerDataSet; +import com.jd.blockchain.ledger.BlockchainKeyGenerator; +import com.jd.blockchain.ledger.BlockchainKeypair; +import com.jd.blockchain.ledger.BytesData; +import com.jd.blockchain.ledger.BytesValue; +import com.jd.blockchain.ledger.DataAccountRegisterOperation; +import com.jd.blockchain.ledger.EndpointRequest; +import com.jd.blockchain.ledger.KVDataEntry; +import com.jd.blockchain.ledger.LedgerBlock; +import com.jd.blockchain.ledger.LedgerInitSetting; +import com.jd.blockchain.ledger.LedgerPermission; +import com.jd.blockchain.ledger.LedgerTransaction; +import com.jd.blockchain.ledger.NodeRequest; +import com.jd.blockchain.ledger.OperationResult; +import com.jd.blockchain.ledger.TransactionContent; +import com.jd.blockchain.ledger.TransactionContentBody; +import com.jd.blockchain.ledger.TransactionPermission; +import com.jd.blockchain.ledger.TransactionRequest; +import com.jd.blockchain.ledger.TransactionRequestBuilder; +import com.jd.blockchain.ledger.TransactionResponse; +import com.jd.blockchain.ledger.TransactionState; +import com.jd.blockchain.ledger.UserRegisterOperation; +import com.jd.blockchain.ledger.core.DefaultOperationHandleRegisteration; +import com.jd.blockchain.ledger.core.LedgerDataQuery; +import com.jd.blockchain.ledger.core.LedgerDataset; import com.jd.blockchain.ledger.core.LedgerEditor; +import com.jd.blockchain.ledger.core.LedgerManager; import com.jd.blockchain.ledger.core.LedgerRepository; +import com.jd.blockchain.ledger.core.LedgerSecurityManager; import com.jd.blockchain.ledger.core.LedgerService; import com.jd.blockchain.ledger.core.LedgerTransactionContext; +import com.jd.blockchain.ledger.core.LedgerTransactionalEditor; +import com.jd.blockchain.ledger.core.OperationHandleRegisteration; +import com.jd.blockchain.ledger.core.SecurityPolicy; +import com.jd.blockchain.ledger.core.TransactionBatchProcessor; import com.jd.blockchain.ledger.core.UserAccount; -import com.jd.blockchain.ledger.core.impl.DefaultOperationHandleRegisteration; -import com.jd.blockchain.ledger.core.impl.LedgerManager; -import com.jd.blockchain.ledger.core.impl.LedgerTransactionalEditor; -import com.jd.blockchain.ledger.core.impl.OperationHandleRegisteration; -import com.jd.blockchain.ledger.core.impl.TransactionBatchProcessor; import com.jd.blockchain.service.TransactionBatchResultHandle; import com.jd.blockchain.storage.service.utils.MemoryKVStorage; import com.jd.blockchain.transaction.BooleanValueHolder; import com.jd.blockchain.transaction.TxBuilder; import com.jd.blockchain.utils.Bytes; +import test.com.jd.blockchain.ledger.TxTestContract; +import test.com.jd.blockchain.ledger.TxTestContractImpl; + public class ContractInvokingTest { static { DataContractRegistry.register(TransactionContent.class); @@ -48,9 +75,6 @@ public class ContractInvokingTest { DataContractRegistry.register(TransactionResponse.class); DataContractRegistry.register(UserRegisterOperation.class); DataContractRegistry.register(DataAccountRegisterOperation.class); - DataContractRegistry.register(ParticipantRegisterOperation.class); - DataContractRegistry.register(ParticipantStateUpdateOperation.class); - } private static final String LEDGER_KEY_PREFIX = "LDG://"; @@ -78,33 +102,36 @@ public class ContractInvokingTest { // 创建和加载合约实例; BlockchainKeypair contractKey = BlockchainKeyGenerator.getInstance().generate(); Bytes contractAddress = contractKey.getAddress(); + TestContract contractInstance = Mockito.mock(TestContract.class); + final String asset = "AK"; + final long issueAmount = new Random().nextLong(); + when(contractInstance.issue(anyString(), anyLong())).thenReturn(issueAmount); + + // 装载合约; contractInvokingHandle.setup(contractAddress, TestContract.class, contractInstance); // 注册合约处理器; DefaultOperationHandleRegisteration opReg = new DefaultOperationHandleRegisteration(); - opReg.insertAsTopPriority(contractInvokingHandle); + opReg.registerHandle(contractInvokingHandle); // 发布指定地址合约 deploy(ledgerRepo, ledgerManager, opReg, ledgerHash, contractKey); - // 创建新区块的交易处理器; LedgerBlock preBlock = ledgerRepo.getLatestBlock(); - LedgerDataSet previousBlockDataset = ledgerRepo.getDataSet(preBlock); + LedgerDataQuery previousBlockDataset = ledgerRepo.getDataSet(preBlock); // 加载合约 LedgerEditor newBlockEditor = ledgerRepo.createNextBlock(); - TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(newBlockEditor, previousBlockDataset, - opReg, ledgerManager); + LedgerSecurityManager securityManager = getSecurityManager(); + TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(securityManager, newBlockEditor, + previousBlockDataset, opReg, ledgerManager); // 构建基于接口调用合约的交易请求,用于测试合约调用; TxBuilder txBuilder = new TxBuilder(ledgerHash); TestContract contractProxy = txBuilder.contract(contractAddress, TestContract.class); - TestContract contractProxy1 = txBuilder.contract(contractAddress, TestContract.class); - String asset = "AK"; - long issueAmount = new Random().nextLong(); - when(contractInstance.issue(anyString(), anyLong())).thenReturn(issueAmount); + // 构造调用合约的交易; contractProxy.issue(asset, issueAmount); TransactionRequestBuilder txReqBuilder = txBuilder.prepareRequest(); @@ -160,19 +187,19 @@ public class ContractInvokingTest { // 注册合约处理器; DefaultOperationHandleRegisteration opReg = new DefaultOperationHandleRegisteration(); - opReg.insertAsTopPriority(contractInvokingHandle); + opReg.registerHandle(contractInvokingHandle); // 发布指定地址合约 deploy(ledgerRepo, ledgerManager, opReg, ledgerHash, contractKey); // 创建新区块的交易处理器; LedgerBlock preBlock = ledgerRepo.getLatestBlock(); - LedgerDataSet previousBlockDataset = ledgerRepo.getDataSet(preBlock); + LedgerDataQuery previousBlockDataset = ledgerRepo.getDataSet(preBlock); // 加载合约 LedgerEditor newBlockEditor = ledgerRepo.createNextBlock(); - TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(newBlockEditor, previousBlockDataset, - opReg, ledgerManager); + TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(getSecurityManager(), newBlockEditor, + previousBlockDataset, opReg, ledgerManager); String key = TxTestContractImpl.KEY; String value = "VAL"; @@ -241,7 +268,7 @@ public class ContractInvokingTest { // 注册合约处理器; DefaultOperationHandleRegisteration opReg = new DefaultOperationHandleRegisteration(); - opReg.insertAsTopPriority(contractInvokingHandle); + opReg.registerHandle(contractInvokingHandle); // 发布指定地址合约 deploy(ledgerRepo, ledgerManager, opReg, ledgerHash, contractKey); @@ -291,7 +318,7 @@ public class ContractInvokingTest { assertEquals(1, kv2.getVersion()); assertEquals("V1-1", kv1.getValue()); assertEquals("V2-1", kv2.getValue()); - + // 构建基于接口调用合约的交易请求,用于测试合约调用; buildBlock(ledgerRepo, ledgerManager, opReg, new TxDefinitor() { @Override @@ -316,10 +343,10 @@ public class ContractInvokingTest { private LedgerBlock buildBlock(LedgerRepository ledgerRepo, LedgerService ledgerService, OperationHandleRegisteration opReg, TxDefinitor txDefinitor) { LedgerBlock preBlock = ledgerRepo.getLatestBlock(); - LedgerDataSet previousBlockDataset = ledgerRepo.getDataSet(preBlock); + LedgerDataQuery previousBlockDataset = ledgerRepo.getDataSet(preBlock); LedgerEditor newBlockEditor = ledgerRepo.createNextBlock(); - TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(newBlockEditor, previousBlockDataset, - opReg, ledgerService); + TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(getSecurityManager(), newBlockEditor, + previousBlockDataset, opReg, ledgerService); TxBuilder txBuilder = new TxBuilder(ledgerRepo.getHash()); txDefinitor.buildTx(txBuilder); @@ -349,12 +376,12 @@ public class ContractInvokingTest { private void registerDataAccount(LedgerRepository ledgerRepo, LedgerManager ledgerManager, DefaultOperationHandleRegisteration opReg, HashDigest ledgerHash, BlockchainKeypair kpDataAccount) { LedgerBlock preBlock = ledgerRepo.getLatestBlock(); - LedgerDataSet previousBlockDataset = ledgerRepo.getDataSet(preBlock); + LedgerDataQuery previousBlockDataset = ledgerRepo.getDataSet(preBlock); // 加载合约 LedgerEditor newBlockEditor = ledgerRepo.createNextBlock(); - TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(newBlockEditor, previousBlockDataset, - opReg, ledgerManager); + TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(getSecurityManager(), newBlockEditor, + previousBlockDataset, opReg, ledgerManager); // 注册数据账户; TxBuilder txBuilder = new TxBuilder(ledgerHash); @@ -379,12 +406,13 @@ public class ContractInvokingTest { DefaultOperationHandleRegisteration opReg, HashDigest ledgerHash, BlockchainKeypair contractKey) { // 创建新区块的交易处理器; LedgerBlock preBlock = ledgerRepo.getLatestBlock(); - LedgerDataSet previousBlockDataset = ledgerRepo.getDataSet(preBlock); + LedgerDataQuery previousBlockDataset = ledgerRepo.getDataSet(preBlock); // 加载合约 LedgerEditor newBlockEditor = ledgerRepo.createNextBlock(); - TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(newBlockEditor, previousBlockDataset, - opReg, ledgerManager); + LedgerSecurityManager securityManager = getSecurityManager(); + TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(securityManager, newBlockEditor, + previousBlockDataset, opReg, ledgerManager); // 构建基于接口调用合约的交易请求,用于测试合约调用; TxBuilder txBuilder = new TxBuilder(ledgerHash); @@ -412,7 +440,7 @@ public class ContractInvokingTest { TransactionRequest genesisTxReq = LedgerTestUtils.createLedgerInitTxRequest(partiKeys); LedgerTransactionContext genisisTxCtx = ldgEdt.newTransaction(genesisTxReq); - LedgerDataSet ldgDS = genisisTxCtx.getDataSet(); + LedgerDataset ldgDS = genisisTxCtx.getDataset(); for (int i = 0; i < partiKeys.length; i++) { UserAccount userAccount = ldgDS.getUserAccountSet().register(partiKeys[i].getAddress(), @@ -446,6 +474,20 @@ public class ContractInvokingTest { return chainCode; } + private static LedgerSecurityManager getSecurityManager() { + LedgerSecurityManager securityManager = Mockito.mock(LedgerSecurityManager.class); + + SecurityPolicy securityPolicy = Mockito.mock(SecurityPolicy.class); + when(securityPolicy.isEndpointEnable(any(LedgerPermission.class), any())).thenReturn(true); + when(securityPolicy.isEndpointEnable(any(TransactionPermission.class), any())).thenReturn(true); + when(securityPolicy.isNodeEnable(any(LedgerPermission.class), any())).thenReturn(true); + when(securityPolicy.isNodeEnable(any(TransactionPermission.class), any())).thenReturn(true); + + when(securityManager.createSecurityPolicy(any(), any())).thenReturn(securityPolicy); + + return securityManager; + } + public static interface TxDefinitor { void buildTx(TxBuilder txBuilder); diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerAccountTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerAccountTest.java similarity index 97% rename from source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerAccountTest.java rename to source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerAccountTest.java index 18566ca6..27dcc438 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerAccountTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerAccountTest.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger; +package test.com.jd.blockchain.ledger.core; import static org.junit.Assert.assertEquals; diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerAdminDatasetTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerAdminDatasetTest.java new file mode 100644 index 00000000..e591aa7f --- /dev/null +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerAdminDatasetTest.java @@ -0,0 +1,305 @@ +package test.com.jd.blockchain.ledger.core; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.Random; + +import org.junit.Test; + +import com.jd.blockchain.crypto.AddressEncoding; +import com.jd.blockchain.crypto.Crypto; +import com.jd.blockchain.crypto.CryptoProvider; +import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; +import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; +import com.jd.blockchain.crypto.service.sm.SMCryptoService; +import com.jd.blockchain.ledger.BlockchainKeyGenerator; +import com.jd.blockchain.ledger.BlockchainKeypair; +import com.jd.blockchain.ledger.LedgerAdminInfo; +import com.jd.blockchain.ledger.LedgerMetadata_V2; +import com.jd.blockchain.ledger.LedgerPermission; +import com.jd.blockchain.ledger.LedgerSettings; +import com.jd.blockchain.ledger.ParticipantNode; +import com.jd.blockchain.ledger.RolePrivilegeSettings; +import com.jd.blockchain.ledger.RolePrivileges; +import com.jd.blockchain.ledger.RolesPolicy; +import com.jd.blockchain.ledger.TransactionPermission; +import com.jd.blockchain.ledger.UserRolesSettings; +import com.jd.blockchain.ledger.UserRoles; +import com.jd.blockchain.ledger.core.CryptoConfig; +import com.jd.blockchain.ledger.core.LedgerAdminDataset; +import com.jd.blockchain.ledger.core.LedgerConfiguration; +import com.jd.blockchain.storage.service.utils.MemoryKVStorage; +import com.jd.blockchain.transaction.ConsensusParticipantData; +import com.jd.blockchain.transaction.LedgerInitData; +import com.jd.blockchain.utils.Bytes; +import com.jd.blockchain.utils.net.NetworkAddress; + +public class LedgerAdminDatasetTest { + + private static final String[] SUPPORTED_PROVIDERS = { ClassicCryptoService.class.getName(), + SMCryptoService.class.getName() }; + + private Random rand = new Random(); + + @Test + public void testSerialization() { + String keyPrefix = ""; + LedgerInitData initSetting = new LedgerInitData(); + ConsensusParticipantData[] parties = new ConsensusParticipantData[5]; + BlockchainKeypair[] bckeys = new BlockchainKeypair[parties.length]; + for (int i = 0; i < parties.length; i++) { + bckeys[i] = BlockchainKeyGenerator.getInstance().generate(); + parties[i] = new ConsensusParticipantData(); + parties[i].setId(i); + parties[i].setAddress(AddressEncoding.generateAddress(bckeys[i].getPubKey())); + parties[i].setHostAddress(new NetworkAddress("192.168.10." + (10 + i), 10010 + 10 * i)); + parties[i].setName("Participant[" + i + "]"); + parties[i].setPubKey(bckeys[i].getPubKey()); + } + ConsensusParticipantData[] parties1 = Arrays.copyOf(parties, 4); + initSetting.setConsensusParticipants(parties1); + + byte[] csSysSettingBytes = new byte[64]; + rand.nextBytes(csSysSettingBytes); + initSetting.setConsensusSettings(new Bytes(csSysSettingBytes)); + initSetting.setConsensusProvider("consensus-provider"); + + CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length]; + for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) { + supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]); + } + CryptoConfig cryptoSetting = new CryptoConfig(); + cryptoSetting.setSupportedProviders(supportedProviders); + cryptoSetting.setAutoVerifyHash(true); + cryptoSetting.setHashAlgorithm(ClassicAlgorithm.SHA256); + initSetting.setCryptoSetting(cryptoSetting); + + byte[] ledgerSeed = new byte[16]; + rand.nextBytes(ledgerSeed); + initSetting.setLedgerSeed(ledgerSeed); + + MemoryKVStorage testStorage = new MemoryKVStorage(); + + // Create intance with init setting; + LedgerAdminDataset ledgerAdminDataset = new LedgerAdminDataset(initSetting, keyPrefix, testStorage, + testStorage); + + ledgerAdminDataset.getRolePrivileges().addRolePrivilege("DEFAULT", + new LedgerPermission[] { LedgerPermission.CONFIGURE_ROLES, LedgerPermission.REGISTER_USER, + LedgerPermission.APPROVE_TX }, + new TransactionPermission[] { TransactionPermission.DIRECT_OPERATION, + TransactionPermission.CONTRACT_OPERATION }); + + ledgerAdminDataset.getUserRoles().addUserRoles(parties[0].getAddress(), RolesPolicy.UNION, "DEFAULT"); + + // New created instance is updated until being committed; + assertTrue(ledgerAdminDataset.isUpdated()); + // Hash of account is null until being committed; + assertNull(ledgerAdminDataset.getHash()); + + LedgerMetadata_V2 meta = ledgerAdminDataset.getMetadata(); + assertNull(meta.getParticipantsHash()); + + // Commit, and check the storage keys; + ledgerAdminDataset.commit(); + + // New created instance isn't updated after being committed; + assertFalse(ledgerAdminDataset.isUpdated()); + // Hash of account isn't null after being committed; + assertNotNull(ledgerAdminDataset.getHash()); + + meta = ledgerAdminDataset.getMetadata(); + assertNotNull(meta.getParticipantsHash()); + assertNotNull(meta.getSettingsHash()); + assertNotNull(meta.getRolePrivilegesHash()); + assertNotNull(meta.getUserRolesHash()); + + assertNotNull(ledgerAdminDataset.getRolePrivileges().getRolePrivilege("DEFAULT")); + + // ---------------------- + // Reload account from storage with readonly mode, and check the integrity of + // data; + HashDigest adminAccHash = ledgerAdminDataset.getHash(); + LedgerAdminDataset reloadAdminAccount1 = new LedgerAdminDataset(adminAccHash, keyPrefix, testStorage, + testStorage, true); + + LedgerMetadata_V2 meta2 = reloadAdminAccount1.getMetadata(); + assertNotNull(meta2.getParticipantsHash()); + assertNotNull(meta2.getSettingsHash()); + assertNotNull(meta2.getRolePrivilegesHash()); + assertNotNull(meta2.getUserRolesHash()); + + // verify realod settings of admin account; + verifyRealoadingSettings(reloadAdminAccount1, adminAccHash, ledgerAdminDataset.getMetadata(), + ledgerAdminDataset.getSettings()); + // verify the consensus participant list; + verifyRealoadingParities(reloadAdminAccount1, parties1); + // It will throw exeception because of this account is readonly; + verifyReadonlyState(reloadAdminAccount1); + + verifyRealoadingRoleAuthorizations(reloadAdminAccount1, ledgerAdminDataset.getRolePrivileges(), + ledgerAdminDataset.getUserRoles()); + + // -------------- + // 重新加载,并进行修改; + LedgerAdminDataset reloadAdminAccount2 = new LedgerAdminDataset(adminAccHash, keyPrefix, testStorage, testStorage, false); + LedgerConfiguration newSetting = new LedgerConfiguration(reloadAdminAccount2.getPreviousSetting()); + byte[] newCsSettingBytes = new byte[64]; + rand.nextBytes(newCsSettingBytes); + newSetting.setConsensusSetting(new Bytes(newCsSettingBytes)); + newSetting.getCryptoSetting().setAutoVerifyHash(false); + reloadAdminAccount2.setLedgerSetting(newSetting); + + reloadAdminAccount2.addParticipant(parties[4]); + + reloadAdminAccount2.getRolePrivileges().addRolePrivilege("ADMIN", + new LedgerPermission[] { LedgerPermission.APPROVE_TX }, + new TransactionPermission[] { TransactionPermission.DIRECT_OPERATION }); + + reloadAdminAccount2.getRolePrivileges().disablePermissions("DEFAULT", TransactionPermission.CONTRACT_OPERATION); + + reloadAdminAccount2.getUserRoles().addUserRoles(parties[1].getAddress(), RolesPolicy.UNION, "DEFAULT", "ADMIN"); + + reloadAdminAccount2.commit(); + + LedgerSettings newlyLedgerSettings = reloadAdminAccount2.getSettings(); + + // record the new account hash; + HashDigest newAccHash = reloadAdminAccount2.getHash(); + LedgerMetadata_V2 newMeta = reloadAdminAccount2.getMetadata(); + + // load the last version of account and verify again; + LedgerAdminDataset previousAdminAccount = new LedgerAdminDataset(adminAccHash, keyPrefix, testStorage, + testStorage, true); + verifyRealoadingSettings(previousAdminAccount, adminAccHash, ledgerAdminDataset.getMetadata(), + ledgerAdminDataset.getSettings()); + verifyRealoadingParities(previousAdminAccount, parties1); + verifyReadonlyState(previousAdminAccount); + + // load the hash of new committing; + LedgerAdminDataset newlyAdminAccount = new LedgerAdminDataset(newAccHash, keyPrefix, testStorage, testStorage, + true); + verifyRealoadingSettings(newlyAdminAccount, newAccHash, newMeta, newlyLedgerSettings); + verifyRealoadingParities(newlyAdminAccount, parties); + verifyReadonlyState(newlyAdminAccount); + +// System.out.println("========= [LedgerAdminAccount Test] Show generated storage keys... ======="); +// testStorage.printStoragedKeys(); + } + + private void verifyRealoadingSettings(LedgerAdminDataset actualAccount, HashDigest expAccRootHash, + LedgerMetadata_V2 expMeta, LedgerSettings expLedgerSettings) { + // 验证基本信息; + assertFalse(actualAccount.isUpdated()); + assertTrue(actualAccount.isReadonly()); + + assertEquals(expAccRootHash, actualAccount.getHash()); + + // verify metadata; + LedgerMetadata_V2 actualMeta = actualAccount.getMetadata(); + assertArrayEquals(expMeta.getSeed(), actualMeta.getSeed()); + assertEquals(expMeta.getParticipantsHash(), actualMeta.getParticipantsHash()); + assertNotNull(actualMeta.getSettingsHash()); + assertEquals(expMeta.getSettingsHash(), actualMeta.getSettingsHash()); + assertNotNull(actualMeta.getRolePrivilegesHash()); + assertEquals(expMeta.getRolePrivilegesHash(), actualMeta.getRolePrivilegesHash()); + assertNotNull(actualMeta.getUserRolesHash()); + assertEquals(expMeta.getUserRolesHash(), actualMeta.getUserRolesHash()); + + LedgerSettings actualLedgerSettings = actualAccount.getSettings(); + + assertEquals(expLedgerSettings.getConsensusSetting(), actualLedgerSettings.getConsensusSetting()); + assertEquals(expLedgerSettings.getConsensusProvider(), actualLedgerSettings.getConsensusProvider()); + + assertEquals(expLedgerSettings.getCryptoSetting().getAutoVerifyHash(), + actualLedgerSettings.getCryptoSetting().getAutoVerifyHash()); + assertEquals(expLedgerSettings.getCryptoSetting().getHashAlgorithm(), + actualLedgerSettings.getCryptoSetting().getHashAlgorithm()); + } + + private void verifyRealoadingRoleAuthorizations(LedgerAdminInfo actualAccount, + RolePrivilegeSettings expRolePrivilegeSettings, UserRolesSettings expUserRoleSettings) { + // 验证基本信息; + RolePrivilegeSettings actualRolePrivileges = actualAccount.getRolePrivileges(); + RolePrivileges[] expRPs = expRolePrivilegeSettings.getRolePrivileges(); + + assertEquals(expRPs.length, actualRolePrivileges.getRoleCount()); + + for (RolePrivileges expRP : expRPs) { + RolePrivileges actualRP = actualRolePrivileges.getRolePrivilege(expRP.getRoleName()); + assertNotNull(actualRP); + assertArrayEquals(expRP.getLedgerPrivilege().toBytes(), actualRP.getLedgerPrivilege().toBytes()); + assertArrayEquals(expRP.getTransactionPrivilege().toBytes(), actualRP.getTransactionPrivilege().toBytes()); + } + + UserRolesSettings actualUserRoleSettings = actualAccount.getUserRoles(); + UserRoles[] expUserRoles = expUserRoleSettings.getUserRoles(); + assertEquals(expUserRoles.length, actualUserRoleSettings.getUserCount()); + + for (UserRoles expUR : expUserRoles) { + UserRoles actualUR = actualAccount.getUserRoles().getUserRoles(expUR.getUserAddress()); + assertNotNull(actualUR); + assertEquals(expUR.getPolicy(), actualUR.getPolicy()); + String[] expRoles = expUR.getRoles(); + Arrays.sort(expRoles); + String[] actualRoles = actualUR.getRoles(); + Arrays.sort(actualRoles); + assertArrayEquals(expRoles, actualRoles); + } + } + + private void verifyRealoadingParities(LedgerAdminInfo actualAccount, ParticipantNode[] expParties) { + assertEquals(expParties.length, actualAccount.getParticipantCount()); + ParticipantNode[] actualPaticipants = actualAccount.getParticipants(); + assertEquals(expParties.length, actualPaticipants.length); + for (int i = 0; i < actualPaticipants.length; i++) { + ParticipantNode rlParti = actualPaticipants[i]; + assertEquals(expParties[i].getAddress(), rlParti.getAddress()); + assertEquals(expParties[i].getName(), rlParti.getName()); + // assertEquals(expParties[i].getConsensusAddress(), + // rlParti.getConsensusAddress()); + assertEquals(expParties[i].getPubKey(), rlParti.getPubKey()); + } + } + + /** + * 验证指定账户是否只读; + * + * @param readonlyAccount + */ + private void verifyReadonlyState(LedgerAdminDataset readonlyAccount) { + ConsensusParticipantData newParti = new ConsensusParticipantData(); + newParti.setId((int) readonlyAccount.getParticipantCount()); + newParti.setHostAddress( + new NetworkAddress("192.168.10." + (10 + newParti.getId()), 10010 + 10 * newParti.getId())); + newParti.setName("Participant[" + newParti.getAddress() + "]"); + + BlockchainKeypair newKey = BlockchainKeyGenerator.getInstance().generate(); + newParti.setPubKey(newKey.getPubKey()); + + Throwable ex = null; + try { + readonlyAccount.addParticipant(newParti); + } catch (Exception e) { + ex = e; + } + assertNotNull(ex); + + ex = null; + try { + LedgerConfiguration newLedgerSetting = new LedgerConfiguration(readonlyAccount.getSettings()); + readonlyAccount.setLedgerSetting(newLedgerSetting); + } catch (Exception e) { + ex = e; + } + assertNotNull(ex); + } + +} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerBlockImplTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerBlockImplTest.java similarity index 96% rename from source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerBlockImplTest.java rename to source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerBlockImplTest.java index ce29e1a5..9479cc2b 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerBlockImplTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerBlockImplTest.java @@ -6,7 +6,7 @@ * Date: 2018/8/30 上午10:45 * Description: */ -package test.com.jd.blockchain.ledger; +package test.com.jd.blockchain.ledger.core; import static org.junit.Assert.assertEquals; @@ -19,8 +19,8 @@ import com.jd.blockchain.crypto.HashDigest; import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; import com.jd.blockchain.ledger.LedgerBlock; import com.jd.blockchain.ledger.LedgerDataSnapshot; -import com.jd.blockchain.ledger.core.impl.LedgerBlockData; -import com.jd.blockchain.ledger.core.impl.TransactionStagedSnapshot; +import com.jd.blockchain.ledger.core.LedgerBlockData; +import com.jd.blockchain.ledger.core.TransactionStagedSnapshot; /** * diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerEditorTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerEditorTest.java similarity index 94% rename from source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerEditorTest.java rename to source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerEditorTest.java index 0779204e..97979205 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerEditorTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerEditorTest.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger; +package test.com.jd.blockchain.ledger.core; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -27,14 +27,14 @@ import com.jd.blockchain.ledger.TransactionRequest; import com.jd.blockchain.ledger.TransactionState; import com.jd.blockchain.ledger.core.CryptoConfig; import com.jd.blockchain.ledger.core.DataAccount; -import com.jd.blockchain.ledger.core.LedgerDataSet; +import com.jd.blockchain.ledger.core.LedgerDataset; import com.jd.blockchain.ledger.core.LedgerEditor; import com.jd.blockchain.ledger.core.LedgerTransactionContext; +import com.jd.blockchain.ledger.core.LedgerTransactionalEditor; import com.jd.blockchain.ledger.core.UserAccount; -import com.jd.blockchain.ledger.core.impl.LedgerTransactionalEditor; import com.jd.blockchain.storage.service.utils.MemoryKVStorage; import com.jd.blockchain.transaction.ConsensusParticipantData; -import com.jd.blockchain.transaction.LedgerInitSettingData; +import com.jd.blockchain.transaction.LedgerInitData; import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.io.BytesUtils; import com.jd.blockchain.utils.net.NetworkAddress; @@ -95,7 +95,7 @@ public class LedgerEditorTest { public void testWriteDataAccoutKvOp() { LedgerEditor ldgEdt = createLedgerInitEditor(); LedgerTransactionContext genisisTxCtx = createGenisisTx(ldgEdt, participants); - LedgerDataSet ldgDS = genisisTxCtx.getDataSet(); + LedgerDataset ldgDS = genisisTxCtx.getDataset(); AsymmetricKeypair cryptoKeyPair = signatureFunction.generateKeypair(); BlockchainKeypair dataKP = new BlockchainKeypair(cryptoKeyPair.getPubKey(), cryptoKeyPair.getPrivKey()); @@ -128,7 +128,7 @@ public class LedgerEditorTest { public void testGennesisBlockCreation() { LedgerEditor ldgEdt = createLedgerInitEditor(); LedgerTransactionContext genisisTxCtx = createGenisisTx(ldgEdt, participants); - LedgerDataSet ldgDS = genisisTxCtx.getDataSet(); + LedgerDataset ldgDS = genisisTxCtx.getDataset(); AsymmetricKeypair cryptoKeyPair = signatureFunction.generateKeypair(); BlockchainKeypair userKP = new BlockchainKeypair(cryptoKeyPair.getPubKey(), cryptoKeyPair.getPrivKey()); diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerInitOperationTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerInitOperationTest.java similarity index 96% rename from source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerInitOperationTest.java rename to source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerInitOperationTest.java index 9cee71df..8c245fa2 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerInitOperationTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerInitOperationTest.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger; +package test.com.jd.blockchain.ledger.core; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -25,7 +25,7 @@ import com.jd.blockchain.ledger.core.CryptoConfig; import com.jd.blockchain.ledger.core.ParticipantCertData; import com.jd.blockchain.transaction.ConsensusParticipantData; import com.jd.blockchain.transaction.LedgerInitOpTemplate; -import com.jd.blockchain.transaction.LedgerInitSettingData; +import com.jd.blockchain.transaction.LedgerInitData; import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.net.NetworkAddress; @@ -36,7 +36,7 @@ public class LedgerInitOperationTest { byte[] seed = null; byte[] csSysSettingBytes = null; - LedgerInitSettingData ledgerInitSettingData = new LedgerInitSettingData(); + LedgerInitData ledgerInitSettingData = new LedgerInitData(); @Before public void initCfg() { @@ -76,7 +76,7 @@ public class LedgerInitOperationTest { keys[i] = BlockchainKeyGenerator.getInstance().generate(); parties[i] = new ConsensusParticipantData(); // parties[i].setId(i); - parties[i].setAddress(AddressEncoding.generateAddress(keys[i].getPubKey()).toBase58()); + parties[i].setAddress(AddressEncoding.generateAddress(keys[i].getPubKey())); parties[i].setHostAddress(new NetworkAddress("192.168.10." + (10 + i), 10010 + 10 * i)); parties[i].setName("Participant[" + i + "]"); parties[i].setPubKey(keys[i].getPubKey()); @@ -117,7 +117,7 @@ public class LedgerInitOperationTest { for (int i = 0; i < parties.length; i++) { keys[i] = BlockchainKeyGenerator.getInstance().generate(); - parties[i] = new ParticipantCertData(AddressEncoding.generateAddress(keys[i].getPubKey()).toBase58(), + parties[i] = new ParticipantCertData(AddressEncoding.generateAddress(keys[i].getPubKey()), "Participant[" + i + "]", keys[i].getPubKey()); } diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerInitSettingSerializeTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerInitSettingSerializeTest.java similarity index 96% rename from source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerInitSettingSerializeTest.java rename to source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerInitSettingSerializeTest.java index f867ae9b..46c96f65 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerInitSettingSerializeTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerInitSettingSerializeTest.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger; +package test.com.jd.blockchain.ledger.core; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -24,14 +24,14 @@ import com.jd.blockchain.ledger.core.CryptoConfig; import com.jd.blockchain.ledger.core.ParticipantCertData; import com.jd.blockchain.transaction.ConsensusParticipantData; import com.jd.blockchain.transaction.LedgerInitOpTemplate; -import com.jd.blockchain.transaction.LedgerInitSettingData; +import com.jd.blockchain.transaction.LedgerInitData; import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.net.NetworkAddress; public class LedgerInitSettingSerializeTest { byte[] seed = null; byte[] csSysSettingBytes = null; - LedgerInitSettingData ledgerInitSettingData = new LedgerInitSettingData(); + LedgerInitData ledgerInitSettingData = new LedgerInitData(); LedgerInitOpTemplate template = new LedgerInitOpTemplate(); private static final String[] SUPPORTED_PROVIDERS = { ClassicCryptoService.class.getName(), @@ -76,7 +76,7 @@ public class LedgerInitSettingSerializeTest { keys[i] = BlockchainKeyGenerator.getInstance().generate(); parties[i] = new ConsensusParticipantData(); // parties[i].setId(i); - parties[i].setAddress(AddressEncoding.generateAddress(keys[i].getPubKey()).toBase58()); + parties[i].setAddress(AddressEncoding.generateAddress(keys[i].getPubKey())); parties[i].setHostAddress(new NetworkAddress("192.168.10." + (10 + i), 10010 + 10 * i)); parties[i].setName("Participant[" + i + "]"); parties[i].setPubKey(keys[i].getPubKey()); @@ -84,7 +84,7 @@ public class LedgerInitSettingSerializeTest { ConsensusParticipantData[] parties1 = Arrays.copyOf(parties, 4); ledgerInitSettingData.setConsensusParticipants(parties1); - + byte[] encode = BinaryProtocol.encode(ledgerInitSettingData, LedgerInitSetting.class); LedgerInitSetting decode = BinaryProtocol.decode(encode); @@ -121,7 +121,7 @@ public class LedgerInitSettingSerializeTest { for (int i = 0; i < parties.length; i++) { keys[i] = BlockchainKeyGenerator.getInstance().generate(); - parties[i] = new ParticipantCertData(AddressEncoding.generateAddress(keys[i].getPubKey()).toBase58(), + parties[i] = new ParticipantCertData(AddressEncoding.generateAddress(keys[i].getPubKey()), "Participant[" + i + "]", keys[i].getPubKey()); } diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerManagerTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerManagerTest.java similarity index 88% rename from source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerManagerTest.java rename to source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerManagerTest.java index 3cd1a26d..d814326d 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerManagerTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerManagerTest.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger; +package test.com.jd.blockchain.ledger.core; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -20,19 +20,20 @@ import com.jd.blockchain.crypto.SignatureFunction; import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; import com.jd.blockchain.crypto.service.sm.SMCryptoService; -import com.jd.blockchain.ledger.core.ContractAccountSet; +import com.jd.blockchain.ledger.core.ContractAccountQuery; import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.DataAccountSet; -import com.jd.blockchain.ledger.core.LedgerDataSet; +import com.jd.blockchain.ledger.core.DataAccountQuery; +import com.jd.blockchain.ledger.core.LedgerDataset; import com.jd.blockchain.ledger.core.LedgerEditor; +import com.jd.blockchain.ledger.core.LedgerInitializer; +import com.jd.blockchain.ledger.core.LedgerManager; import com.jd.blockchain.ledger.core.LedgerRepository; import com.jd.blockchain.ledger.core.LedgerTransactionContext; import com.jd.blockchain.ledger.core.UserAccount; -import com.jd.blockchain.ledger.core.UserAccountSet; -import com.jd.blockchain.ledger.core.impl.LedgerManager; +import com.jd.blockchain.ledger.core.UserAccountQuery; import com.jd.blockchain.storage.service.utils.MemoryKVStorage; import com.jd.blockchain.transaction.ConsensusParticipantData; -import com.jd.blockchain.transaction.LedgerInitSettingData; +import com.jd.blockchain.transaction.LedgerInitData; import com.jd.blockchain.transaction.TxBuilder; import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.io.BytesUtils; @@ -71,20 +72,19 @@ public class LedgerManagerTest { public void testLedgerInit() { // 创建账本初始化配置; LedgerInitSetting initSetting = createLedgerInitSetting(); - + // 采用基于内存的 Storage; MemoryKVStorage storage = new MemoryKVStorage(); // 新建账本; - LedgerManager ledgerManager = new LedgerManager(); - LedgerEditor ldgEdt = ledgerManager.newLedger(initSetting, storage); + LedgerEditor ldgEdt = LedgerInitializer.createLedgerEditor(initSetting, storage); // 创建一个模拟的创世交易; TransactionRequest genesisTxReq = LedgerTestUtils.createLedgerInitTxRequest(participants); // 记录交易,注册用户; LedgerTransactionContext txCtx = ldgEdt.newTransaction(genesisTxReq); - LedgerDataSet ldgDS = txCtx.getDataSet(); + LedgerDataset ldgDS = txCtx.getDataset(); BlockchainKeypair userKP = BlockchainKeyGenerator.getInstance().generate(); UserAccount userAccount = ldgDS.getUserAccountSet().register(userKP.getAddress(), userKP.getPubKey()); @@ -111,6 +111,9 @@ public class LedgerManagerTest { // 提交数据,写入存储; ldgEdt.commit(); + + assertNull(genesisBlock.getLedgerHash()); + assertNotNull(genesisBlock.getHash()); // 重新加载并校验结果; LedgerManager reloadLedgerManager = new LedgerManager(); @@ -135,7 +138,7 @@ public class LedgerManagerTest { TransactionRequest txRequest = txReqBuilder.buildRequest(); LedgerTransactionContext txCtx1 = editor1.newTransaction(txRequest); - txCtx1.getDataSet().getDataAccountSet().register(dataKey.getAddress(), dataKey.getPubKey(), null); + txCtx1.getDataset().getDataAccountSet().register(dataKey.getAddress(), dataKey.getPubKey(), null); txCtx1.commit(TransactionState.SUCCESS); LedgerBlock block1 = editor1.prepare(); @@ -157,9 +160,9 @@ public class LedgerManagerTest { assertEquals(1, latestBlock.getHeight()); assertEquals(block1.getHash(), latestBlock.getHash()); - DataAccountSet dataAccountSet = reloadLedgerRepo.getDataAccountSet(latestBlock); - UserAccountSet userAccountSet = reloadLedgerRepo.getUserAccountSet(latestBlock); - ContractAccountSet contractAccountSet = reloadLedgerRepo.getContractAccountSet(latestBlock); + DataAccountQuery dataAccountSet = reloadLedgerRepo.getDataAccountSet(latestBlock); + UserAccountQuery userAccountSet = reloadLedgerRepo.getUserAccountSet(latestBlock); + ContractAccountQuery contractAccountSet = reloadLedgerRepo.getContractAccountSet(latestBlock); } @@ -189,7 +192,7 @@ public class LedgerManagerTest { defCryptoSetting.setAutoVerifyHash(true); defCryptoSetting.setHashAlgorithm(ClassicAlgorithm.SHA256); - LedgerInitSettingData initSetting = new LedgerInitSettingData(); + LedgerInitData initSetting = new LedgerInitData(); initSetting.setLedgerSeed(BytesUtils.toBytes("A Test Ledger seed!", "UTF-8")); initSetting.setCryptoSetting(defCryptoSetting); @@ -199,7 +202,7 @@ public class LedgerManagerTest { parties[0].setName("John"); AsymmetricKeypair kp0 = signatureFunction.generateKeypair(); parties[0].setPubKey(kp0.getPubKey()); - parties[0].setAddress(AddressEncoding.generateAddress(kp0.getPubKey()).toBase58()); + parties[0].setAddress(AddressEncoding.generateAddress(kp0.getPubKey())); parties[0].setHostAddress(new NetworkAddress("127.0.0.1", 9000)); parties[1] = new ConsensusParticipantData(); @@ -207,7 +210,7 @@ public class LedgerManagerTest { parties[1].setName("Mary"); AsymmetricKeypair kp1 = signatureFunction.generateKeypair(); parties[1].setPubKey(kp1.getPubKey()); - parties[1].setAddress(AddressEncoding.generateAddress(kp1.getPubKey()).toBase58()); + parties[1].setAddress(AddressEncoding.generateAddress(kp1.getPubKey())); parties[1].setHostAddress(new NetworkAddress("127.0.0.1", 9010)); parties[2] = new ConsensusParticipantData(); @@ -215,7 +218,7 @@ public class LedgerManagerTest { parties[2].setName("Jerry"); AsymmetricKeypair kp2 = signatureFunction.generateKeypair(); parties[2].setPubKey(kp2.getPubKey()); - parties[2].setAddress(AddressEncoding.generateAddress(kp2.getPubKey()).toBase58()); + parties[2].setAddress(AddressEncoding.generateAddress(kp2.getPubKey())); parties[2].setHostAddress(new NetworkAddress("127.0.0.1", 9020)); parties[3] = new ConsensusParticipantData(); @@ -223,7 +226,7 @@ public class LedgerManagerTest { parties[3].setName("Tom"); AsymmetricKeypair kp3 = signatureFunction.generateKeypair(); parties[3].setPubKey(kp3.getPubKey()); - parties[3].setAddress(AddressEncoding.generateAddress(kp3.getPubKey()).toBase58()); + parties[3].setAddress(AddressEncoding.generateAddress(kp3.getPubKey())); parties[3].setHostAddress(new NetworkAddress("127.0.0.1", 9030)); initSetting.setConsensusParticipants(parties); diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerMetaDataTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerMetaDataTest.java similarity index 90% rename from source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerMetaDataTest.java rename to source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerMetaDataTest.java index 401c5de2..e7cba7ad 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerMetaDataTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerMetaDataTest.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger; +package test.com.jd.blockchain.ledger.core; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -8,7 +8,7 @@ import static org.junit.Assert.assertTrue; import java.util.Random; import com.jd.blockchain.ledger.LedgerMetadata; -import com.jd.blockchain.ledger.LedgerSetting; +import com.jd.blockchain.ledger.LedgerSettings; import org.junit.Before; import org.junit.Test; @@ -16,6 +16,7 @@ import com.jd.blockchain.binaryproto.BinaryProtocol; import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.crypto.AddressEncoding; import com.jd.blockchain.crypto.Crypto; +import com.jd.blockchain.crypto.CryptoAlgorithm; import com.jd.blockchain.crypto.CryptoProvider; import com.jd.blockchain.crypto.HashDigest; import com.jd.blockchain.crypto.PubKey; @@ -25,7 +26,7 @@ import com.jd.blockchain.crypto.service.sm.SMCryptoService; import com.jd.blockchain.ledger.CryptoSetting; import com.jd.blockchain.ledger.ParticipantNode; import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.LedgerAdminAccount; +import com.jd.blockchain.ledger.core.LedgerAdminDataset; import com.jd.blockchain.ledger.core.LedgerConfiguration; import com.jd.blockchain.ledger.core.ParticipantCertData; import com.jd.blockchain.utils.Bytes; @@ -74,12 +75,14 @@ public class LedgerMetaDataTest { cryptoConfig.setAutoVerifyHash(true); cryptoConfig.setHashAlgorithm(ClassicAlgorithm.SHA256); - LedgerConfiguration ledgerConfiguration = new LedgerConfiguration(consensusProvider, - new Bytes(consensusSettingBytes), cryptoConfig); - LedgerAdminAccount.LedgerMetadataImpl ledgerMetadata = new LedgerAdminAccount.LedgerMetadataImpl(); +// LedgerConfiguration ledgerConfiguration = new LedgerConfiguration(consensusProvider, +// new Bytes(consensusSettingBytes), cryptoConfig); + HashDigest settingsHash = Crypto.getHashFunction("SHA256").hash(consensusSettingBytes); + + LedgerAdminDataset.LedgerMetadataInfo ledgerMetadata = new LedgerAdminDataset.LedgerMetadataInfo(); ledgerMetadata.setSeed(seed); - ledgerMetadata.setSetting(ledgerConfiguration); + ledgerMetadata.setSettingsHash(settingsHash); HashDigest hashDigest = new HashDigest(ClassicAlgorithm.SHA256, rawDigestBytes); ledgerMetadata.setParticipantsHash(hashDigest); @@ -91,7 +94,7 @@ public class LedgerMetaDataTest { // verify start assertArrayEquals(ledgerMetadata.getSeed(), deLedgerMetaData.getSeed()); assertEquals(ledgerMetadata.getParticipantsHash(), deLedgerMetaData.getParticipantsHash()); - assertNotEquals(ledgerMetadata.getSetting(), deLedgerMetaData.getSetting()); + assertEquals(ledgerMetadata.getSettingsHash(), deLedgerMetaData.getSettingsHash()); return; } @@ -119,8 +122,8 @@ public class LedgerMetaDataTest { LedgerConfiguration ledgerConfiguration = new LedgerConfiguration(consensusProvider, new Bytes(csSettingsBytes), cryptoConfig); - byte[] encodeBytes = BinaryProtocol.encode(ledgerConfiguration, LedgerSetting.class); - LedgerSetting deLedgerConfiguration = BinaryProtocol.decode(encodeBytes); + byte[] encodeBytes = BinaryProtocol.encode(ledgerConfiguration, LedgerSettings.class); + LedgerSettings deLedgerConfiguration = BinaryProtocol.decode(encodeBytes); // verify start assertTrue(ledgerConfiguration.getConsensusSetting().equals(deLedgerConfiguration.getConsensusSetting())); assertEquals(ledgerConfiguration.getCryptoSetting().getAutoVerifyHash(), @@ -185,7 +188,7 @@ public class LedgerMetaDataTest { String name = "John"; // NetworkAddress consensusAddress = new NetworkAddress("192.168.1.1", 9001, // false); - String address = AddressEncoding.generateAddress(pubKey).toBase58(); + Bytes address = AddressEncoding.generateAddress(pubKey); ParticipantCertData participantCertData = new ParticipantCertData(address, name, pubKey); // encode and decode diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerSecurityManagerTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerSecurityManagerTest.java new file mode 100644 index 00000000..7c82d21b --- /dev/null +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerSecurityManagerTest.java @@ -0,0 +1,181 @@ +package test.com.jd.blockchain.ledger.core; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; +import org.mockito.Mockito; + +import com.jd.blockchain.crypto.Crypto; +import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.CryptoProvider; +import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; +import com.jd.blockchain.crypto.service.sm.SMCryptoService; +import com.jd.blockchain.ledger.BlockchainKeyGenerator; +import com.jd.blockchain.ledger.BlockchainKeypair; +import com.jd.blockchain.ledger.CryptoSetting; +import com.jd.blockchain.ledger.LedgerPermission; +import com.jd.blockchain.ledger.ParticipantDataQuery; +import com.jd.blockchain.ledger.Privileges; +import com.jd.blockchain.ledger.RolesPolicy; +import com.jd.blockchain.ledger.TransactionPermission; +import com.jd.blockchain.ledger.core.CryptoConfig; +import com.jd.blockchain.ledger.core.LedgerSecurityManager; +import com.jd.blockchain.ledger.core.LedgerSecurityManagerImpl; +import com.jd.blockchain.ledger.core.MultiIDsPolicy; +import com.jd.blockchain.ledger.core.RolePrivilegeDataset; +import com.jd.blockchain.ledger.core.SecurityPolicy; +import com.jd.blockchain.ledger.core.UserAccountQuery; +import com.jd.blockchain.ledger.core.UserRoleDataset; +import com.jd.blockchain.storage.service.utils.MemoryKVStorage; +import com.jd.blockchain.utils.Bytes; + +public class LedgerSecurityManagerTest { + + private static final String[] SUPPORTED_PROVIDER_NAMES = { ClassicCryptoService.class.getName(), + SMCryptoService.class.getName() }; + + private static final CryptoAlgorithm HASH_ALGORITHM = Crypto.getAlgorithm("SHA256"); + + private static final CryptoProvider[] SUPPORTED_PROVIDERS = new CryptoProvider[SUPPORTED_PROVIDER_NAMES.length]; + + private static final CryptoSetting CRYPTO_SETTINGS; + + static { + for (int i = 0; i < SUPPORTED_PROVIDER_NAMES.length; i++) { + SUPPORTED_PROVIDERS[i] = Crypto.getProvider(SUPPORTED_PROVIDER_NAMES[i]); + } + + CryptoConfig cryptoConfig = new CryptoConfig(); + cryptoConfig.setAutoVerifyHash(true); + cryptoConfig.setSupportedProviders(SUPPORTED_PROVIDERS); + cryptoConfig.setHashAlgorithm(HASH_ALGORITHM); + + CRYPTO_SETTINGS = cryptoConfig; + } + + private RolePrivilegeDataset createRolePrivilegeDataset(MemoryKVStorage testStorage) { + String prefix = "role-privilege/"; + RolePrivilegeDataset rolePrivilegeDataset = new RolePrivilegeDataset(CRYPTO_SETTINGS, prefix, testStorage, + testStorage); + + return rolePrivilegeDataset; + } + + private UserRoleDataset createUserRoleDataset(MemoryKVStorage testStorage) { + String prefix = "user-roles/"; + UserRoleDataset userRolesDataset = new UserRoleDataset(CRYPTO_SETTINGS, prefix, testStorage, testStorage); + + return userRolesDataset; + } + + @Test + public void testGetSecurityPolicy() { + MemoryKVStorage testStorage = new MemoryKVStorage(); + + // 定义不同角色用户的 keypair; + final BlockchainKeypair kpManager = BlockchainKeyGenerator.getInstance().generate(); + final BlockchainKeypair kpEmployee = BlockchainKeyGenerator.getInstance().generate(); + final BlockchainKeypair kpDevoice = BlockchainKeyGenerator.getInstance().generate(); + final BlockchainKeypair kpPlatform = BlockchainKeyGenerator.getInstance().generate(); + + // 定义角色和权限; + final String ROLE_ADMIN = "ID_ADMIN"; + final String ROLE_OPERATOR = "OPERATOR"; + final String ROLE_DATA_COLLECTOR = "DATA_COLLECTOR"; + final String ROLE_PLATFORM = "PLATFORM"; + + // 定义管理员角色的权限:【账本权限只允许:注册用户、注册数据账户】【交易权限只允许:调用账本直接操作】 + final Privileges PRIVILEGES_ADMIN = Privileges.configure() + .enable(LedgerPermission.REGISTER_USER, LedgerPermission.REGISTER_DATA_ACCOUNT) + .enable(TransactionPermission.DIRECT_OPERATION); + + // 定义操作员角色的权限:【账本权限只允许:写入数据账户】【交易权限只允许:调用合约】 + final Privileges PRIVILEGES_OPERATOR = Privileges.configure().enable(LedgerPermission.WRITE_DATA_ACCOUNT) + .enable(TransactionPermission.CONTRACT_OPERATION); + + // 定义数据收集器角色的权限:【账本权限只允许:写入数据账户】【交易权限只允许:调用账本直接操作】 + final Privileges PRIVILEGES_DATA_COLLECTOR = Privileges.configure().enable(LedgerPermission.WRITE_DATA_ACCOUNT) + .enable(TransactionPermission.DIRECT_OPERATION); + + // 定义平台角色的权限:【账本权限只允许:签署合约】 (只允许作为节点签署交易,不允许作为终端发起交易指令) + final Privileges PRIVILEGES_PLATFORM = Privileges.configure().enable(LedgerPermission.APPROVE_TX); + + RolePrivilegeDataset rolePrivilegeDataset = createRolePrivilegeDataset(testStorage); + long v = rolePrivilegeDataset.addRolePrivilege(ROLE_ADMIN, PRIVILEGES_ADMIN); + assertTrue(v > -1); + v = rolePrivilegeDataset.addRolePrivilege(ROLE_OPERATOR, PRIVILEGES_OPERATOR); + assertTrue(v > -1); + v = rolePrivilegeDataset.addRolePrivilege(ROLE_DATA_COLLECTOR, PRIVILEGES_DATA_COLLECTOR); + assertTrue(v > -1); + v = rolePrivilegeDataset.addRolePrivilege(ROLE_PLATFORM, PRIVILEGES_PLATFORM); + assertTrue(v > -1); + rolePrivilegeDataset.commit(); + + // 为用户分配角色; + String[] managerRoles = new String[] { ROLE_ADMIN, ROLE_OPERATOR }; + String[] employeeRoles = new String[] { ROLE_OPERATOR }; + String[] devoiceRoles = new String[] { ROLE_DATA_COLLECTOR }; + String[] platformRoles = new String[] { ROLE_PLATFORM }; + UserRoleDataset userRolesDataset = createUserRoleDataset(testStorage); + userRolesDataset.addUserRoles(kpManager.getAddress(), RolesPolicy.UNION, managerRoles); + userRolesDataset.addUserRoles(kpEmployee.getAddress(), RolesPolicy.UNION, employeeRoles); + userRolesDataset.addUserRoles(kpDevoice.getAddress(), RolesPolicy.UNION, devoiceRoles); + userRolesDataset.addUserRoles(kpPlatform.getAddress(), RolesPolicy.UNION, platformRoles); + userRolesDataset.commit(); + + ParticipantDataQuery partisQuery = Mockito.mock(ParticipantDataQuery.class); + UserAccountQuery usersQuery = Mockito.mock(UserAccountQuery.class); + + // 创建安全管理器; + LedgerSecurityManager securityManager = new LedgerSecurityManagerImpl(rolePrivilegeDataset, userRolesDataset, + partisQuery, usersQuery); + + // 定义终端用户列表;终端用户一起共同具有 ADMIN、OPERATOR 角色; + final Map endpoints = new HashMap<>(); + endpoints.put(kpManager.getAddress(), kpManager); + endpoints.put(kpEmployee.getAddress(), kpEmployee); + + // 定义节点参与方列表; + final Map nodes = new HashMap<>(); + nodes.put(kpPlatform.getAddress(), kpPlatform); + + // 创建一项与指定的终端用户和节点参与方相关的安全策略; + SecurityPolicy policy = securityManager.createSecurityPolicy(endpoints.keySet(), nodes.keySet()); + + // 校验安全策略的正确性; + LedgerPermission[] ledgerPermissions = LedgerPermission.values(); + for (LedgerPermission p : ledgerPermissions) { + // 终端节点有 ADMIN 和 OPERATOR 两种角色的合并权限; + if (p == LedgerPermission.REGISTER_USER || p == LedgerPermission.REGISTER_DATA_ACCOUNT + || p == LedgerPermission.WRITE_DATA_ACCOUNT) { + assertTrue(policy.isEndpointEnable(p, MultiIDsPolicy.AT_LEAST_ONE)); + } else { + assertFalse(policy.isEndpointEnable(p, MultiIDsPolicy.AT_LEAST_ONE)); + } + + if (p == LedgerPermission.APPROVE_TX) { + // 共识参与方只有 PLATFORM 角色的权限:核准交易; + assertTrue(policy.isNodeEnable(p, MultiIDsPolicy.AT_LEAST_ONE)); + } else { + assertFalse(policy.isNodeEnable(p, MultiIDsPolicy.AT_LEAST_ONE)); + } + } + + TransactionPermission[] transactionPermissions = TransactionPermission.values(); + for (TransactionPermission p : transactionPermissions) { + // 终端节点有 ADMIN 和 OPERATOR 两种角色的合并权限; + if (p == TransactionPermission.DIRECT_OPERATION || p == TransactionPermission.CONTRACT_OPERATION) { + assertTrue(policy.isEndpointEnable(p, MultiIDsPolicy.AT_LEAST_ONE)); + } else { + assertFalse(policy.isEndpointEnable(p, MultiIDsPolicy.AT_LEAST_ONE)); + } + + assertFalse(policy.isNodeEnable(p, MultiIDsPolicy.AT_LEAST_ONE)); + } + } + +} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerTestUtils.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerTestUtils.java similarity index 93% rename from source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerTestUtils.java rename to source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerTestUtils.java index 6101cdba..eb6835b5 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerTestUtils.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerTestUtils.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger; +package test.com.jd.blockchain.ledger.core; import java.util.Random; @@ -19,9 +19,9 @@ import com.jd.blockchain.ledger.TransactionRequest; import com.jd.blockchain.ledger.TransactionRequestBuilder; import com.jd.blockchain.ledger.TransactionResponse; import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.impl.TransactionStagedSnapshot; +import com.jd.blockchain.ledger.core.TransactionStagedSnapshot; import com.jd.blockchain.transaction.ConsensusParticipantData; -import com.jd.blockchain.transaction.LedgerInitSettingData; +import com.jd.blockchain.transaction.LedgerInitData; import com.jd.blockchain.transaction.TransactionService; import com.jd.blockchain.transaction.TxBuilder; import com.jd.blockchain.utils.Bytes; @@ -62,7 +62,7 @@ public class LedgerTestUtils { defCryptoSetting.setAutoVerifyHash(true); defCryptoSetting.setHashAlgorithm(ClassicAlgorithm.SHA256); - LedgerInitSettingData initSetting = new LedgerInitSettingData(); + LedgerInitData initSetting = new LedgerInitData(); initSetting.setLedgerSeed(BytesUtils.toBytes("A Test Ledger seed!", "UTF-8")); initSetting.setCryptoSetting(defCryptoSetting); @@ -72,7 +72,7 @@ public class LedgerTestUtils { parties[i].setId(0); parties[i].setName("Parti-" + i); parties[i].setPubKey(partiKeys[i].getPubKey()); - parties[i].setAddress(AddressEncoding.generateAddress(partiKeys[i].getPubKey()).toBase58()); + parties[i].setAddress(AddressEncoding.generateAddress(partiKeys[i].getPubKey())); parties[i].setHostAddress(new NetworkAddress("192.168.1." + (10 + i), 9000)); } @@ -125,13 +125,13 @@ public class LedgerTestUtils { return txReqBuilder.buildRequest(); } - - public static TransactionRequest createTxRequest_DataAccountReg(BlockchainKeypair dataAccountID, HashDigest ledgerHash, - BlockchainKeypair nodeKeypair, BlockchainKeypair... signers) { + + public static TransactionRequest createTxRequest_DataAccountReg(BlockchainKeypair dataAccountID, + HashDigest ledgerHash, BlockchainKeypair nodeKeypair, BlockchainKeypair... signers) { TxBuilder txBuilder = new TxBuilder(ledgerHash); - + txBuilder.dataAccounts().register(dataAccountID.getIdentity()); - + TransactionRequestBuilder txReqBuilder = txBuilder.prepareRequest(); if (signers != null) { for (BlockchainKeypair signer : signers) { @@ -141,16 +141,17 @@ public class LedgerTestUtils { if (nodeKeypair != null) { txReqBuilder.signAsNode(nodeKeypair); } - + return txReqBuilder.buildRequest(); } - - public static TransactionRequest createTxRequest_DataAccountWrite(Bytes dataAccountAddress, String key, String value, long version, HashDigest ledgerHash, - BlockchainKeypair nodeKeypair, BlockchainKeypair... signers) { + + public static TransactionRequest createTxRequest_DataAccountWrite(Bytes dataAccountAddress, String key, + String value, long version, HashDigest ledgerHash, BlockchainKeypair nodeKeypair, + BlockchainKeypair... signers) { TxBuilder txBuilder = new TxBuilder(ledgerHash); - + txBuilder.dataAccount(dataAccountAddress).setText(key, value, version); - + TransactionRequestBuilder txReqBuilder = txBuilder.prepareRequest(); if (signers != null) { for (BlockchainKeypair signer : signers) { @@ -160,7 +161,7 @@ public class LedgerTestUtils { if (nodeKeypair != null) { txReqBuilder.signAsNode(nodeKeypair); } - + return txReqBuilder.buildRequest(); } diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerTransactionDataTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerTransactionDataTest.java similarity index 98% rename from source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerTransactionDataTest.java rename to source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerTransactionDataTest.java index 9e53ae24..f676ea87 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/LedgerTransactionDataTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/LedgerTransactionDataTest.java @@ -6,7 +6,7 @@ * Date: 2018/8/30 上午9:48 * Description: */ -package test.com.jd.blockchain.ledger; +package test.com.jd.blockchain.ledger.core; import static org.junit.Assert.assertEquals; @@ -35,8 +35,8 @@ import com.jd.blockchain.ledger.Transaction; import com.jd.blockchain.ledger.TransactionContent; import com.jd.blockchain.ledger.TransactionRequest; import com.jd.blockchain.ledger.TransactionState; -import com.jd.blockchain.ledger.core.impl.LedgerTransactionData; -import com.jd.blockchain.ledger.core.impl.TransactionStagedSnapshot; +import com.jd.blockchain.ledger.core.LedgerTransactionData; +import com.jd.blockchain.ledger.core.TransactionStagedSnapshot; import com.jd.blockchain.transaction.BlockchainOperationFactory; import com.jd.blockchain.transaction.DigitalSignatureBlob; import com.jd.blockchain.transaction.TxContentBlob; diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/MerkleDataSetTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/MerkleDataSetTest.java similarity index 96% rename from source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/MerkleDataSetTest.java rename to source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/MerkleDataSetTest.java index 7bbe7682..a90806d6 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/MerkleDataSetTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/MerkleDataSetTest.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger; +package test.com.jd.blockchain.ledger.core; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; @@ -20,9 +20,9 @@ import com.jd.blockchain.crypto.HashDigest; import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; import com.jd.blockchain.crypto.service.sm.SMCryptoService; +import com.jd.blockchain.ledger.MerkleProof; import com.jd.blockchain.ledger.core.CryptoConfig; import com.jd.blockchain.ledger.core.MerkleDataSet; -import com.jd.blockchain.ledger.core.MerkleProof; import com.jd.blockchain.storage.service.VersioningKVEntry; import com.jd.blockchain.storage.service.utils.MemoryKVStorage; import com.jd.blockchain.utils.Bytes; @@ -90,6 +90,18 @@ public class MerkleDataSetTest { mds.setValue("C", "C".getBytes(), -1); mds.commit(); + + byte[] va = mds.getValue("A"); + assertNotNull(va); + assertEquals("A", new String(va)); + + byte[] vc = mds.getValue("C"); + VersioningKVEntry ventry = mds.getDataEntry("C"); + assertNotNull(vc); + assertNotNull(ventry); + assertEquals("C", new String(vc)); + assertEquals("C", ventry.getKey().toUTF8String()); + HashDigest root1 = mds.getRootHash(); diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/MerkleTreeTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/MerkleTreeTest.java similarity index 99% rename from source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/MerkleTreeTest.java rename to source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/MerkleTreeTest.java index d8cb3d29..afe8e435 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/MerkleTreeTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/MerkleTreeTest.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger; +package test.com.jd.blockchain.ledger.core; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; @@ -17,9 +17,9 @@ import org.mockito.Mockito; import com.jd.blockchain.crypto.HashDigest; import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.ledger.core.MerkleDataNode; -import com.jd.blockchain.ledger.core.MerkleNode; -import com.jd.blockchain.ledger.core.MerkleProof; +import com.jd.blockchain.ledger.MerkleDataNode; +import com.jd.blockchain.ledger.MerkleNode; +import com.jd.blockchain.ledger.MerkleProof; import com.jd.blockchain.ledger.core.MerkleTree; import com.jd.blockchain.storage.service.utils.ExistancePolicyKVStorageMap; import com.jd.blockchain.utils.Bytes; diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/RolePrivilegeDatasetTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/RolePrivilegeDatasetTest.java new file mode 100644 index 00000000..18937fa0 --- /dev/null +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/RolePrivilegeDatasetTest.java @@ -0,0 +1,69 @@ +package test.com.jd.blockchain.ledger.core; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.jd.blockchain.crypto.Crypto; +import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.CryptoProvider; +import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; +import com.jd.blockchain.crypto.service.sm.SMCryptoService; +import com.jd.blockchain.ledger.LedgerPermission; +import com.jd.blockchain.ledger.RolePrivileges; +import com.jd.blockchain.ledger.TransactionPermission; +import com.jd.blockchain.ledger.core.CryptoConfig; +import com.jd.blockchain.ledger.core.RolePrivilegeDataset; +import com.jd.blockchain.storage.service.utils.MemoryKVStorage; + +public class RolePrivilegeDatasetTest { + + private static final String[] SUPPORTED_PROVIDER_NAMES = { ClassicCryptoService.class.getName(), + SMCryptoService.class.getName() }; + + private static final CryptoAlgorithm HASH_ALGORITHM = Crypto.getAlgorithm("SHA256"); + + private static final CryptoProvider[] SUPPORTED_PROVIDERS = new CryptoProvider[SUPPORTED_PROVIDER_NAMES.length]; + static { + for (int i = 0; i < SUPPORTED_PROVIDER_NAMES.length; i++) { + SUPPORTED_PROVIDERS[i] = Crypto.getProvider(SUPPORTED_PROVIDER_NAMES[i]); + } + } + + @Test + public void testAddRolePrivilege() { + + CryptoConfig cryptoConfig = new CryptoConfig(); + cryptoConfig.setAutoVerifyHash(true); + cryptoConfig.setSupportedProviders(SUPPORTED_PROVIDERS); + cryptoConfig.setHashAlgorithm(HASH_ALGORITHM); + + MemoryKVStorage testStorage = new MemoryKVStorage(); + + String roleName = "DEFAULT"; + String prefix = "role-privilege/"; + RolePrivilegeDataset rolePrivilegeDataset = new RolePrivilegeDataset(cryptoConfig, prefix, testStorage, + testStorage); + rolePrivilegeDataset.addRolePrivilege(roleName, new LedgerPermission[] { LedgerPermission.REGISTER_USER }, + new TransactionPermission[] { TransactionPermission.CONTRACT_OPERATION }); + + rolePrivilegeDataset.commit(); + + RolePrivileges rolePrivilege = rolePrivilegeDataset.getRolePrivilege(roleName); + assertNotNull(rolePrivilege); + + HashDigest rootHash = rolePrivilegeDataset.getRootHash(); + RolePrivilegeDataset newRolePrivilegeDataset = new RolePrivilegeDataset(rootHash, cryptoConfig, prefix, + testStorage, testStorage, true); + rolePrivilege = newRolePrivilegeDataset.getRolePrivilege(roleName); + assertNotNull(rolePrivilege); + + assertTrue(rolePrivilege.getLedgerPrivilege().isEnable(LedgerPermission.REGISTER_USER)); + assertTrue(rolePrivilege.getTransactionPrivilege().isEnable(TransactionPermission.CONTRACT_OPERATION)); + + + } + +} diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/TestContract.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TestContract.java similarity index 96% rename from source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/TestContract.java rename to source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TestContract.java index 4d9a5ccd..4cbe2784 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/TestContract.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TestContract.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger; +package test.com.jd.blockchain.ledger.core; import com.jd.blockchain.contract.Contract; import com.jd.blockchain.contract.ContractEvent; diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/TestContractImpl.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TestContractImpl.java similarity index 94% rename from source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/TestContractImpl.java rename to source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TestContractImpl.java index 3375f7f3..339cb4fb 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/TestContractImpl.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TestContractImpl.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger; +package test.com.jd.blockchain.ledger.core; public interface TestContractImpl { diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/TransactionBatchProcessorTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TransactionBatchProcessorTest.java similarity index 85% rename from source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/TransactionBatchProcessorTest.java rename to source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TransactionBatchProcessorTest.java index f51f211d..1f7dbbc1 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/TransactionBatchProcessorTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TransactionBatchProcessorTest.java @@ -1,12 +1,15 @@ -package test.com.jd.blockchain.ledger; +package test.com.jd.blockchain.ledger.core; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.when; import org.junit.Test; +import org.mockito.Mockito; import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.crypto.HashDigest; @@ -18,25 +21,30 @@ import com.jd.blockchain.ledger.DataVersionConflictException; import com.jd.blockchain.ledger.EndpointRequest; import com.jd.blockchain.ledger.LedgerBlock; import com.jd.blockchain.ledger.LedgerInitSetting; +import com.jd.blockchain.ledger.LedgerPermission; import com.jd.blockchain.ledger.LedgerTransaction; import com.jd.blockchain.ledger.NodeRequest; import com.jd.blockchain.ledger.TransactionContent; import com.jd.blockchain.ledger.TransactionContentBody; +import com.jd.blockchain.ledger.TransactionPermission; import com.jd.blockchain.ledger.TransactionRequest; import com.jd.blockchain.ledger.TransactionResponse; import com.jd.blockchain.ledger.TransactionState; import com.jd.blockchain.ledger.UserRegisterOperation; import com.jd.blockchain.ledger.core.DataAccount; -import com.jd.blockchain.ledger.core.LedgerDataSet; +import com.jd.blockchain.ledger.core.DefaultOperationHandleRegisteration; +import com.jd.blockchain.ledger.core.LedgerDataQuery; +import com.jd.blockchain.ledger.core.LedgerDataset; import com.jd.blockchain.ledger.core.LedgerEditor; +import com.jd.blockchain.ledger.core.LedgerManager; import com.jd.blockchain.ledger.core.LedgerRepository; +import com.jd.blockchain.ledger.core.LedgerSecurityManager; import com.jd.blockchain.ledger.core.LedgerTransactionContext; +import com.jd.blockchain.ledger.core.LedgerTransactionalEditor; +import com.jd.blockchain.ledger.core.OperationHandleRegisteration; +import com.jd.blockchain.ledger.core.SecurityPolicy; +import com.jd.blockchain.ledger.core.TransactionBatchProcessor; import com.jd.blockchain.ledger.core.UserAccount; -import com.jd.blockchain.ledger.core.impl.DefaultOperationHandleRegisteration; -import com.jd.blockchain.ledger.core.impl.LedgerManager; -import com.jd.blockchain.ledger.core.impl.LedgerTransactionalEditor; -import com.jd.blockchain.ledger.core.impl.OperationHandleRegisteration; -import com.jd.blockchain.ledger.core.impl.TransactionBatchProcessor; import com.jd.blockchain.storage.service.utils.MemoryKVStorage; public class TransactionBatchProcessorTest { @@ -76,7 +84,7 @@ public class TransactionBatchProcessorTest { LedgerRepository ledgerRepo = ledgerManager.register(ledgerHash, STORAGE); // 验证参与方账户的存在; - LedgerDataSet previousBlockDataset = ledgerRepo.getDataSet(ledgerRepo.getLatestBlock()); + LedgerDataQuery previousBlockDataset = ledgerRepo.getDataSet(ledgerRepo.getLatestBlock()); UserAccount user0 = previousBlockDataset.getUserAccountSet().getUser(parti0.getAddress()); assertNotNull(user0); boolean partiRegistered = previousBlockDataset.getUserAccountSet().contains(parti0.getAddress()); @@ -86,8 +94,9 @@ public class TransactionBatchProcessorTest { LedgerEditor newBlockEditor = ledgerRepo.createNextBlock(); OperationHandleRegisteration opReg = new DefaultOperationHandleRegisteration(); - TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(newBlockEditor, previousBlockDataset, - opReg, ledgerManager); + LedgerSecurityManager securityManager = getSecurityManager(); + TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(securityManager, newBlockEditor, + previousBlockDataset, opReg, ledgerManager); // 注册新用户; BlockchainKeypair userKeypair = BlockchainKeyGenerator.getInstance().generate(); @@ -109,6 +118,20 @@ public class TransactionBatchProcessorTest { assertEquals(TransactionState.SUCCESS, txResp.getExecutionState()); } + private static LedgerSecurityManager getSecurityManager() { + LedgerSecurityManager securityManager = Mockito.mock(LedgerSecurityManager.class); + + SecurityPolicy securityPolicy = Mockito.mock(SecurityPolicy.class); + when(securityPolicy.isEndpointEnable(any(LedgerPermission.class), any())).thenReturn(true); + when(securityPolicy.isEndpointEnable(any(TransactionPermission.class), any())).thenReturn(true); + when(securityPolicy.isNodeEnable(any(LedgerPermission.class), any())).thenReturn(true); + when(securityPolicy.isNodeEnable(any(TransactionPermission.class), any())).thenReturn(true); + + when(securityManager.createSecurityPolicy(any(), any())).thenReturn(securityPolicy); + + return securityManager; + } + @Test public void testMultiTxsProcess() { final MemoryKVStorage STORAGE = new MemoryKVStorage(); @@ -121,7 +144,7 @@ public class TransactionBatchProcessorTest { LedgerRepository ledgerRepo = ledgerManager.register(ledgerHash, STORAGE); // 验证参与方账户的存在; - LedgerDataSet previousBlockDataset = ledgerRepo.getDataSet(ledgerRepo.getLatestBlock()); + LedgerDataQuery previousBlockDataset = ledgerRepo.getDataSet(ledgerRepo.getLatestBlock()); UserAccount user0 = previousBlockDataset.getUserAccountSet().getUser(parti0.getAddress()); assertNotNull(user0); boolean partiRegistered = previousBlockDataset.getUserAccountSet().contains(parti0.getAddress()); @@ -131,8 +154,9 @@ public class TransactionBatchProcessorTest { LedgerEditor newBlockEditor = ledgerRepo.createNextBlock(); OperationHandleRegisteration opReg = new DefaultOperationHandleRegisteration(); - TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(newBlockEditor, previousBlockDataset, - opReg, ledgerManager); + LedgerSecurityManager securityManager = getSecurityManager(); + TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(securityManager, newBlockEditor, + previousBlockDataset, opReg, ledgerManager); // 注册新用户; BlockchainKeypair userKeypair1 = BlockchainKeyGenerator.getInstance().generate(); @@ -159,7 +183,7 @@ public class TransactionBatchProcessorTest { assertEquals(newBlock.getHash(), latestBlock.getHash()); assertEquals(1, newBlock.getHeight()); - LedgerDataSet ledgerDS = ledgerRepo.getDataSet(latestBlock); + LedgerDataQuery ledgerDS = ledgerRepo.getDataSet(latestBlock); boolean existUser1 = ledgerDS.getUserAccountSet().contains(userKeypair1.getAddress()); boolean existUser2 = ledgerDS.getUserAccountSet().contains(userKeypair2.getAddress()); assertTrue(existUser1); @@ -178,7 +202,7 @@ public class TransactionBatchProcessorTest { LedgerRepository ledgerRepo = ledgerManager.register(ledgerHash, STORAGE); // 验证参与方账户的存在; - LedgerDataSet previousBlockDataset = ledgerRepo.getDataSet(ledgerRepo.getLatestBlock()); + LedgerDataQuery previousBlockDataset = ledgerRepo.getDataSet(ledgerRepo.getLatestBlock()); UserAccount user0 = previousBlockDataset.getUserAccountSet().getUser(parti0.getAddress()); assertNotNull(user0); boolean partiRegistered = previousBlockDataset.getUserAccountSet().contains(parti0.getAddress()); @@ -188,8 +212,9 @@ public class TransactionBatchProcessorTest { LedgerEditor newBlockEditor = ledgerRepo.createNextBlock(); OperationHandleRegisteration opReg = new DefaultOperationHandleRegisteration(); - TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(newBlockEditor, previousBlockDataset, - opReg, ledgerManager); + LedgerSecurityManager securityManager = getSecurityManager(); + TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(securityManager, newBlockEditor, + previousBlockDataset, opReg, ledgerManager); // 注册新用户; BlockchainKeypair userKeypair1 = BlockchainKeyGenerator.getInstance().generate(); @@ -236,7 +261,7 @@ public class TransactionBatchProcessorTest { assertNotNull(tx3); assertEquals(TransactionState.SUCCESS, tx3.getExecutionState()); - LedgerDataSet ledgerDS = ledgerRepo.getDataSet(latestBlock); + LedgerDataQuery ledgerDS = ledgerRepo.getDataSet(latestBlock); boolean existUser1 = ledgerDS.getUserAccountSet().contains(userKeypair1.getAddress()); boolean existUser2 = ledgerDS.getUserAccountSet().contains(userKeypair2.getAddress()); boolean existUser3 = ledgerDS.getUserAccountSet().contains(userKeypair3.getAddress()); @@ -257,7 +282,7 @@ public class TransactionBatchProcessorTest { LedgerRepository ledgerRepo = ledgerManager.register(ledgerHash, STORAGE); // 验证参与方账户的存在; - LedgerDataSet previousBlockDataset = ledgerRepo.getDataSet(ledgerRepo.getLatestBlock()); + LedgerDataQuery previousBlockDataset = ledgerRepo.getDataSet(ledgerRepo.getLatestBlock()); UserAccount user0 = previousBlockDataset.getUserAccountSet().getUser(parti0.getAddress()); assertNotNull(user0); boolean partiRegistered = previousBlockDataset.getUserAccountSet().contains(parti0.getAddress()); @@ -268,8 +293,9 @@ public class TransactionBatchProcessorTest { LedgerEditor newBlockEditor = ledgerRepo.createNextBlock(); OperationHandleRegisteration opReg = new DefaultOperationHandleRegisteration(); - TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(newBlockEditor, previousBlockDataset, - opReg, ledgerManager); + LedgerSecurityManager securityManager = getSecurityManager(); + TransactionBatchProcessor txbatchProcessor = new TransactionBatchProcessor(securityManager, newBlockEditor, + previousBlockDataset, opReg, ledgerManager); BlockchainKeypair dataAccountKeypair = BlockchainKeyGenerator.getInstance().generate(); TransactionRequest transactionRequest1 = LedgerTestUtils.createTxRequest_DataAccountReg(dataAccountKeypair, @@ -296,7 +322,8 @@ public class TransactionBatchProcessorTest { newBlockEditor = ledgerRepo.createNextBlock(); previousBlockDataset = ledgerRepo.getDataSet(ledgerRepo.getLatestBlock()); - txbatchProcessor = new TransactionBatchProcessor(newBlockEditor, previousBlockDataset, opReg, ledgerManager); + txbatchProcessor = new TransactionBatchProcessor(securityManager, newBlockEditor, previousBlockDataset, opReg, + ledgerManager); txbatchProcessor.schedule(txreq1); txbatchProcessor.schedule(txreq2); @@ -335,7 +362,8 @@ public class TransactionBatchProcessorTest { newBlockEditor = ledgerRepo.createNextBlock(); previousBlockDataset = ledgerRepo.getDataSet(ledgerRepo.getLatestBlock()); - txbatchProcessor = new TransactionBatchProcessor(newBlockEditor, previousBlockDataset, opReg, ledgerManager); + txbatchProcessor = new TransactionBatchProcessor(securityManager, newBlockEditor, previousBlockDataset, opReg, + ledgerManager); txbatchProcessor.schedule(txreq5); // 预期会产生版本冲突异常; DataVersionConflictionException; @@ -392,7 +420,7 @@ public class TransactionBatchProcessorTest { TransactionRequest genesisTxReq = LedgerTestUtils.createLedgerInitTxRequest(partiKeys); LedgerTransactionContext genisisTxCtx = ldgEdt.newTransaction(genesisTxReq); - LedgerDataSet ldgDS = genisisTxCtx.getDataSet(); + LedgerDataset ldgDS = genisisTxCtx.getDataset(); for (int i = 0; i < partiKeys.length; i++) { UserAccount userAccount = ldgDS.getUserAccountSet().register(partiKeys[i].getAddress(), diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/TransactionSetTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TransactionSetTest.java similarity index 98% rename from source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/TransactionSetTest.java rename to source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TransactionSetTest.java index bb7cec55..7f8d73d5 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/TransactionSetTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TransactionSetTest.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger; +package test.com.jd.blockchain.ledger.core; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -16,9 +16,9 @@ import com.jd.blockchain.binaryproto.BinaryProtocol; import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.crypto.HashDigest; import com.jd.blockchain.ledger.DataAccountKVSetOperation.KVWriteEntry; +import com.jd.blockchain.ledger.core.LedgerTransactionData; import com.jd.blockchain.ledger.core.TransactionSet; -import com.jd.blockchain.ledger.core.impl.LedgerTransactionData; -import com.jd.blockchain.ledger.core.impl.TransactionStagedSnapshot; +import com.jd.blockchain.ledger.core.TransactionStagedSnapshot; import com.jd.blockchain.storage.service.utils.MemoryKVStorage; import com.jd.blockchain.transaction.TxBuilder; import com.jd.blockchain.utils.io.BytesUtils; diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/TransactionStagedSnapshotTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TransactionStagedSnapshotTest.java similarity index 94% rename from source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/TransactionStagedSnapshotTest.java rename to source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TransactionStagedSnapshotTest.java index 3693f60d..9eebeafd 100644 --- a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/TransactionStagedSnapshotTest.java +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/TransactionStagedSnapshotTest.java @@ -6,7 +6,7 @@ * Date: 2018/8/30 上午10:49 * Description: */ -package test.com.jd.blockchain.ledger; +package test.com.jd.blockchain.ledger.core; import static org.junit.Assert.assertEquals; @@ -18,7 +18,7 @@ import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.crypto.HashDigest; import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; import com.jd.blockchain.ledger.LedgerDataSnapshot; -import com.jd.blockchain.ledger.core.impl.TransactionStagedSnapshot; +import com.jd.blockchain.ledger.core.TransactionStagedSnapshot; /** * diff --git a/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/UserRoleDatasetTest.java b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/UserRoleDatasetTest.java new file mode 100644 index 00000000..44046ee6 --- /dev/null +++ b/source/ledger/ledger-core/src/test/java/test/com/jd/blockchain/ledger/core/UserRoleDatasetTest.java @@ -0,0 +1,62 @@ +package test.com.jd.blockchain.ledger.core; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; + +import com.jd.blockchain.crypto.Crypto; +import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.CryptoProvider; +import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; +import com.jd.blockchain.crypto.service.sm.SMCryptoService; +import com.jd.blockchain.ledger.BlockchainKeyGenerator; +import com.jd.blockchain.ledger.BlockchainKeypair; +import com.jd.blockchain.ledger.RolesPolicy; +import com.jd.blockchain.ledger.UserRoles; +import com.jd.blockchain.ledger.core.CryptoConfig; +import com.jd.blockchain.ledger.core.UserRoleDataset; +import com.jd.blockchain.storage.service.utils.MemoryKVStorage; + +public class UserRoleDatasetTest { + + private static final String[] SUPPORTED_PROVIDER_NAMES = { ClassicCryptoService.class.getName(), + SMCryptoService.class.getName() }; + + private static final CryptoAlgorithm HASH_ALGORITHM = Crypto.getAlgorithm("SHA256"); + + private static final CryptoProvider[] SUPPORTED_PROVIDERS = new CryptoProvider[SUPPORTED_PROVIDER_NAMES.length]; + static { + for (int i = 0; i < SUPPORTED_PROVIDER_NAMES.length; i++) { + SUPPORTED_PROVIDERS[i] = Crypto.getProvider(SUPPORTED_PROVIDER_NAMES[i]); + } + } + + @Test + public void testAddUserRoles() { + CryptoConfig cryptoConfig = new CryptoConfig(); + cryptoConfig.setAutoVerifyHash(true); + cryptoConfig.setSupportedProviders(SUPPORTED_PROVIDERS); + cryptoConfig.setHashAlgorithm(HASH_ALGORITHM); + + MemoryKVStorage testStorage = new MemoryKVStorage(); + String prefix = "user-roles/"; + UserRoleDataset userRolesDataset = new UserRoleDataset(cryptoConfig, prefix, testStorage, testStorage); + + BlockchainKeypair bckp = BlockchainKeyGenerator.getInstance().generate(); + String[] authRoles = { "DEFAULT", "MANAGER" }; + userRolesDataset.addUserRoles(bckp.getAddress(), RolesPolicy.UNION, authRoles); + + userRolesDataset.commit(); + + assertEquals(1, userRolesDataset.getUserCount()); + UserRoles userRoles = userRolesDataset.getUserRoles(bckp.getAddress()); + assertNotNull(userRoles); + String[] roles = userRoles.getRoles(); + assertEquals(2, roles.length); + assertArrayEquals(authRoles, roles); + assertEquals(RolesPolicy.UNION, userRoles.getPolicy()); + } + +} diff --git a/source/ledger/ledger-core/src/test/resources/logback-test.xml b/source/ledger/ledger-core/src/test/resources/logback-test.xml new file mode 100644 index 00000000..29013782 --- /dev/null +++ b/source/ledger/ledger-core/src/test/resources/logback-test.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/AuthorizationException.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/AuthorizationException.java new file mode 100644 index 00000000..94a374a8 --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/AuthorizationException.java @@ -0,0 +1,17 @@ +package com.jd.blockchain.ledger; + +public class AuthorizationException extends LedgerException { + + private static final long serialVersionUID = -4418553411943356320L; + + + + public AuthorizationException(String message) { + super(message); + } + + public AuthorizationException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerAdminInfo.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerAdminInfo.java new file mode 100644 index 00000000..b666535e --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerAdminInfo.java @@ -0,0 +1,17 @@ +package com.jd.blockchain.ledger; + +public interface LedgerAdminInfo { + + LedgerMetadata_V2 getMetadata(); + + LedgerSettings getSettings(); + + long getParticipantCount(); + + ParticipantNode[] getParticipants(); + + UserRolesSettings getUserRoles(); + + RolePrivilegeSettings getRolePrivileges(); + +} \ No newline at end of file diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitException.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitException.java similarity index 75% rename from source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitException.java rename to source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitException.java index 3695a19e..c3a31079 100644 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitException.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitException.java @@ -1,6 +1,4 @@ -package com.jd.blockchain.tools.initializer; - -import com.jd.blockchain.ledger.LedgerException; +package com.jd.blockchain.ledger; public class LedgerInitException extends LedgerException{ diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitProperties.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitProperties.java similarity index 52% rename from source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitProperties.java rename to source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitProperties.java index f1d0c93b..ad946049 100644 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitProperties.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerInitProperties.java @@ -1,4 +1,4 @@ -package com.jd.blockchain.tools.initializer; +package com.jd.blockchain.ledger; import java.io.File; import java.io.FileNotFoundException; @@ -7,15 +7,19 @@ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Properties; +import java.util.TreeMap; import com.jd.blockchain.consts.Global; import com.jd.blockchain.crypto.AddressEncoding; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.ParticipantNode; +import com.jd.blockchain.ledger.LedgerInitProperties.CryptoProperties; import com.jd.blockchain.ledger.ParticipantNodeState; -import com.jd.blockchain.tools.keygen.KeyGenCommand; +import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.PropertiesUtils; +import com.jd.blockchain.utils.StringUtils; import com.jd.blockchain.utils.codec.HexUtils; import com.jd.blockchain.utils.io.FileUtils; import com.jd.blockchain.utils.net.NetworkAddress; @@ -33,6 +37,13 @@ public class LedgerInitProperties { // 创建时间的格式; public static final String CREATED_TIME_FORMAT = Global.DEFAULT_TIME_FORMAT; + // 角色清单; + public static final String ROLES = "security.roles"; + // 角色的账本权限;用角色名称替代占位符; + public static final String ROLE_LEDGER_PRIVILEGES_PATTERN = "security.role.%s.ledger-privileges"; + // 角色的交易权限;用角色名称替代占位符; + public static final String ROLE_TX_PRIVILEGES_PATTERN = "security.role.%s.tx-privileges"; + // 共识参与方的个数,后续以 part.id 分别标识每一个参与方的配置; public static final String PART_COUNT = "cons_parti.count"; // 共识参与方的名称的模式; @@ -43,6 +54,10 @@ public class LedgerInitProperties { public static final String PART_PUBKEY_PATH = "pubkey-path"; // 参与方的公钥文件路径; public static final String PART_PUBKEY = "pubkey"; + // 参与方的角色清单; + public static final String PART_ROLES = "roles"; + // 参与方的角色权限策略; + public static final String PART_ROLES_POLICY = "roles-policy"; // 共识参与方的账本初始服务的主机; public static final String PART_INITIALIZER_HOST = "initializer.host"; @@ -59,6 +74,10 @@ public class LedgerInitProperties { // 密码服务提供者列表,以英文逗点“,”分隔;必须; public static final String CRYPTO_SERVICE_PROVIDERS = "crypto.service-providers"; + // 从存储中加载账本数据时,是否校验哈希;可选; + public static final String CRYPTO_VRIFY_HASH = "crypto.verify-hash"; + // 哈希算法; + public static final String CRYPTO_HASH_ALGORITHM = "crypto.hash-algorithm"; public static final String CRYPTO_SERVICE_PROVIDERS_SPLITTER = ","; @@ -66,13 +85,17 @@ public class LedgerInitProperties { private String ledgerName; - private List consensusParticipants = new ArrayList<>(); + private RoleInitData[] roles; + + private List consensusParticipants = new ArrayList<>(); private String consensusProvider; private Properties consensusConfig; - private String[] cryptoProviders; +// private String[] cryptoProviders; + + private CryptoProperties cryptoProperties = new CryptoProperties(); private long createdTime; @@ -100,7 +123,7 @@ public class LedgerInitProperties { return consensusParticipants.size(); } - public List getConsensusParticipants() { + public List getConsensusParticipants() { return consensusParticipants; } @@ -112,12 +135,15 @@ public class LedgerInitProperties { return consensusParticipants.toArray(participantNodes); } - public String[] getCryptoProviders() { - return cryptoProviders.clone(); + public CryptoProperties getCryptoProperties() { + return cryptoProperties; } - public void setCryptoProviders(String[] cryptoProviders) { - this.cryptoProviders = cryptoProviders; + public void setCryptoProperties(CryptoProperties cryptoProperties) { + if (cryptoProperties == null) { + cryptoProperties = new CryptoProperties(); + } + this.cryptoProperties = cryptoProperties; } /** @@ -126,8 +152,8 @@ public class LedgerInitProperties { * @param id 从 1 开始; 小于等于 {@link #getConsensusParticipantCount()}; * @return */ - public ConsensusParticipantConfig getConsensusParticipant(int id) { - for (ConsensusParticipantConfig p : consensusParticipants) { + public ParticipantProperties getConsensusParticipant(int id) { + for (ParticipantProperties p : consensusParticipants) { if (p.getId() == id) { return p; } @@ -135,15 +161,20 @@ public class LedgerInitProperties { return null; } + /** + * 私有的构造器; + * + * @param ledgerSeed + */ private LedgerInitProperties(byte[] ledgerSeed) { this.ledgerSeed = ledgerSeed; } - public void addConsensusParticipant(ConsensusParticipantConfig participant) { + public void addConsensusParticipant(ParticipantProperties participant) { consensusParticipants.add(participant); } - private static String getKeyOfCsParti(int partId, String partPropKey) { + private static String getKeyOfParticipant(int partId, String partPropKey) { String partAddrStr = String.format(PART_ID_PATTERN, partId); return String.format("%s.%s", partAddrStr, partPropKey); } @@ -162,12 +193,20 @@ public class LedgerInitProperties { public static LedgerInitProperties resolve(Properties props) { return resolve(null, props); } - - public static LedgerInitProperties resolve(String dir, Properties props) { + + /** + * 从属性表解析账本初始化参数; + * + * @param baseDirectory 基础路径;属性中涉及文件位置的相对路径以此参数指定的目录为父目录; + * @param props 要解析的属性表; + * @return + */ + public static LedgerInitProperties resolve(String baseDirectory, Properties props) { String hexLedgerSeed = PropertiesUtils.getRequiredProperty(props, LEDGER_SEED).replace("-", ""); byte[] ledgerSeed = HexUtils.decode(hexLedgerSeed); LedgerInitProperties initProps = new LedgerInitProperties(ledgerSeed); + // 解析账本信息; // 账本名称 String ledgerName = PropertiesUtils.getRequiredProperty(props, LEDGER_NAME); initProps.ledgerName = ledgerName; @@ -180,11 +219,35 @@ public class LedgerInitProperties { throw new IllegalArgumentException(ex.getMessage(), ex); } + // 解析角色清单; + String strRoleNames = PropertiesUtils.getOptionalProperty(props, ROLES); + String[] roles = StringUtils.splitToArray(strRoleNames, ","); + + Map rolesInitSettingMap = new TreeMap(); + // 解析角色权限表; + for (String role : roles) { + String ledgerPrivilegeKey = getKeyOfRoleLedgerPrivilege(role); + String strLedgerPermissions = PropertiesUtils.getOptionalProperty(props, ledgerPrivilegeKey); + LedgerPermission[] ledgerPermissions = resolveLedgerPermissions(strLedgerPermissions); + + String txPrivilegeKey = getKeyOfRoleTxPrivilege(role); + String strTxPermissions = PropertiesUtils.getOptionalProperty(props, txPrivilegeKey); + TransactionPermission[] txPermissions = resolveTransactionPermissions(strTxPermissions); + + if (ledgerPermissions.length > 0 || txPermissions.length > 0) { + RoleInitData rolesSettings = new RoleInitData(role, ledgerPermissions, txPermissions); + rolesInitSettingMap.put(role, rolesSettings); + } + } + RoleInitData[] rolesInitDatas = rolesInitSettingMap.values() + .toArray(new RoleInitData[rolesInitSettingMap.size()]); + initProps.setRoles(rolesInitDatas); + // 解析共识相关的属性; initProps.consensusProvider = PropertiesUtils.getRequiredProperty(props, CONSENSUS_SERVICE_PROVIDER); String consensusConfigFilePath = PropertiesUtils.getRequiredProperty(props, CONSENSUS_CONFIG); try { - File consensusConfigFile = FileUtils.getFile(dir, consensusConfigFilePath); + File consensusConfigFile = FileUtils.getFile(baseDirectory, consensusConfigFilePath); initProps.consensusConfig = FileUtils.readProperties(consensusConfigFile); } catch (FileNotFoundException e) { throw new IllegalArgumentException( @@ -197,7 +260,14 @@ public class LedgerInitProperties { for (int i = 0; i < cryptoProviders.length; i++) { cryptoProviders[i] = cryptoProviders[i].trim(); } - initProps.cryptoProviders = cryptoProviders; + initProps.cryptoProperties.setProviders(cryptoProviders); + // 哈希校验选项; + boolean verifyHash = PropertiesUtils.getBooleanOptional(props, CRYPTO_VRIFY_HASH, false); + initProps.cryptoProperties.setVerifyHash(verifyHash); + // 哈希算法; + String hashAlgorithm = PropertiesUtils.getOptionalProperty(props, CRYPTO_HASH_ALGORITHM); + initProps.cryptoProperties.setHashAlgorithm(hashAlgorithm); + // 解析参与方节点列表; int partCount = getInt(PropertiesUtils.getRequiredProperty(props, PART_COUNT)); @@ -208,36 +278,50 @@ public class LedgerInitProperties { throw new IllegalArgumentException(String.format("Property[%s] is less than 4!", PART_COUNT)); } for (int i = 0; i < partCount; i++) { - ConsensusParticipantConfig parti = new ConsensusParticipantConfig(); + ParticipantProperties parti = new ParticipantProperties(); parti.setId(i); - String nameKey = getKeyOfCsParti(i, PART_NAME); + String nameKey = getKeyOfParticipant(i, PART_NAME); parti.setName(PropertiesUtils.getRequiredProperty(props, nameKey)); - String pubkeyPathKey = getKeyOfCsParti(i, PART_PUBKEY_PATH); + String pubkeyPathKey = getKeyOfParticipant(i, PART_PUBKEY_PATH); String pubkeyPath = PropertiesUtils.getProperty(props, pubkeyPathKey, false); - String pubkeyKey = getKeyOfCsParti(i, PART_PUBKEY); + String pubkeyKey = getKeyOfParticipant(i, PART_PUBKEY); String base58PubKey = PropertiesUtils.getProperty(props, pubkeyKey, false); if (base58PubKey != null) { - PubKey pubKey = KeyGenCommand.decodePubKey(base58PubKey); + PubKey pubKey = KeyGenUtils.decodePubKey(base58PubKey); parti.setPubKey(pubKey); } else if (pubkeyPath != null) { - PubKey pubKey = KeyGenCommand.readPubKey(pubkeyPath); + PubKey pubKey = KeyGenUtils.readPubKey(pubkeyPath); parti.setPubKey(pubKey); } else { throw new IllegalArgumentException( String.format("Property[%s] and property[%s] are all empty!", pubkeyKey, pubkeyPathKey)); } - String initializerHostKey = getKeyOfCsParti(i, PART_INITIALIZER_HOST); + // 解析参与方的角色权限配置; + String partiRolesKey = getKeyOfParticipant(i, PART_ROLES); + String strPartiRoles = PropertiesUtils.getOptionalProperty(props, partiRolesKey); + String[] partiRoles = StringUtils.splitToArray(strPartiRoles, ","); + parti.setRoles(partiRoles); + + String partiRolePolicyKey = getKeyOfParticipant(i, PART_ROLES_POLICY); + String strPartiPolicy = PropertiesUtils.getOptionalProperty(props, partiRolePolicyKey); + RolesPolicy policy = strPartiPolicy == null ? RolesPolicy.UNION + : RolesPolicy.valueOf(strPartiPolicy.trim()); + policy = policy == null ? RolesPolicy.UNION : policy; + parti.setRolesPolicy(policy); + + // 解析参与方的网络配置参数; + String initializerHostKey = getKeyOfParticipant(i, PART_INITIALIZER_HOST); String initializerHost = PropertiesUtils.getRequiredProperty(props, initializerHostKey); - String initializerPortKey = getKeyOfCsParti(i, PART_INITIALIZER_PORT); + String initializerPortKey = getKeyOfParticipant(i, PART_INITIALIZER_PORT); int initializerPort = getInt(PropertiesUtils.getRequiredProperty(props, initializerPortKey)); - String initializerSecureKey = getKeyOfCsParti(i, PART_INITIALIZER_SECURE); + String initializerSecureKey = getKeyOfParticipant(i, PART_INITIALIZER_SECURE); boolean initializerSecure = Boolean .parseBoolean(PropertiesUtils.getRequiredProperty(props, initializerSecureKey)); NetworkAddress initializerAddress = new NetworkAddress(initializerHost, initializerPort, initializerSecure); @@ -249,28 +333,108 @@ public class LedgerInitProperties { return initProps; } + private static TransactionPermission[] resolveTransactionPermissions(String strTxPermissions) { + String[] strPermissions = StringUtils.splitToArray(strTxPermissions, ","); + List permissions = new ArrayList(); + if (strPermissions != null) { + for (String pm : strPermissions) { + TransactionPermission permission = TransactionPermission.valueOf(pm); + if (permission != null) { + permissions.add(permission); + } + } + } + return permissions.toArray(new TransactionPermission[permissions.size()]); + } + + private static LedgerPermission[] resolveLedgerPermissions(String strLedgerPermissions) { + String[] strPermissions = StringUtils.splitToArray(strLedgerPermissions, ","); + List permissions = new ArrayList(); + if (strPermissions != null) { + for (String pm : strPermissions) { + LedgerPermission permission = LedgerPermission.valueOf(pm); + if (permission != null) { + permissions.add(permission); + } + } + } + return permissions.toArray(new LedgerPermission[permissions.size()]); + } + + private static String getKeyOfRoleLedgerPrivilege(String role) { + return String.format(ROLE_LEDGER_PRIVILEGES_PATTERN, role); + } + + private static String getKeyOfRoleTxPrivilege(String role) { + return String.format(ROLE_TX_PRIVILEGES_PATTERN, role); + } + private static int getInt(String strInt) { return Integer.parseInt(strInt.trim()); } + public RoleInitData[] getRoles() { + return roles; + } + + public void setRoles(RoleInitData[] roles) { + this.roles = roles; + } + + public static class CryptoProperties { + + private String[] providers; + + private boolean verifyHash; + + private String hashAlgorithm; + + public String[] getProviders() { + return providers; + } + + public void setProviders(String[] providers) { + this.providers = providers; + } + + public boolean isVerifyHash() { + return verifyHash; + } + + public void setVerifyHash(boolean verifyHash) { + this.verifyHash = verifyHash; + } + + public String getHashAlgorithm() { + return hashAlgorithm; + } + + public void setHashAlgorithm(String hashAlgorithm) { + this.hashAlgorithm = hashAlgorithm; + } + + } + /** * 参与方配置信息; * * @author huanghaiquan * */ - public static class ConsensusParticipantConfig implements ParticipantNode { + public static class ParticipantProperties implements ParticipantNode { private int id; - private String address; + private Bytes address; private String name; -// private String pubKeyPath; - private PubKey pubKey; + private String[] roles; + + private RolesPolicy rolesPolicy; + // private NetworkAddress consensusAddress; private ParticipantNodeState participantNodeState; @@ -286,7 +450,7 @@ public class LedgerInitProperties { } @Override - public String getAddress() { + public Bytes getAddress() { return address; } @@ -328,7 +492,23 @@ public class LedgerInitProperties { public void setPubKey(PubKey pubKey) { this.pubKey = pubKey; - this.address = AddressEncoding.generateAddress(pubKey).toBase58(); + this.address = AddressEncoding.generateAddress(pubKey); + } + + public String[] getRoles() { + return roles; + } + + public void setRoles(String[] roles) { + this.roles = roles; + } + + public RolesPolicy getRolesPolicy() { + return rolesPolicy; + } + + public void setRolesPolicy(RolesPolicy rolesPolicy) { + this.rolesPolicy = rolesPolicy; } } diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerMetadata.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerMetadata.java index 4d7a57b0..f7108ff3 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerMetadata.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerMetadata.java @@ -6,31 +6,37 @@ import com.jd.blockchain.binaryproto.PrimitiveType; import com.jd.blockchain.consts.DataCodes; import com.jd.blockchain.crypto.HashDigest; -@DataContract(code = DataCodes.METADATA) +/** + * 账本的元数据; + * + * @author huanghaiquan + * + */ +@DataContract(code = DataCodes.METADATA, name = "LEDGER-METADATA") public interface LedgerMetadata { - /** - * 账本的初始化种子; - * - * @return - */ - @DataField(order = 1, primitiveType = PrimitiveType.BYTES) - byte[] getSeed(); + /** + * 账本的初始化种子; + * + * @return + */ + @DataField(order = 1, primitiveType = PrimitiveType.BYTES) + byte[] getSeed(); - /** - * 共识参与方的默克尔树的根; - * - * @return - */ - @DataField(order = 2, primitiveType = PrimitiveType.BYTES) - HashDigest getParticipantsHash(); + /** + * 共识参与方的默克尔树的根; + * + * @return + */ + @DataField(order = 2, primitiveType = PrimitiveType.BYTES) + HashDigest getParticipantsHash(); - /** - * 账本配置; - * - * @return - */ - @DataField(order = 3, refContract = true) - LedgerSetting getSetting(); + /** + * 账本配置的哈希; + * + * @return + */ + @DataField(order = 3, primitiveType = PrimitiveType.BYTES) + HashDigest getSettingsHash(); } diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerMetadata_V2.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerMetadata_V2.java new file mode 100644 index 00000000..228019b7 --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerMetadata_V2.java @@ -0,0 +1,35 @@ +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 LedgerMetadata_V2} 是 {@link LedgerMetadata} 的升级版本,新增加了 + * {@link #getRolePrivilegesHash()} 属性; + * + * @author huanghaiquan + * + */ +@DataContract(code = DataCodes.METADATA_V2, name = "LEDGER-METADATA-V2") +public interface LedgerMetadata_V2 extends LedgerMetadata { + + /** + * 角色权限集合的根哈希;; + * + * @return + */ + @DataField(order = 4, primitiveType = PrimitiveType.BYTES) + HashDigest getRolePrivilegesHash(); + + /** + * 用户角色授权集合的根哈希; + * + * @return + */ + @DataField(order = 5, primitiveType = PrimitiveType.BYTES) + HashDigest getUserRolesHash(); + +} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerPermission.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerPermission.java new file mode 100644 index 00000000..a735a2da --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerPermission.java @@ -0,0 +1,97 @@ +package com.jd.blockchain.ledger; + +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_LEDGER_PERMISSION) +public enum LedgerPermission { + + /** + * 配置角色的权限;
+ */ + CONFIGURE_ROLES((byte) 0x01), + + /** + * 授权用户角色;
+ */ + AUTHORIZE_USER_ROLES((byte) 0x02), + + /** + * 设置共识协议;
+ */ + SET_CONSENSUS((byte) 0x03), + + /** + * 设置密码体系;
+ */ + SET_CRYPTO((byte) 0x04), + + /** + * 注册参与方;
+ */ + REGISTER_PARTICIPANT((byte) 0x05), + + /** + * 注册用户;
+ * + * 如果不具备此项权限,则无法注册用户; + */ + REGISTER_USER((byte) 0x11), + + /** + * 注册数据账户;
+ */ + REGISTER_DATA_ACCOUNT((byte) 0x12), + + /** + * 注册合约;
+ */ + REGISTER_CONTRACT((byte) 0x13), + + /** + * 升级合约 + */ + UPGRADE_CONTRACT((byte) 0x14), + + /** + * 设置用户属性;
+ */ + SET_USER_ATTRIBUTES((byte) 0x15), + + /** + * 写入数据账户;
+ */ + WRITE_DATA_ACCOUNT((byte) 0x16), + + /** + * 参与方核准交易;
+ * + * 如果不具备此项权限,则无法作为节点签署由终端提交的交易; + *

+ * 只对交易请求的节点签名列表{@link TransactionRequest#getNodeSignatures()}的用户产生影响; + */ + APPROVE_TX((byte) 0x0C), + + /** + * 参与方共识交易;
+ * + * 如果不具备此项权限,则无法作为共识节点接入并对交易进行共识; + */ + CONSENSUS_TX((byte) 0x0D); + + @EnumField(type = PrimitiveType.INT8) + public final byte CODE; + + private LedgerPermission(byte code) { + this.CODE = code; + } + +} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerPrivilege.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerPrivilege.java new file mode 100644 index 00000000..dad59a41 --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerPrivilege.java @@ -0,0 +1,29 @@ +package com.jd.blockchain.ledger; + +/** + * LedgerPrivilege 账本特权是授权给特定角色的权限代码序列; + * + * @author huanghaiquan + * + */ +public class LedgerPrivilege extends PrivilegeBitset { + + private static final CodeIndexer CODE_INDEXER = new LedgerPermissionCodeIndexer(); + + public LedgerPrivilege() { + super(CODE_INDEXER); + } + + public LedgerPrivilege(byte[] codeBytes) { + super(codeBytes, CODE_INDEXER); + } + + private static class LedgerPermissionCodeIndexer implements CodeIndexer { + + @Override + public int getCodeIndex(LedgerPermission permission) { + return permission.CODE & 0xFF; + } + + } +} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerSecurityException.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerSecurityException.java new file mode 100644 index 00000000..0b3e98a8 --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerSecurityException.java @@ -0,0 +1,17 @@ +package com.jd.blockchain.ledger; + +public class LedgerSecurityException extends RuntimeException { + + private static final long serialVersionUID = -4090881296855827888L; + + + + public LedgerSecurityException(String message) { + super(message); + } + + public LedgerSecurityException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerSetting.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerSettings.java similarity index 87% rename from source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerSetting.java rename to source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerSettings.java index 1a0441bd..fd77685a 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerSetting.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/LedgerSettings.java @@ -8,7 +8,7 @@ import com.jd.blockchain.ledger.CryptoSetting; import com.jd.blockchain.utils.Bytes; @DataContract(code = DataCodes.METADATA_LEDGER_SETTING) -public interface LedgerSetting { +public interface LedgerSettings { @DataField(order=0, primitiveType=PrimitiveType.TEXT) String getConsensusProvider(); @@ -19,6 +19,4 @@ public interface LedgerSetting { @DataField(order=2, refContract=true) CryptoSetting getCryptoSetting(); -// PrivilegeModelSetting getPrivilegesModelSetting(); - } \ No newline at end of file diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleDataNode.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/MerkleDataNode.java similarity index 78% rename from source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleDataNode.java rename to source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/MerkleDataNode.java index 63db9103..c2014877 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleDataNode.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/MerkleDataNode.java @@ -1,4 +1,4 @@ -package com.jd.blockchain.ledger.core; +package com.jd.blockchain.ledger; import com.jd.blockchain.utils.Bytes; diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleNode.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/MerkleNode.java similarity index 86% rename from source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleNode.java rename to source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/MerkleNode.java index 185d5403..b8eba626 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleNode.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/MerkleNode.java @@ -1,4 +1,4 @@ -package com.jd.blockchain.ledger.core; +package com.jd.blockchain.ledger; import com.jd.blockchain.crypto.HashDigest; diff --git a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleProof.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/MerkleProof.java similarity index 97% rename from source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleProof.java rename to source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/MerkleProof.java index db9fe2f4..1463f736 100644 --- a/source/ledger/ledger-core/src/main/java/com/jd/blockchain/ledger/core/MerkleProof.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/MerkleProof.java @@ -1,4 +1,4 @@ -package com.jd.blockchain.ledger.core; +package com.jd.blockchain.ledger; import com.jd.blockchain.crypto.HashDigest; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantDataQuery.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantDataQuery.java new file mode 100644 index 00000000..6ba0668e --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantDataQuery.java @@ -0,0 +1,29 @@ +package com.jd.blockchain.ledger; + +import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.utils.Bytes; + +public interface ParticipantDataQuery { + + HashDigest getRootHash(); + + MerkleProof getProof(Bytes key); + + long getParticipantCount(); + + boolean contains(Bytes address); + + /** + * 返回指定地址的参与方凭证; + * + *
+ * 如果不存在,则返回 null; + * + * @param address + * @return + */ + ParticipantNode getParticipant(Bytes address); + + ParticipantNode[] getParticipants(); + +} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantDoesNotExistException.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantDoesNotExistException.java new file mode 100644 index 00000000..54994dc7 --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantDoesNotExistException.java @@ -0,0 +1,15 @@ +package com.jd.blockchain.ledger; + +public class ParticipantDoesNotExistException extends LedgerException { + + private static final long serialVersionUID = 397450363050148898L; + + public ParticipantDoesNotExistException(String message) { + super(message); + } + + public ParticipantDoesNotExistException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantNode.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantNode.java index 82730bba..9be89492 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantNode.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/ParticipantNode.java @@ -5,6 +5,7 @@ import com.jd.blockchain.binaryproto.DataField; import com.jd.blockchain.binaryproto.PrimitiveType; import com.jd.blockchain.consts.DataCodes; import com.jd.blockchain.crypto.PubKey; +import com.jd.blockchain.utils.Bytes; /** * 参与方节点; @@ -13,7 +14,7 @@ import com.jd.blockchain.crypto.PubKey; * */ @DataContract(code = DataCodes.METADATA_CONSENSUS_PARTICIPANT) -public interface ParticipantNode {// extends ConsensusNode, ParticipantInfo { +public interface ParticipantNode { /** * 节点的顺序编号;
@@ -30,8 +31,8 @@ public interface ParticipantNode {// extends ConsensusNode, ParticipantInfo { * * @return */ - @DataField(order = 1, primitiveType = PrimitiveType.TEXT) - String getAddress(); + @DataField(order = 1, primitiveType = PrimitiveType.BYTES) + Bytes getAddress(); /** * 参与者名称; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Privilege.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Privilege.java new file mode 100644 index 00000000..4a77e0b9 --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Privilege.java @@ -0,0 +1,5 @@ +package com.jd.blockchain.ledger; + +public interface Privilege> { + +} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/PrivilegeBitset.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/PrivilegeBitset.java new file mode 100644 index 00000000..1282530d --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/PrivilegeBitset.java @@ -0,0 +1,148 @@ +package com.jd.blockchain.ledger; + +import java.util.BitSet; + +import com.jd.blockchain.utils.io.BytesSerializable; + +/** + * PrivilegeBitset 定义了用位表示的权限码; + * + * @author huanghaiquan + * + */ +public class PrivilegeBitset> implements Privilege, BytesSerializable { + // 加入前缀位,可避免序列化时输出空的字节数组; + private static final boolean[] PREFIX = { false, false, false, true, false, false, false, true }; + private static final int OFFSET = PREFIX.length; + private static final int MAX_SIZE = 256 - PREFIX.length; + + private BitSet permissionBits; + + private CodeIndexer codeIndexer; + + public PrivilegeBitset(CodeIndexer codeIndexer) { + this.permissionBits = new BitSet(); + this.codeIndexer = codeIndexer; + // 设置前缀; + for (int i = 0; i < PREFIX.length; i++) { + permissionBits.set(i, PREFIX[i]); + } + } + + public PrivilegeBitset(byte[] codeBytes, CodeIndexer codeIndexer) { + if (codeBytes.length > MAX_SIZE) { + throw new IllegalArgumentException( + "The size of code bytes specified to PrivilegeBitset exceed the max size[" + MAX_SIZE + "]!"); + } + this.permissionBits = BitSet.valueOf(codeBytes); + this.codeIndexer = codeIndexer; + // 校验前缀; + for (int i = 0; i < PREFIX.length; i++) { + if (permissionBits.get(i) != PREFIX[i]) { + throw new IllegalArgumentException("The code bytes is not match the privilege prefix code!"); + } + } + } + + private PrivilegeBitset(BitSet bits, CodeIndexer codeIndexer) { + this.permissionBits = bits; + this.codeIndexer = codeIndexer; + } + + public boolean isEnable(E permission) { + return permissionBits.get(index(permission)); + } + + public void enable(E permission) { + permissionBits.set(index(permission)); + } + + public void disable(E permission) { + permissionBits.clear(index(permission)); + } + + @SuppressWarnings("unchecked") + public void enable(E... permissions) { + for (E p : permissions) { + permissionBits.set(index(p)); + } + } + + @SuppressWarnings("unchecked") + public void disable(E... permissions) { + for (E p : permissions) { + permissionBits.clear(index(p)); + } + } + + @Override + public byte[] toBytes() { + return permissionBits.toByteArray(); + } + + /** + * 把指定的权限合并到当前的权限中;
+ * + * @param privileges + * @return + */ + @SuppressWarnings("unchecked") + public Privilege union(PrivilegeBitset... privileges) { + return union(privileges, 0, privileges.length); + } + + /** + * 把指定的权限合并到当前的权限中;
+ * + * @param privileges + * @param offset + * @param count + * @return + */ + public Privilege union(PrivilegeBitset[] privileges, int offset, int count) { + BitSet bits = this.permissionBits; + for (int i = 0; i < count; i++) { + bits.or(privileges[i + offset].permissionBits); + } + return this; + } + + /** + * 保留当前的权限与指定权限的共同生效的部分,同时清除其它的权限位;
+ * + * @param privileges + * @return + */ + @SuppressWarnings("unchecked") + public Privilege intersect(PrivilegeBitset... privileges) { + return intersect(privileges, 0, privileges.length); + } + + /** + * 保留当前的权限与指定权限的共同生效的部分,同时清除其它的权限位;
+ * + * @param privileges + * @param offset + * @param count + * @return + */ + public Privilege intersect(PrivilegeBitset[] privileges, int offset, int count) { + BitSet bits = this.permissionBits; + for (int i = 0; i < count; i++) { + bits.and(privileges[i + offset].permissionBits); + } + return this; + } + + public PrivilegeBitset clone() { + return new PrivilegeBitset((BitSet) permissionBits.clone(), codeIndexer); + } + + private int index(E permission) { + return OFFSET + codeIndexer.getCodeIndex(permission); + } + + static interface CodeIndexer> { + int getCodeIndex(E permission); + } +} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/PrivilegeSet.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/PrivilegeSet.java new file mode 100644 index 00000000..bf0d3da7 --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/PrivilegeSet.java @@ -0,0 +1,23 @@ +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.PRIVILEGE_SET, name = "PRIVILEGE-SET") +public interface PrivilegeSet { + + @DataField(order = 1, primitiveType = PrimitiveType.BYTES) + LedgerPrivilege getLedgerPrivilege(); + + @DataField(order = 2, primitiveType = PrimitiveType.BYTES) + TransactionPrivilege getTransactionPrivilege(); + +} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Privileges.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Privileges.java new file mode 100644 index 00000000..420cbf45 --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/Privileges.java @@ -0,0 +1,65 @@ +package com.jd.blockchain.ledger; + +public class Privileges implements PrivilegeSet { + + private LedgerPrivilege ledgerPrivilege; + + private TransactionPrivilege txPrivilege; + + protected Privileges() { + this.ledgerPrivilege = new LedgerPrivilege(); + this.txPrivilege = new TransactionPrivilege(); + } + + protected Privileges(PrivilegeSet privilege) { + this.ledgerPrivilege = privilege.getLedgerPrivilege(); + this.txPrivilege = privilege.getTransactionPrivilege(); + } + + protected Privileges(LedgerPrivilege ledgerPrivilege, TransactionPrivilege txPrivilege) { + this.ledgerPrivilege = ledgerPrivilege; + this.txPrivilege = txPrivilege; + } + + @Override + public LedgerPrivilege getLedgerPrivilege() { + return ledgerPrivilege; + } + + public void setLedgerPrivilege(LedgerPrivilege ledgerPrivilege) { + this.ledgerPrivilege = ledgerPrivilege; + } + + @Override + public TransactionPrivilege getTransactionPrivilege() { + return txPrivilege; + } + + public void setTransactionPrivilege(TransactionPrivilege txPrivilege) { + this.txPrivilege = txPrivilege; + } + + public static Privileges configure() { + return new Privileges(); + } + + public Privileges enable(LedgerPermission...ledgerPermissions) { + this.ledgerPrivilege.enable(ledgerPermissions); + return this; + } + + public Privileges disable(LedgerPermission...ledgerPermissions) { + this.ledgerPrivilege.disable(ledgerPermissions); + return this; + } + + public Privileges enable(TransactionPermission...transactionPermissions) { + this.txPrivilege.enable(transactionPermissions); + return this; + } + + public Privileges disable(TransactionPermission...transactionPermissions) { + this.txPrivilege.disable(transactionPermissions); + return this; + } +} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RoleInitData.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RoleInitData.java new file mode 100644 index 00000000..ea1822e2 --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RoleInitData.java @@ -0,0 +1,48 @@ +package com.jd.blockchain.ledger; + +public class RoleInitData implements RoleInitSettings { + + private String roleName; + + private LedgerPermission[] ledgerPermissions; + + private TransactionPermission[] transactionPermissions; + + public RoleInitData() { + } + + public RoleInitData(String roleName, LedgerPermission[] ledgerPermissions, + TransactionPermission[] transactionPermissions) { + this.roleName = roleName; + this.ledgerPermissions = ledgerPermissions; + this.transactionPermissions = transactionPermissions; + } + + @Override + public String getRoleName() { + return roleName; + } + + @Override + public LedgerPermission[] getLedgerPermissions() { + return ledgerPermissions; + } + + @Override + public TransactionPermission[] getTransactionPermissions() { + return transactionPermissions; + } + + public void setRoleName(String roleName) { + this.roleName = roleName; + } + + public void setLedgerPermissions(LedgerPermission[] ledgerPermissions) { + this.ledgerPermissions = ledgerPermissions; + } + + public void setTransactionPermissions(TransactionPermission[] transactionPermissions) { + this.transactionPermissions = transactionPermissions; + } + +} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RoleInitSettings.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RoleInitSettings.java new file mode 100644 index 00000000..71c6965b --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RoleInitSettings.java @@ -0,0 +1,41 @@ +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.SECURITY_ROLE_INIT_SETTING) +public interface RoleInitSettings { + + /** + * 角色名称; + * + * @return + */ + @DataField(order = 0, primitiveType = PrimitiveType.TEXT) + String getRoleName(); + + /** + * 角色的账本权限; + * + * @return + */ + @DataField(order = 1, refEnum = true, list = true) + LedgerPermission[] getLedgerPermissions(); + + /** + * 角色的交易权限; + * + * @return + */ + @DataField(order = 2, refEnum = true, list = true) + TransactionPermission[] getTransactionPermissions(); + +} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RolePrivilegeSettings.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RolePrivilegeSettings.java new file mode 100644 index 00000000..cdaa99e8 --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RolePrivilegeSettings.java @@ -0,0 +1,160 @@ +package com.jd.blockchain.ledger; + +public interface RolePrivilegeSettings { + + /** + * 角色名称的最大 Unicode 字符数; + */ + public static final int MAX_ROLE_NAME_LENGTH = 20; + + /** + * 角色的数量; + * + * @return + */ + long getRoleCount(); + + /** + * 查询角色权限; + * + *
+ * 如果不存在,则返回 null; + * + * @param address + * @return + */ + RolePrivileges getRolePrivilege(String roleName); + + /** + * 返回指定位置的角色权限; + * + * @param index + * @param count + * @return + */ + RolePrivileges[] getRolePrivileges(int index, int count); + + /** + * 返回所有的角色权限; + * + * @return + */ + RolePrivileges[] getRolePrivileges(); + + /** + * 是否只读; + * + * @return + */ + boolean isReadonly(); + + /** + * 加入新的角色权限;
+ * + * 如果指定的角色已经存在,则引发 {@link LedgerException} 异常; + * + * @param roleName 角色名称;不能超过 {@link #MAX_ROLE_NAME_LENGTH} 个 Unicode 字符; + * @param ledgerPrivilege + * @param txPrivilege + */ + long addRolePrivilege(String roleName, Privileges privileges); + + /** + * 加入新的角色权限;
+ * + * 如果指定的角色已经存在,则引发 {@link LedgerException} 异常; + * + * @param roleName 角色名称;不能超过 {@link #MAX_ROLE_NAME_LENGTH} 个 Unicode 字符; + * @param ledgerPrivilege + * @param txPrivilege + */ + long addRolePrivilege(String roleName, LedgerPrivilege ledgerPrivilege, TransactionPrivilege txPrivilege); + + /** + * 加入新的角色权限;
+ * + * 如果指定的角色已经存在,则引发 {@link LedgerException} 异常; + * + * @param roleName 角色名称;不能超过 {@link #MAX_ROLE_NAME_LENGTH} 个 Unicode + * 字符; + * @param ledgerPermissions 给角色授予的账本权限列表; + * @param txPermissions 给角色授予的交易权限列表; + * @return + */ + long addRolePrivilege(String roleName, LedgerPermission[] ledgerPermissions, TransactionPermission[] txPermissions); + + /** + * 更新角色权限;
+ * 如果指定的角色不存在,或者版本不匹配,则引发 {@link LedgerException} 异常; + * + * @param participant + */ + void updateRolePrivilege(RolePrivileges roleAuth); + + /** + * 授权角色指定的权限;
+ * 如果角色不存在,则返回 -1; + * + * @param roleName 角色; + * @param permissions 权限列表; + * @return + */ + long enablePermissions(String roleName, LedgerPermission... permissions); + + /** + * 授权角色指定的权限;
+ * 如果角色不存在,则返回 -1; + * + * @param roleName 角色; + * @param permissions 权限列表; + * @return + */ + long enablePermissions(String roleName, TransactionPermission... permissions); + + /** + * 禁止角色指定的权限;
+ * 如果角色不存在,则返回 -1; + * + * @param roleName 角色; + * @param permissions 权限列表; + * @return + */ + long disablePermissions(String roleName, LedgerPermission... permissions); + + /** + * 禁止角色指定的权限;
+ * 如果角色不存在,则返回 -1; + * + * @param roleName 角色; + * @param permissions 权限列表; + * @return + */ + long disablePermissions(String roleName, TransactionPermission... permissions); + + /** + * 授权角色指定的权限;
+ * 如果角色不存在,则返回 -1; + * + * @param roleName + * @param ledgerPermissions + * @param txPermissions + * @return + */ + long enablePermissions(String roleName, LedgerPermission[] ledgerPermissions, + TransactionPermission[] txPermissions); + + /** + * 禁用角色指定的权限;
+ * 如果角色不存在,则返回 -1; + * + * @param roleName + * @param ledgerPermissions + * @param txPermissions + * @return + */ + long disablePermissions(String roleName, LedgerPermission[] ledgerPermissions, + TransactionPermission[] txPermissions); + + boolean contains(String r); + +} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RolePrivileges.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RolePrivileges.java new file mode 100644 index 00000000..1b0b32ba --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RolePrivileges.java @@ -0,0 +1,41 @@ +package com.jd.blockchain.ledger; + +/** + * 对角色的授权; + * + * @author huanghaiquan + * + */ +public class RolePrivileges extends Privileges { + + private String roleName; + + private long version; + + public RolePrivileges(String roleName, long version) { + this.roleName = roleName; + this.version = version; + } + + public RolePrivileges(String roleName, long version, PrivilegeSet privilege) { + super(privilege); + this.roleName = roleName; + this.version = version; + } + + public RolePrivileges(String roleName, long version, LedgerPrivilege ledgerPrivilege, + TransactionPrivilege txPrivilege) { + super(ledgerPrivilege, txPrivilege); + this.roleName = roleName; + this.version = version; + } + + public String getRoleName() { + return roleName; + } + + public long getVersion() { + return version; + } + +} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RoleSet.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RoleSet.java new file mode 100644 index 00000000..a026c23f --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RoleSet.java @@ -0,0 +1,23 @@ +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.ROLE_SET) +public interface RoleSet { + + @DataField(order = 1, refEnum = true) + RolesPolicy getPolicy(); + + @DataField(order = 2, primitiveType = PrimitiveType.TEXT, list = true) + String[] getRoles(); + +} 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 new file mode 100644 index 00000000..1e448740 --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RolesConfigureOperation.java @@ -0,0 +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(); + + } +} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RolesPolicy.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RolesPolicy.java new file mode 100644 index 00000000..690d0be5 --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/RolesPolicy.java @@ -0,0 +1,40 @@ +package com.jd.blockchain.ledger; + +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_MULTI_ROLES_POLICY, name = "USER-ROLE-POLICY") +public enum RolesPolicy { + + /** + * 合并权限;
+ * + * 综合权限是所有角色权限的并集,即任何一个角色的权限都被继承; + */ + UNION((byte) 0), + + /** + * 交叉权限;
+ * + * 综合权限是所有角色权限的交集,即只有全部角色共同拥有的权限才会被继承; + */ + INTERSECT((byte) 1); + + @EnumField(type = PrimitiveType.INT8) + public final byte CODE; + + private RolesPolicy(byte code) { + this.CODE = code; + } + +} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/SecurityInitData.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/SecurityInitData.java new file mode 100644 index 00000000..626adef1 --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/SecurityInitData.java @@ -0,0 +1,54 @@ +package com.jd.blockchain.ledger; + +import java.util.LinkedHashMap; +import java.util.Map; + +import com.jd.blockchain.utils.Bytes; + +public class SecurityInitData implements SecurityInitSettings { + + private Map roles = new LinkedHashMap<>(); + + private Map userAuthentications = new LinkedHashMap<>(); + + @Override + public RoleInitData[] getRoles() { + return roles.values().toArray(new RoleInitData[roles.size()]); + } + + public int getRolesCount() { + return roles.size(); + } + + public void setRoles(RoleInitData[] roles) { + Map newRoles = new LinkedHashMap<>(); + for (RoleInitData r : roles) { + newRoles.put(r.getRoleName(), r); + } + this.roles = newRoles; + } + + public boolean containsRole(String roleName) { + return roles.containsKey(roleName); + } + + public void addRole(String roleName, LedgerPermission[] ledgerPermissions, + TransactionPermission[] transactionPermissions) { + RoleInitData roleInitData = new RoleInitData(roleName, ledgerPermissions, transactionPermissions); + roles.put(roleName, roleInitData); + } + + @Override + public UserAuthInitData[] getUserAuthorizations() { + return userAuthentications.values().toArray(new UserAuthInitData[userAuthentications.size()]); + } + + public void addUserAuthencation(Bytes address, String[] roles, RolesPolicy policy) { + UserAuthInitData userAuth = new UserAuthInitData(); + userAuth.setUserAddress(address); + userAuth.setRoles(roles); + userAuth.setPolicy(policy); + + userAuthentications.put(address, userAuth); + } +} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/SecurityInitSettings.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/SecurityInitSettings.java new file mode 100644 index 00000000..8ca64d79 --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/SecurityInitSettings.java @@ -0,0 +1,27 @@ +package com.jd.blockchain.ledger; + +import com.jd.blockchain.binaryproto.DataContract; +import com.jd.blockchain.binaryproto.DataField; +import com.jd.blockchain.consts.DataCodes; + +/** + * 安全权限的初始化; + * + * @author huanghaiquan + * + */ +@DataContract(code = DataCodes.SECURITY_INIT_SETTING) +public interface SecurityInitSettings { + + /** + * 角色列表; + * + * @return + */ + @DataField(order = 0, refContract = true, list = true) + RoleInitSettings[] getRoles(); + + @DataField(order = 1, refContract = true, list = true) + UserAuthInitSettings[] getUserAuthorizations(); + +} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/SecurityUtils.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/SecurityUtils.java new file mode 100644 index 00000000..b0175fc5 --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/SecurityUtils.java @@ -0,0 +1,28 @@ +package com.jd.blockchain.ledger; + +public class SecurityUtils { + + public static final int MAX_ROLE_NAMES = 20; + + /** + * 校验角色名称的有效性,并格式化角色名称:去掉两端空白字符,统一为大写字符; + * + * @param roleName + * @return + */ + public static String formatRoleName(String roleName) { + if (roleName == null) { + throw new IllegalArgumentException("Role name is empty!"); + } + roleName = roleName.trim(); + if (roleName.length() > MAX_ROLE_NAMES) { + throw new IllegalArgumentException("Role name exceeds max length!"); + } + if (roleName.length() == 0) { + throw new IllegalArgumentException("Role name is empty!"); + } + + return roleName.toUpperCase(); + } + +} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionPermission.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionPermission.java new file mode 100644 index 00000000..b197820e --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionPermission.java @@ -0,0 +1,34 @@ +package com.jd.blockchain.ledger; + +import com.jd.blockchain.binaryproto.EnumContract; +import com.jd.blockchain.binaryproto.EnumField; +import com.jd.blockchain.binaryproto.PrimitiveType; +import com.jd.blockchain.consts.DataCodes; + +/** + * TxPermission 交易权限表示一个用户可以发起的交易类型; + * + * @author huanghaiquan + * + */ +@EnumContract(code = DataCodes.ENUM_TX_PERMISSION) +public enum TransactionPermission { + + /** + * 交易中包含指令操作; + */ + DIRECT_OPERATION((byte) 0x01), + + /** + * 交易中包含合约操作; + */ + CONTRACT_OPERATION((byte) 0x02); + + @EnumField(type = PrimitiveType.INT8) + public final byte CODE; + + private TransactionPermission(byte code) { + this.CODE = code; + } + +} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionPrivilege.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionPrivilege.java new file mode 100644 index 00000000..755a75a7 --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionPrivilege.java @@ -0,0 +1,23 @@ +package com.jd.blockchain.ledger; + +public class TransactionPrivilege extends PrivilegeBitset { + + private static final CodeIndexer CODE_INDEXER = new TransactionPermissionCodeIndexer(); + + public TransactionPrivilege() { + super(CODE_INDEXER); + } + + public TransactionPrivilege(byte[] codeBytes) { + super(codeBytes, CODE_INDEXER); + } + + private static class TransactionPermissionCodeIndexer implements CodeIndexer { + + @Override + public int getCodeIndex(TransactionPermission permission) { + return permission.CODE & 0xFF; + } + + } +} 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 0818d865..87c445ad 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 @@ -60,7 +60,7 @@ public interface TransactionRequestBuilder extends HashObject { * Base64格式的签名摘要; * @return */ - void addEndpointSignature(DigitalSignature signature); + void addEndpointSignature(DigitalSignature... signature); /** * 加入签名; @@ -71,7 +71,7 @@ public interface TransactionRequestBuilder extends HashObject { * Base64格式的签名摘要; * @return */ - void addNodeSignature(DigitalSignature signature); + void addNodeSignature(DigitalSignature... signatures); /** * 生成交易请求; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionState.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionState.java index 55390655..029ccbab 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionState.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/TransactionState.java @@ -44,6 +44,16 @@ public enum TransactionState { */ DATA_VERSION_CONFLICT((byte) 0x05), + /** + * 参与方不存在; + */ + PARTICIPANT_DOES_NOT_EXIST((byte) 0x05), + + /** + * 被安全策略拒绝; + */ + REJECTED_BY_SECURITY_POLICY((byte) 0x10), + /** * 由于在错误的账本上执行交易而被丢弃; */ diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserAuthInitData.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserAuthInitData.java new file mode 100644 index 00000000..6866c991 --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserAuthInitData.java @@ -0,0 +1,40 @@ +package com.jd.blockchain.ledger; + +import com.jd.blockchain.utils.Bytes; + +public class UserAuthInitData implements UserAuthInitSettings { + + private Bytes userAddress; + + private String[] roles; + + private RolesPolicy policy; + + public void setUserAddress(Bytes userAddress) { + this.userAddress = userAddress; + } + + public void setRoles(String[] roles) { + this.roles = roles; + } + + public void setPolicy(RolesPolicy policy) { + this.policy = policy; + } + + @Override + public Bytes getUserAddress() { + return userAddress; + } + + @Override + public String[] getRoles() { + return roles; + } + + @Override + public RolesPolicy getPolicy() { + return policy; + } + +} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserAuthInitSettings.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserAuthInitSettings.java new file mode 100644 index 00000000..31a6033a --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserAuthInitSettings.java @@ -0,0 +1,21 @@ +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.SECURITY_USER_AUTH_INIT_SETTING) +public interface UserAuthInitSettings { + + @DataField(order = 1, primitiveType = PrimitiveType.BYTES) + Bytes getUserAddress(); + + @DataField(order = 2, primitiveType = PrimitiveType.TEXT, list = true) + String[] getRoles(); + + @DataField(order = 3, refEnum = true) + RolesPolicy getPolicy(); + +} 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 new file mode 100644 index 00000000..67e37e17 --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserAuthorizeOperation.java @@ -0,0 +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(); + + } +} 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 b9a92317..c6372b78 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,33 +1,29 @@ -//package com.jd.blockchain.ledger; -// -//import com.jd.blockchain.binaryproto.DataContract; -// -///** -// * @author huanghaiquan -// * -// */ -//@DataContract(code=LedgerCodes.TX_OP_USER_INFO_SET) -//public interface UserInfoSetOperation extends Operation { -// -// @Override -// default OperationType getType() { -// return OperationType.SET_USER_INFO; -// } -// -// String getUserAddress(); -// -// KVEntry[] getPropertiesWriteSet(); -// -// -// @DataContract(code=LedgerCodes.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 f325085e..caa642de 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 @@ -4,10 +4,10 @@ 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) +@DataContract(code = DataCodes.TX_OP_USER_REG) public interface UserRegisterOperation extends Operation { - - @DataField(order=2, refContract = true) - BlockchainIdentity getUserID(); + @DataField(order = 2, refContract = true) + BlockchainIdentity getUserID(); + } diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserRoles.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserRoles.java new file mode 100644 index 00000000..d73d67a2 --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserRoles.java @@ -0,0 +1,107 @@ +package com.jd.blockchain.ledger; + +import java.util.Collection; +import java.util.Set; +import java.util.TreeSet; + +import com.jd.blockchain.utils.Bytes; + +public class UserRoles implements RoleSet { + + private Bytes userAddress; + + private RolesPolicy policy; + + private Set roles; + + private long version; + + public UserRoles(Bytes userAddress, long version, RolesPolicy policy) { + this.userAddress = userAddress; + this.version = version; + this.policy = policy; + this.roles = new TreeSet(); + } + + public UserRoles(Bytes userAddress, long version, RoleSet roleSet) { + this.userAddress = userAddress; + this.version = version; + this.policy = roleSet.getPolicy(); + this.roles = initRoles(roleSet.getRoles()); + + } + + private Set initRoles(String[] roles) { + TreeSet roleset = new TreeSet(); + if (roles != null) { + for (String r : roles) { + roleset.add(r); + } + } + return roleset; + } + + public Bytes getUserAddress() { + return userAddress; + } + + @Override + public RolesPolicy getPolicy() { + return policy; + } + + public void setPolicy(RolesPolicy policy) { + this.policy = policy; + } + + public int getRoleCount() { + return roles.size(); + } + + @Override + public String[] getRoles() { + return roles.toArray(new String[roles.size()]); + } + + public long getVersion() { + return version; + } + + public void addRoles(String... roles) { + for (String r : roles) { + this.roles.add(r); + } + } + + public void addRoles(Collection roles) { + for (String r : roles) { + this.roles.add(r); + } + } + + public void removeRoles(String... roles) { + for (String r : roles) { + this.roles.remove(r); + } + } + + public void removeRoles(Collection roles) { + for (String r : roles) { + this.roles.remove(r); + } + } + + /** + * 设置角色集合;
+ * 注意,这不是追加;现有的不在参数指定范围的角色将被移除; + * + * @param roles + */ + public void setRoles(String[] roles) { + TreeSet rs = new TreeSet(); + for (String r : roles) { + rs.add(r); + } + this.roles = rs; + } +} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserRolesSettings.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserRolesSettings.java new file mode 100644 index 00000000..af822b82 --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/ledger/UserRolesSettings.java @@ -0,0 +1,87 @@ +package com.jd.blockchain.ledger; + +import java.util.Collection; + +import com.jd.blockchain.utils.Bytes; + +public interface UserRolesSettings { + + /** + * 单一用户可被授权的角色数量的最大值; + */ + public static final int MAX_ROLES_PER_USER = 20; + + /** + * 进行了授权的用户的数量; + * + * @return + */ + long getUserCount(); + + /** + * 查询角色授权; + * + *
+ * 如果不存在,则返回 null; + * + * @param address + * @return + */ + UserRoles getUserRoles(Bytes userAddress); + + /** + * 返回全部的用户授权; + * + * @return + */ + UserRoles[] getUserRoles(); + + /** + * 是否只读; + * + * @return + */ + boolean isReadonly(); + + /** + * 加入新的用户角色授权;
+ * + * 如果该用户的授权已经存在,则引发 {@link LedgerException} 异常; + * + * @param userAddress + * @param rolesPolicy + * @param roles + */ + void addUserRoles(Bytes userAddress, RolesPolicy rolesPolicy, String... roles); + + /** + * 加入新的用户角色授权;
+ * + * 如果该用户的授权已经存在,则引发 {@link LedgerException} 异常; + * + * @param userAddress + * @param rolesPolicy + * @param roles + */ + void addUserRoles(Bytes userAddress, RolesPolicy rolesPolicy, Collection roles); + + /** + * 更新用户角色授权;
+ * 如果指定用户的授权不存在,或者版本不匹配,则引发 {@link LedgerException} 异常; + * + * @param userRoles + */ + void updateUserRoles(UserRoles userRoles); + + /** + * 设置用户的角色;
+ * 如果用户的角色授权不存在,则创建新的授权; + * + * @param userAddress 用户; + * @param policy 角色策略; + * @param roles 角色列表; + * @return + */ + long setRoles(Bytes userAddress, RolesPolicy policy, String... roles); + +} \ No newline at end of file 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 df064ad8..317b6e85 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 @@ -12,6 +12,8 @@ import com.jd.blockchain.utils.Bytes; * */ 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(); @@ -22,6 +24,8 @@ public class BlockchainOperationFactory implements ClientOperator, LedgerInitOpe 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(); @@ -50,6 +54,11 @@ public class BlockchainOperationFactory implements ClientOperator, LedgerInitOpe public LedgerInitOperationBuilder ledgers() { return ledgerInitOpBuilder; } + + @Override + public SecurityOperationBuilder security() { + return securityOpBuilder; + } @Override public UserRegisterOperationBuilder users() { @@ -160,6 +169,23 @@ public class BlockchainOperationFactory implements ClientOperator, LedgerInitOpe } } + + 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 { 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 a9f47141..9710b50d 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,7 +1,21 @@ package com.jd.blockchain.transaction; +import org.springframework.cglib.core.Block; + import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.*; +import com.jd.blockchain.ledger.AccountHeader; +import com.jd.blockchain.ledger.ContractInfo; +import com.jd.blockchain.ledger.KVDataEntry; +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; /** * 区块链查询器; @@ -28,12 +42,20 @@ public interface BlockchainQueryService { */ LedgerInfo getLedger(HashDigest ledgerHash); - /** - * 返回当前账本的参与者信息列表 - * - * @param ledgerHash - * @return - */ + /** + * 获取账本信息; + * + * @param ledgerHash + * @return 账本对象;如果不存在,则返回 null; + */ + LedgerAdminInfo getLedgerAdminInfo(HashDigest ledgerHash); + + /** + * 返回当前账本的参与者信息列表 + * + * @param ledgerHash + * @return + */ ParticipantNode[] getConsensusParticipants(HashDigest ledgerHash); /** @@ -47,10 +69,8 @@ public interface BlockchainQueryService { /** * 返回指定账本序号的区块; * - * @param ledgerHash - * 账本hash; - * @param height - * 高度; + * @param ledgerHash 账本hash; + * @param height 高度; * @return */ LedgerBlock getBlock(HashDigest ledgerHash, long height); @@ -58,10 +78,8 @@ public interface BlockchainQueryService { /** * 返回指定区块hash的区块; * - * @param ledgerHash - * 账本hash; - * @param blockHash - * 区块hash; + * @param ledgerHash 账本hash; + * @param blockHash 区块hash; * @return */ LedgerBlock getBlock(HashDigest ledgerHash, HashDigest blockHash); @@ -84,125 +102,116 @@ public interface BlockchainQueryService { */ long getTransactionCount(HashDigest ledgerHash, HashDigest blockHash); - /** - * 返回当前账本的交易总数 - * - * @param ledgerHash - * @return - */ + /** + * 返回当前账本的交易总数 + * + * @param ledgerHash + * @return + */ long getTransactionTotalCount(HashDigest ledgerHash); - /** - * 返回指定高度的区块中记录的数据账户总数 - * - * @param ledgerHash - * @param height - * @return - */ + /** + * 返回指定高度的区块中记录的数据账户总数 + * + * @param ledgerHash + * @param height + * @return + */ long getDataAccountCount(HashDigest ledgerHash, long height); - /** - * 返回指定的区块中记录的数据账户总数 - * - * @param ledgerHash - * @param blockHash - * @return - */ + /** + * 返回指定的区块中记录的数据账户总数 + * + * @param ledgerHash + * @param blockHash + * @return + */ long getDataAccountCount(HashDigest ledgerHash, HashDigest blockHash); - /** - * 返回当前账本的数据账户总数 - * - * @param ledgerHash - * @return - */ - long getDataAccountTotalCount(HashDigest ledgerHash); - - /** - * 返回指定高度区块中的用户总数 - * - * @param ledgerHash - * @param height - * @return - */ + /** + * 返回当前账本的数据账户总数 + * + * @param ledgerHash + * @return + */ + long getDataAccountTotalCount(HashDigest ledgerHash); + + /** + * 返回指定高度区块中的用户总数 + * + * @param ledgerHash + * @param height + * @return + */ long getUserCount(HashDigest ledgerHash, long height); - /** - * 返回指定区块中的用户总数 - * - * @param ledgerHash - * @param blockHash - * @return - */ + /** + * 返回指定区块中的用户总数 + * + * @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 + * @return + */ + long getUserTotalCount(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); + long getContractCount(HashDigest ledgerHash, long height); /** - * 分页返回指定账本序号的区块中的交易列表; + * 返回指定区块中的合约总数 * * @param ledgerHash - * 账本hash; * @param blockHash - * 账本高度; - * @param fromIndex - * 开始的记录数; - * @param count - * 本次返回的记录数;
- * 如果参数值为 -1,则返回全部的记录;
- * 注:通过 {@link #getBlock(String, String)} 方法获得的区块信息中可以得到区块的总交易数 - * {@link Block#getTxCount()}; + * @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); @@ -210,21 +219,17 @@ public interface BlockchainQueryService { /** * 根据交易内容的哈希获取对应的交易记录; * - * @param ledgerHash - * 账本hash; - * @param contentHash - * 交易内容的hash,即交易的 {@link Transaction#getContentHash()} 属性的值; + * @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()} 属性的值; + * @param ledgerHash 账本hash; + * @param contentHash 交易内容的hash,即交易的 {@link Transaction#getContentHash()} 属性的值; * @return */ TransactionState getTransactionStateByContentHash(HashDigest ledgerHash, HashDigest contentHash); @@ -273,18 +278,13 @@ public interface BlockchainQueryService { long getDataEntriesTotalCount(HashDigest ledgerHash, String address); /** - * 返回数据账户中指定序号的最新值; - * 返回结果的顺序与指定的序号的顺序是一致的;
+ * 返回数据账户中指定序号的最新值; 返回结果的顺序与指定的序号的顺序是一致的;
* - * @param ledgerHash - * 账本hash; - * @param address - * 数据账户地址; - * @param fromIndex - * 开始的记录数; - * @param count - * 本次返回的记录数;
- * 如果参数值为 -1,则返回全部的记录;
+ * @param ledgerHash 账本hash; + * @param address 数据账户地址; + * @param fromIndex 开始的记录数; + * @param count 本次返回的记录数;
+ * 如果参数值为 -1,则返回全部的记录;
* @return */ KVDataEntry[] getDataEntries(HashDigest ledgerHash, String address, int fromIndex, int count); @@ -300,6 +300,7 @@ public interface BlockchainQueryService { /** * get users by ledgerHash and its range; + * * @param ledgerHash * @param fromIndex * @param count @@ -309,6 +310,7 @@ public interface BlockchainQueryService { /** * get data accounts by ledgerHash and its range; + * * @param ledgerHash * @param fromIndex * @param count @@ -318,6 +320,7 @@ public interface BlockchainQueryService { /** * get contract accounts by ledgerHash and its range; + * * @param ledgerHash * @param fromIndex * @param count diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ClientOperator.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ClientOperator.java index ac1dc9f7..724e8d8a 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ClientOperator.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ClientOperator.java @@ -6,6 +6,7 @@ package com.jd.blockchain.transaction; * @author huanghaiquan * */ -public interface ClientOperator extends UserOperator, DataAccountOperator, ContractOperator, EventOperator, ParticipantOperator, ParticipantStateOperator{ +public interface ClientOperator + extends SecurityOperator, UserOperator, DataAccountOperator, ContractOperator, EventOperator, ParticipantOperator, ParticipantStateOperator { } \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ConsensusParticipantData.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ConsensusParticipantData.java index 99a233ba..7b5cfd17 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ConsensusParticipantData.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/ConsensusParticipantData.java @@ -2,14 +2,15 @@ package com.jd.blockchain.transaction; import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.ledger.ParticipantNodeState; +import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.net.NetworkAddress; +import com.jd.blockchain.ledger.ParticipantNodeState; public class ConsensusParticipantData implements ParticipantNode { private int id; - private String address; + private Bytes address; private String name; @@ -52,11 +53,11 @@ public class ConsensusParticipantData implements ParticipantNode { this.pubKey = pubKey; } - public String getAddress() { + public Bytes getAddress() { return address; } - public void setAddress(String address) { + public void setAddress(Bytes address) { this.address = address; } diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LedgerInitSettingData.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LedgerInitData.java similarity index 89% rename from source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LedgerInitSettingData.java rename to source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LedgerInitData.java index a6f6045a..6de96680 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LedgerInitSettingData.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/LedgerInitData.java @@ -1,22 +1,22 @@ package com.jd.blockchain.transaction; -import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.ledger.CryptoSetting; import com.jd.blockchain.ledger.LedgerInitSetting; +import com.jd.blockchain.ledger.ParticipantNode; +import com.jd.blockchain.utils.Bytes; -public class LedgerInitSettingData implements LedgerInitSetting { +public class LedgerInitData implements LedgerInitSetting { private byte[] ledgerSeed; private ParticipantNode[] consensusParticipants; private CryptoSetting cryptoSetting; - + private String consensusProvider; private Bytes consensusSettings; - + private long createdTime; @Override @@ -55,11 +55,15 @@ public class LedgerInitSettingData implements LedgerInitSetting { this.consensusSettings = consensusSettings; } + public void setConsensusSettings(byte[] consensusSettings) { + this.consensusSettings = new Bytes(consensusSettings); + } + @Override public String getConsensusProvider() { return consensusProvider; } - + public void setConsensusProvider(String consensusProvider) { this.consensusProvider = consensusProvider; } @@ -68,7 +72,7 @@ public class LedgerInitSettingData implements LedgerInitSetting { public long getCreatedTime() { return createdTime; } - + public void setCreatedTime(long createdTime) { this.createdTime = createdTime; } diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/PreparedTx.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/PreparedTx.java index cb39f6b6..bba464e3 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/PreparedTx.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/PreparedTx.java @@ -7,13 +7,8 @@ import java.util.Comparator; import org.springframework.cglib.proxy.UndeclaredThrowableException; -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.crypto.PrivKey; -import com.jd.blockchain.crypto.SignatureDigest; -import com.jd.blockchain.crypto.SignatureFunction; import com.jd.blockchain.ledger.DigitalSignature; import com.jd.blockchain.ledger.OperationResult; import com.jd.blockchain.ledger.PreparedTransaction; diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/RolePrivilegeConfigurer.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/RolePrivilegeConfigurer.java new file mode 100644 index 00000000..13539536 --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/RolePrivilegeConfigurer.java @@ -0,0 +1,18 @@ +package com.jd.blockchain.transaction; + +import com.jd.blockchain.ledger.LedgerPermission; +import com.jd.blockchain.ledger.TransactionPermission; + +public interface RolePrivilegeConfigurer extends RolesConfigure { + + String getRoleName(); + + RolePrivilegeConfigurer disable(TransactionPermission... permissions); + + RolePrivilegeConfigurer enable(TransactionPermission... permissions); + + RolePrivilegeConfigurer disable(LedgerPermission... permissions); + + RolePrivilegeConfigurer enable(LedgerPermission... permissions); + +} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/RolesConfigure.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/RolesConfigure.java new file mode 100644 index 00000000..4626fa5a --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/RolesConfigure.java @@ -0,0 +1,7 @@ +package com.jd.blockchain.transaction; + +public interface RolesConfigure { + + RolePrivilegeConfigurer configure(String roleName); + +} 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 new file mode 100644 index 00000000..5ff5fea0 --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/RolesConfigureOpTemplate.java @@ -0,0 +1,137 @@ +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); + } + + 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/RolesConfigurer.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/RolesConfigurer.java new file mode 100644 index 00000000..0621a626 --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/RolesConfigurer.java @@ -0,0 +1,9 @@ +package com.jd.blockchain.transaction; + +import com.jd.blockchain.ledger.RolesConfigureOperation; + +public interface RolesConfigurer extends RolesConfigure { + + RolesConfigureOperation getOperation(); + +} 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 new file mode 100644 index 00000000..f3b6622c --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/SecurityOperationBuilder.java @@ -0,0 +1,19 @@ +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/SecurityOperationBuilderImpl.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/SecurityOperationBuilderImpl.java new file mode 100644 index 00000000..ce271fce --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/SecurityOperationBuilderImpl.java @@ -0,0 +1,15 @@ +package com.jd.blockchain.transaction; + +public class SecurityOperationBuilderImpl implements SecurityOperationBuilder{ + + @Override + public RolesConfigurer roles() { + return new RolesConfigureOpTemplate(); + } + + @Override + public UserAuthorizer authorziations() { + return new UserAuthorizeOpTemplate(); + } + +} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/SecurityOperator.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/SecurityOperator.java new file mode 100644 index 00000000..a636c577 --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/SecurityOperator.java @@ -0,0 +1,23 @@ +package com.jd.blockchain.transaction; + +/** + * 与安全配置相关的操作门面; + * + *
+ * + * 只能通过客户端接口直接操作;不支持通过合约操作; + * + * @author huanghaiquan + * + */ +public interface SecurityOperator { + + /** + * 注册账户操作; + * + * @return + */ + + SecurityOperationBuilder security(); + +} \ No newline at end of file diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxBuilder.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxBuilder.java index b3b7ca7b..0421b265 100644 --- a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxBuilder.java +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/TxBuilder.java @@ -75,6 +75,11 @@ public class TxBuilder implements TransactionBuilder { public Collection getReturnValuehandlers() { return opFactory.getReturnValuetHandlers(); } + + @Override + public SecurityOperationBuilder security() { + return opFactory.security(); + } @Override public LedgerInitOperationBuilder ledgers() { 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 ef4df764..68653c0e 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 @@ -7,9 +7,6 @@ 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.crypto.PrivKey; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.crypto.SignatureDigest; import com.jd.blockchain.ledger.DigitalSignature; import com.jd.blockchain.ledger.NodeRequest; import com.jd.blockchain.ledger.TransactionContent; @@ -55,13 +52,21 @@ public class TxRequestBuilder implements TransactionRequestBuilder { } @Override - public void addNodeSignature(DigitalSignature signature) { - nodeSignatures.add(signature); + public void addNodeSignature(DigitalSignature... signatures) { + if (signatures != null) { + for (DigitalSignature s : signatures) { + nodeSignatures.add(s); + } + } } @Override - public void addEndpointSignature(DigitalSignature signature) { - endpointSignatures.add(signature); + public void addEndpointSignature(DigitalSignature... signatures) { + if (signatures != null) { + for (DigitalSignature s : signatures) { + endpointSignatures.add(s); + } + } } // public static DigitalSignature sign(TransactionContent txContent, AsymmetricKeypair keyPair) { 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 7b407f61..5f006111 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 @@ -35,6 +35,12 @@ public class TxTemplate implements TransactionTemplate { return new PreparedTx(stateManager, txReqBuilder, txService, txBuilder.getReturnValuehandlers()); } + @Override + public SecurityOperationBuilder security() { + stateManager.operate(); + return txBuilder.security(); + } + @Override public UserRegisterOperationBuilder users() { stateManager.operate(); @@ -92,9 +98,10 @@ public class TxTemplate implements TransactionTemplate { @Override public void close() throws IOException { if (!stateManager.close()) { - Collection handlers = txBuilder.getReturnValuehandlers(); + Collection handlers = txBuilder.getReturnValuehandlers(); if (handlers.size() > 0) { - TransactionCancelledExeption error = new TransactionCancelledExeption("Transaction template has been cancelled!"); + 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/UserAuthorize.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserAuthorize.java new file mode 100644 index 00000000..ecaaa7ef --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserAuthorize.java @@ -0,0 +1,12 @@ +package com.jd.blockchain.transaction; + +import com.jd.blockchain.ledger.BlockchainIdentity; +import com.jd.blockchain.utils.Bytes; + +public interface UserAuthorize { + + UserRolesAuthorizer forUser(BlockchainIdentity... userId); + + UserRolesAuthorizer forUser(Bytes... userAddress); + +} 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 new file mode 100644 index 00000000..a8f44f87 --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserAuthorizeOpTemplate.java @@ -0,0 +1,128 @@ +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); + } + + private Set userAuthMap = Collections + .synchronizedSet(new LinkedHashSet()); + + public UserAuthorizeOpTemplate() { + } + + public UserAuthorizeOpTemplate(BlockchainIdentity userID) { + } + + @Override + public UserRolesAuthorization[] getUserRolesAuthorizations() { + return ArrayUtils.toArray(userAuthMap, UserRolesAuthorization.class); + } + + @Override + public UserAuthorizeOperation getOperation() { + return this; + } + + @Override + public UserRolesAuthorizer forUser(Bytes... userAddresses) { + UserRolesAuthorization userRolesAuth = new UserRolesAuthorization(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 UserRolesAuthorization implements UserRolesAuthorizer, UserRolesEntry { + + private Bytes[] userAddress; + + private RolesPolicy policy = RolesPolicy.UNION; + + private Set authRoles = new LinkedHashSet(); + private Set unauthRoles = new LinkedHashSet(); + + private UserRolesAuthorization(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/UserAuthorizer.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserAuthorizer.java new file mode 100644 index 00000000..66f083c7 --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserAuthorizer.java @@ -0,0 +1,9 @@ +package com.jd.blockchain.transaction; + +import com.jd.blockchain.ledger.UserAuthorizeOperation; + +public interface UserAuthorizer extends UserAuthorize { + + UserAuthorizeOperation getOperation(); + +} diff --git a/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserRolesAuthorizer.java b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserRolesAuthorizer.java new file mode 100644 index 00000000..2a58858a --- /dev/null +++ b/source/ledger/ledger-model/src/main/java/com/jd/blockchain/transaction/UserRolesAuthorizer.java @@ -0,0 +1,13 @@ +package com.jd.blockchain.transaction; + +import com.jd.blockchain.ledger.RolesPolicy; + +public interface UserRolesAuthorizer extends UserAuthorize { + + UserRolesAuthorizer authorize(String... roles); + + UserRolesAuthorizer unauthorize(String... roles); + + UserRolesAuthorizer setPolicy(RolesPolicy rolePolicy); + +} diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/AddressEncodingTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/AddressEncodingTest.java similarity index 96% rename from source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/AddressEncodingTest.java rename to source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/AddressEncodingTest.java index ae8dbef8..aab1dbef 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/AddressEncodingTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/AddressEncodingTest.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger.data; +package test.com.jd.blockchain.ledger; import java.util.Random; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/BytesEncodingTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/BytesEncodingTest.java similarity index 95% rename from source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/BytesEncodingTest.java rename to source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/BytesEncodingTest.java index 07bd9c1e..32d48aba 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/BytesEncodingTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/BytesEncodingTest.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger.data; +package test.com.jd.blockchain.ledger; import static org.junit.Assert.*; @@ -6,6 +6,7 @@ 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; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/BytesToBytesValueResolverTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/BytesToBytesValueResolverTest.java similarity index 96% rename from source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/BytesToBytesValueResolverTest.java rename to source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/BytesToBytesValueResolverTest.java index fb470200..3635743c 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/BytesToBytesValueResolverTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/BytesToBytesValueResolverTest.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger.data; +package test.com.jd.blockchain.ledger; import com.jd.blockchain.ledger.BytesValue; import com.jd.blockchain.ledger.DataType; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/BytesValueEncodingTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/BytesValueEncodingTest.java similarity index 98% rename from source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/BytesValueEncodingTest.java rename to source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/BytesValueEncodingTest.java index 73d51d7b..e5b624c9 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/BytesValueEncodingTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/BytesValueEncodingTest.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger.data; +package test.com.jd.blockchain.ledger; import com.jd.blockchain.ledger.*; import com.jd.blockchain.utils.Bytes; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/ContractCodeDeployOpTemplateTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ContractCodeDeployOpTemplateTest.java similarity index 98% rename from source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/ContractCodeDeployOpTemplateTest.java rename to source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ContractCodeDeployOpTemplateTest.java index a54ce94f..5c6b24d2 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/ContractCodeDeployOpTemplateTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ContractCodeDeployOpTemplateTest.java @@ -6,7 +6,7 @@ * Date: 2018/8/30 上午10:53 * Description: */ -package test.com.jd.blockchain.ledger.data; +package test.com.jd.blockchain.ledger; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/ContractEventSendOpTemplateTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ContractEventSendOpTemplateTest.java similarity index 98% rename from source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/ContractEventSendOpTemplateTest.java rename to source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ContractEventSendOpTemplateTest.java index bdfaaa80..d010ae6f 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/ContractEventSendOpTemplateTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ContractEventSendOpTemplateTest.java @@ -6,7 +6,7 @@ * Date: 2018/8/30 上午10:56 * Description: */ -package test.com.jd.blockchain.ledger.data; +package test.com.jd.blockchain.ledger; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/ContractTypeTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ContractTypeTest.java similarity index 98% rename from source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/ContractTypeTest.java rename to source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ContractTypeTest.java index beceb39c..d6a49c9c 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/ContractTypeTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ContractTypeTest.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger.data; +package test.com.jd.blockchain.ledger; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/DataAccountKVSetOpTemplateTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/DataAccountKVSetOpTemplateTest.java similarity index 98% rename from source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/DataAccountKVSetOpTemplateTest.java rename to source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/DataAccountKVSetOpTemplateTest.java index a87919b4..d8b33048 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/DataAccountKVSetOpTemplateTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/DataAccountKVSetOpTemplateTest.java @@ -6,7 +6,7 @@ * Date: 2018/8/30 上午10:59 * Description: */ -package test.com.jd.blockchain.ledger.data; +package test.com.jd.blockchain.ledger; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/DataAccountRegisterOpTemplateTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/DataAccountRegisterOpTemplateTest.java similarity index 98% rename from source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/DataAccountRegisterOpTemplateTest.java rename to source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/DataAccountRegisterOpTemplateTest.java index fcca954f..e13bad09 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/DataAccountRegisterOpTemplateTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/DataAccountRegisterOpTemplateTest.java @@ -6,7 +6,7 @@ * Date: 2018/8/30 上午11:03 * Description: */ -package test.com.jd.blockchain.ledger.data; +package test.com.jd.blockchain.ledger; import static org.junit.Assert.assertEquals; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/DigitalSignatureBlobTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/DigitalSignatureBlobTest.java similarity index 98% rename from source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/DigitalSignatureBlobTest.java rename to source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/DigitalSignatureBlobTest.java index b3e73a0a..068a4040 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/DigitalSignatureBlobTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/DigitalSignatureBlobTest.java @@ -6,7 +6,7 @@ * Date: 2018/8/30 下午2:12 * Description: */ -package test.com.jd.blockchain.ledger.data; +package test.com.jd.blockchain.ledger; import static org.junit.Assert.assertEquals; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/ED25519SignatureTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ED25519SignatureTest.java similarity index 97% rename from source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/ED25519SignatureTest.java rename to source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ED25519SignatureTest.java index 11cc02d1..a9a187ab 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/ED25519SignatureTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ED25519SignatureTest.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger.data; +package test.com.jd.blockchain.ledger; import java.util.Random; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/IntegerToBytesValueResolverTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/IntegerToBytesValueResolverTest.java similarity index 97% rename from source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/IntegerToBytesValueResolverTest.java rename to source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/IntegerToBytesValueResolverTest.java index 4b65ae16..8e39aa85 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/IntegerToBytesValueResolverTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/IntegerToBytesValueResolverTest.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger.data; +package test.com.jd.blockchain.ledger; import com.jd.blockchain.ledger.BytesValue; import com.jd.blockchain.ledger.DataType; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/KVDataTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/KVDataTest.java similarity index 97% rename from source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/KVDataTest.java rename to source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/KVDataTest.java index 229c308d..d1a6fcb9 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/KVDataTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/KVDataTest.java @@ -6,7 +6,7 @@ * Date: 2018/8/30 上午11:08 * Description: */ -package test.com.jd.blockchain.ledger.data; +package test.com.jd.blockchain.ledger; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/LedgerInitPropertiesTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/LedgerInitPropertiesTest.java new file mode 100644 index 00000000..ea17f4d2 --- /dev/null +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/LedgerInitPropertiesTest.java @@ -0,0 +1,203 @@ +package test.com.jd.blockchain.ledger; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.io.InputStream; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.TimeZone; + +import org.junit.Test; +import org.springframework.core.io.ClassPathResource; + +import com.jd.blockchain.binaryproto.DataContractRegistry; +import com.jd.blockchain.crypto.AddressEncoding; +import com.jd.blockchain.crypto.KeyGenUtils; +import com.jd.blockchain.crypto.PubKey; +import com.jd.blockchain.ledger.LedgerInitOperation; +import com.jd.blockchain.ledger.LedgerInitProperties; +import com.jd.blockchain.ledger.LedgerInitProperties.ParticipantProperties; +import com.jd.blockchain.ledger.LedgerPermission; +import com.jd.blockchain.ledger.RoleInitData; +import com.jd.blockchain.ledger.RolesPolicy; +import com.jd.blockchain.ledger.TransactionPermission; +import com.jd.blockchain.ledger.UserRegisterOperation; +import com.jd.blockchain.utils.codec.HexUtils; + +public class LedgerInitPropertiesTest { + + + static { + DataContractRegistry.register(LedgerInitOperation.class); + DataContractRegistry.register(UserRegisterOperation.class); + } + + public static final String PASSWORD = "abc"; + + public static final String[] PUB_KEYS = { "3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9", + "3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX", + "3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x", + "3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk" }; + + public static final String[] PRIV_KEYS = { + "177gjzHTznYdPgWqZrH43W3yp37onm74wYXT4v9FukpCHBrhRysBBZh7Pzdo5AMRyQGJD7x", + "177gju9p5zrNdHJVEQnEEKF4ZjDDYmAXyfG84V5RPGVc5xFfmtwnHA7j51nyNLUFffzz5UT", + "177gjtwLgmSx5v1hFb46ijh7L9kdbKUpJYqdKVf9afiEmAuLgo8Rck9yu5UuUcHknWJuWaF", + "177gk1pudweTq5zgJTh8y3ENCTwtSFsKyX7YnpuKPo7rKgCkCBXVXh5z2syaTCPEMbuWRns" }; + + + private static String expectedCreatedTimeStr = "2019-08-01 14:26:58.069+0800"; + + private static String expectedCreatedTimeStr1 = "2019-08-01 13:26:58.069+0700"; + + @Test + public void testTimeFormat() throws ParseException { + SimpleDateFormat timeFormat = new SimpleDateFormat(LedgerInitProperties.CREATED_TIME_FORMAT); + timeFormat.setTimeZone(TimeZone.getTimeZone("GMT+08:00")); + // 或者设置全局的默认时区; + // TimeZone.setDefault(TimeZone.getTimeZone("GMT+08:00")); + + Date time = timeFormat.parse(expectedCreatedTimeStr); + String actualTimeStr = timeFormat.format(time); + assertEquals(expectedCreatedTimeStr, actualTimeStr); + + Date time1 = timeFormat.parse(expectedCreatedTimeStr1); + String actualTimeStr1 = timeFormat.format(time1); + assertEquals(expectedCreatedTimeStr, actualTimeStr1); + } + + @Test + public void testProperties() throws IOException, ParseException { + // 加载用于测试的账本初始化配置; + ClassPathResource ledgerInitSettingResource = new ClassPathResource("ledger.init"); + InputStream in = ledgerInitSettingResource.getInputStream(); + try { + LedgerInitProperties initProps = LedgerInitProperties.resolve(in); + + // 验证账本信息; + String expectedLedgerSeed = "932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffe" + .replace("-", ""); + String actualLedgerSeed = HexUtils.encode(initProps.getLedgerSeed()); + assertEquals(expectedLedgerSeed, actualLedgerSeed); + + SimpleDateFormat timeFormat = new SimpleDateFormat(LedgerInitProperties.CREATED_TIME_FORMAT); + timeFormat.setTimeZone(TimeZone.getTimeZone("GMT+08:00")); + long expectedTs = timeFormat.parse(expectedCreatedTimeStr).getTime(); + assertEquals(expectedTs, initProps.getCreatedTime()); + + String createdTimeStr = timeFormat.format(new Date(initProps.getCreatedTime())); + assertEquals(expectedCreatedTimeStr, createdTimeStr); + + // 验证角色配置; + RoleInitData[] roles = initProps.getRoles(); + assertEquals(4, roles.length); + Map rolesInitDatas = new HashMap(); + for (RoleInitData r : roles) { + rolesInitDatas.put(r.getRoleName(), r); + } + // 初始化配置的角色最终也是有序排列的,按照角色名称的自然顺序; + String[] expectedRolesNames = { "DEFAULT", "ADMIN", "MANAGER", "GUEST" }; + Arrays.sort(expectedRolesNames); + assertEquals(expectedRolesNames[0], roles[0].getRoleName()); + assertEquals(expectedRolesNames[1], roles[1].getRoleName()); + assertEquals(expectedRolesNames[2], roles[2].getRoleName()); + assertEquals(expectedRolesNames[3], roles[3].getRoleName()); + + RoleInitData roleDefault = rolesInitDatas.get("DEFAULT"); + assertArrayEquals( + new LedgerPermission[] { LedgerPermission.REGISTER_USER, LedgerPermission.REGISTER_DATA_ACCOUNT }, + roleDefault.getLedgerPermissions()); + assertArrayEquals(new TransactionPermission[] { TransactionPermission.DIRECT_OPERATION, + TransactionPermission.CONTRACT_OPERATION }, roleDefault.getTransactionPermissions()); + + RoleInitData roleAdmin = rolesInitDatas.get("ADMIN"); + assertArrayEquals( + new LedgerPermission[] { LedgerPermission.CONFIGURE_ROLES, LedgerPermission.AUTHORIZE_USER_ROLES, + LedgerPermission.SET_CONSENSUS, LedgerPermission.SET_CRYPTO, + LedgerPermission.REGISTER_PARTICIPANT, LedgerPermission.REGISTER_USER }, + roleAdmin.getLedgerPermissions()); + assertArrayEquals(new TransactionPermission[] { TransactionPermission.DIRECT_OPERATION }, + roleAdmin.getTransactionPermissions()); + + RoleInitData roleManager = rolesInitDatas.get("MANAGER"); + assertArrayEquals( + new LedgerPermission[] { LedgerPermission.CONFIGURE_ROLES, LedgerPermission.AUTHORIZE_USER_ROLES, + LedgerPermission.REGISTER_USER, LedgerPermission.REGISTER_DATA_ACCOUNT, + LedgerPermission.REGISTER_CONTRACT, LedgerPermission.UPGRADE_CONTRACT, + LedgerPermission.SET_USER_ATTRIBUTES, LedgerPermission.WRITE_DATA_ACCOUNT }, + roleManager.getLedgerPermissions()); + assertArrayEquals(new TransactionPermission[] { TransactionPermission.DIRECT_OPERATION, + TransactionPermission.CONTRACT_OPERATION }, roleManager.getTransactionPermissions()); + + RoleInitData roleGuest = rolesInitDatas.get("GUEST"); + assertTrue(roleGuest.getLedgerPermissions() == null || roleGuest.getLedgerPermissions().length == 0); + assertArrayEquals(new TransactionPermission[] { TransactionPermission.CONTRACT_OPERATION }, + roleGuest.getTransactionPermissions()); + + // 验证共识和密码配置; + assertEquals("com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider", + initProps.getConsensusProvider()); + + String[] cryptoProviders = initProps.getCryptoProperties().getProviders(); + assertEquals(2, cryptoProviders.length); + assertEquals("com.jd.blockchain.crypto.service.classic.ClassicCryptoService", cryptoProviders[0]); + assertEquals("com.jd.blockchain.crypto.service.sm.SMCryptoService", cryptoProviders[1]); + + // 验证参与方信息; + assertEquals(4, initProps.getConsensusParticipantCount()); + + ParticipantProperties part0 = initProps.getConsensusParticipant(0); + assertEquals("jd.com", part0.getName()); + PubKey pubKey0 = KeyGenUtils.decodePubKey("3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9"); + assertEquals(pubKey0, part0.getPubKey()); + assertEquals("127.0.0.1", part0.getInitializerAddress().getHost()); + assertEquals(8800, part0.getInitializerAddress().getPort()); + assertEquals(true, part0.getInitializerAddress().isSecure()); + assertArrayEquals(new String[] { "ADMIN", "MANAGER" }, part0.getRoles()); + assertEquals(RolesPolicy.UNION, part0.getRolesPolicy()); + + ParticipantProperties part1 = initProps.getConsensusParticipant(1); + assertEquals(false, part1.getInitializerAddress().isSecure()); + PubKey pubKey1 = KeyGenUtils.decodePubKey("3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX"); + assertEquals(pubKey1, part1.getPubKey()); + assertArrayEquals(new String[] { "MANAGER" }, part1.getRoles()); + assertEquals(RolesPolicy.UNION, part1.getRolesPolicy()); + + ParticipantProperties part2 = initProps.getConsensusParticipant(2); + assertEquals("7VeRAr3dSbi1xatq11ZcF7sEPkaMmtZhV9shonGJWk9T4pLe", part2.getPubKey().toBase58()); + assertArrayEquals(new String[] { "MANAGER" }, part2.getRoles()); + assertEquals(RolesPolicy.UNION, part2.getRolesPolicy()); + + ParticipantProperties part3 = initProps.getConsensusParticipant(3); + PubKey pubKey3 = KeyGenUtils.decodePubKey("3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk"); + assertEquals(pubKey3, part3.getPubKey()); + assertArrayEquals(new String[] { "GUEST" }, part3.getRoles()); + assertEquals(RolesPolicy.INTERSECT, part3.getRolesPolicy()); + + } finally { + in.close(); + } + } + + @Test + public void testPubKeyAddress() { + String[] pubKeys = PUB_KEYS; + int index = 0; + for (String pubKeyStr : pubKeys) { + System.out.println("[" + index + "][配置] = " + pubKeyStr); + PubKey pubKey = KeyGenUtils.decodePubKey(pubKeyStr); + System.out.println("[" + index + "][公钥Base58] = " + pubKey.toBase58()); + System.out.println("[" + index + "][地址] = " + AddressEncoding.generateAddress(pubKey).toBase58()); + System.out.println("--------------------------------------------------------------------"); + index++; + } + } + +} diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/LongToBytesValueResolverTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/LongToBytesValueResolverTest.java similarity index 97% rename from source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/LongToBytesValueResolverTest.java rename to source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/LongToBytesValueResolverTest.java index 19cbdcbd..899a6415 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/LongToBytesValueResolverTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/LongToBytesValueResolverTest.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger.data; +package test.com.jd.blockchain.ledger; import com.jd.blockchain.ledger.BytesValue; import com.jd.blockchain.ledger.DataType; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/NormalContract.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/NormalContract.java similarity index 96% rename from source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/NormalContract.java rename to source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/NormalContract.java index 87dcd127..12324b42 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/NormalContract.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/NormalContract.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger.data; +package test.com.jd.blockchain.ledger; import com.jd.blockchain.contract.Contract; import com.jd.blockchain.contract.ContractEvent; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/NormalContractImpl.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/NormalContractImpl.java similarity index 93% rename from source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/NormalContractImpl.java rename to source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/NormalContractImpl.java index ad71598d..d2ba8714 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/NormalContractImpl.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/NormalContractImpl.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger.data; +package test.com.jd.blockchain.ledger; public class NormalContractImpl implements NormalContract{ diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/OpBlobTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/OpBlobTest.java similarity index 95% rename from source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/OpBlobTest.java rename to source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/OpBlobTest.java index 0692a3e4..6ea6da45 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/OpBlobTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/OpBlobTest.java @@ -1,3 +1,4 @@ +package test.com.jd.blockchain.ledger; //package test.com.jd.blockchain.ledger.data; // //import static org.junit.Assert.*; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/PrivilegesTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/PrivilegesTest.java new file mode 100644 index 00000000..10f964c0 --- /dev/null +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/PrivilegesTest.java @@ -0,0 +1,92 @@ +package test.com.jd.blockchain.ledger; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import com.jd.blockchain.binaryproto.BinaryProtocol; +import com.jd.blockchain.ledger.LedgerPermission; +import com.jd.blockchain.ledger.PrivilegeSet; +import com.jd.blockchain.ledger.Privileges; +import com.jd.blockchain.ledger.TransactionPermission; + +public class PrivilegesTest { + + @Test + public void test() { + // 正常情形; + { + Privileges privileges = Privileges.configure() + .enable(LedgerPermission.REGISTER_USER, LedgerPermission.APPROVE_TX) + .enable(TransactionPermission.DIRECT_OPERATION); + + byte[] bytes = BinaryProtocol.encode(privileges, PrivilegeSet.class); + + PrivilegeSet decodePrivileges = BinaryProtocol.decode(bytes); + + assertNotNull(decodePrivileges.getLedgerPrivilege()); + assertNotNull(decodePrivileges.getTransactionPrivilege()); + + for (LedgerPermission p : LedgerPermission.values()) { + if (p == LedgerPermission.REGISTER_USER || p == LedgerPermission.APPROVE_TX) { + assertTrue(decodePrivileges.getLedgerPrivilege().isEnable(p)); + } else { + assertFalse(decodePrivileges.getLedgerPrivilege().isEnable(p)); + } + } + for (TransactionPermission p : TransactionPermission.values()) { + if (p == TransactionPermission.DIRECT_OPERATION) { + assertTrue(decodePrivileges.getTransactionPrivilege().isEnable(p)); + } else { + assertFalse(decodePrivileges.getTransactionPrivilege().isEnable(p)); + } + } + } + // 只定义账本权限的情形; + { + Privileges privileges = Privileges.configure().enable(LedgerPermission.REGISTER_USER, + LedgerPermission.APPROVE_TX); + + byte[] bytes = BinaryProtocol.encode(privileges, PrivilegeSet.class); + + PrivilegeSet decodePrivileges = BinaryProtocol.decode(bytes); + + assertNotNull(decodePrivileges.getLedgerPrivilege()); + assertNotNull(decodePrivileges.getTransactionPrivilege()); + + for (LedgerPermission p : LedgerPermission.values()) { + if (p == LedgerPermission.REGISTER_USER || p == LedgerPermission.APPROVE_TX) { + assertTrue(decodePrivileges.getLedgerPrivilege().isEnable(p)); + } else { + assertFalse(decodePrivileges.getLedgerPrivilege().isEnable(p)); + } + } + for (TransactionPermission p : TransactionPermission.values()) { + assertFalse(decodePrivileges.getTransactionPrivilege().isEnable(p)); + } + } + // 只定义交易权限的情形; + { + Privileges privileges = Privileges.configure().enable(TransactionPermission.CONTRACT_OPERATION); + + byte[] bytes = BinaryProtocol.encode(privileges, PrivilegeSet.class); + + PrivilegeSet decodePrivileges = BinaryProtocol.decode(bytes); + + assertNotNull(decodePrivileges.getLedgerPrivilege()); + assertNotNull(decodePrivileges.getTransactionPrivilege()); + + for (LedgerPermission p : LedgerPermission.values()) { + assertFalse(decodePrivileges.getLedgerPrivilege().isEnable(p)); + } + for (TransactionPermission p : TransactionPermission.values()) { + if (p == TransactionPermission.CONTRACT_OPERATION) { + assertTrue(decodePrivileges.getTransactionPrivilege().isEnable(p)); + } else { + assertFalse(decodePrivileges.getTransactionPrivilege().isEnable(p)); + } + } + } + } + +} diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/SecurityInitDataTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/SecurityInitDataTest.java new file mode 100644 index 00000000..c573fcf6 --- /dev/null +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/SecurityInitDataTest.java @@ -0,0 +1,94 @@ +package test.com.jd.blockchain.ledger; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; + +import com.jd.blockchain.binaryproto.BinaryProtocol; +import com.jd.blockchain.ledger.LedgerPermission; +import com.jd.blockchain.ledger.SecurityInitData; +import com.jd.blockchain.ledger.SecurityInitSettings; +import com.jd.blockchain.ledger.TransactionPermission; +import com.jd.blockchain.utils.serialize.json.JSONSerializeUtils; + +public class SecurityInitDataTest { + + @Test + public void testEnumsSerialization() { + LedgerPermission[] permissions = JSONSerializeUtils.deserializeFromJSON("[\"REGISTER_USER\",\"REGISTER_DATA_ACCOUNT\"]", LedgerPermission[].class); + assertNotNull(permissions); + assertEquals(2, permissions.length); + assertEquals(LedgerPermission.REGISTER_USER, permissions[0]); + assertEquals(LedgerPermission.REGISTER_DATA_ACCOUNT, permissions[1]); + + LedgerPermission[] permissions2 = JSONSerializeUtils.deserializeFromJSON("['REGISTER_USER', 'REGISTER_DATA_ACCOUNT']", LedgerPermission[].class); + assertNotNull(permissions2); + assertEquals(2, permissions2.length); + assertEquals(LedgerPermission.REGISTER_USER, permissions2[0]); + assertEquals(LedgerPermission.REGISTER_DATA_ACCOUNT, permissions2[1]); + + LedgerPermission[] allLedgerPermissions = LedgerPermission.values(); + String jsonLedgerPersioms = JSONSerializeUtils.serializeToJSON(allLedgerPermissions); + + TransactionPermission[] allTransactionPermissions = TransactionPermission.values(); + String jsonTransactionPersioms = JSONSerializeUtils.serializeToJSON(allTransactionPermissions); + + System.out.println("----------- Ledger Permissions JSON ------------"); + System.out.println(jsonLedgerPersioms); + System.out.println("-----------------------"); + System.out.println("----------- Transaction Permissions JSON ------------"); + System.out.println(jsonTransactionPersioms); + System.out.println("-----------------------"); + } + + @Test + public void testSecurityInitDataSerialization() { + + SecurityInitData securityInitData = new SecurityInitData(); + + securityInitData.addRole("DEFAULT", + new LedgerPermission[] { LedgerPermission.REGISTER_USER, LedgerPermission.REGISTER_DATA_ACCOUNT }, + new TransactionPermission[] { TransactionPermission.CONTRACT_OPERATION }); + securityInitData.addRole("ADMIN", + new LedgerPermission[] { LedgerPermission.REGISTER_USER, LedgerPermission.REGISTER_DATA_ACCOUNT }, + new TransactionPermission[] { TransactionPermission.DIRECT_OPERATION, + TransactionPermission.CONTRACT_OPERATION }); + securityInitData.addRole("R1", + new LedgerPermission[] { LedgerPermission.REGISTER_USER, LedgerPermission.REGISTER_DATA_ACCOUNT }, + null); + securityInitData.addRole("R2", null, new TransactionPermission[] { TransactionPermission.DIRECT_OPERATION, + TransactionPermission.CONTRACT_OPERATION }); + + String json = JSONSerializeUtils.serializeToJSON(securityInitData, true); + System.out.println("----------- JSON ------------"); + System.out.println(json); + System.out.println("-----------------------"); + + SecurityInitData desSecurityInitData = JSONSerializeUtils.deserializeFromJSON(json, SecurityInitData.class); + + String json2 = JSONSerializeUtils.serializeToJSON(desSecurityInitData, true); + System.out.println("----------- JSON2 ------------"); + System.out.println(json2); + System.out.println("-----------------------"); + + assertEquals(json, json2); + + byte[] bytes = BinaryProtocol.encode(securityInitData, SecurityInitSettings.class); + + SecurityInitSettings securityInitData2 = BinaryProtocol.decode(bytes); + + byte[] bytes2 = BinaryProtocol.encode(securityInitData2, SecurityInitSettings.class); + + assertArrayEquals(bytes, bytes2); + + assertEquals(4, securityInitData2.getRoles().length); + assertEquals(securityInitData.getRoles().length, securityInitData2.getRoles().length); + assertEquals(LedgerPermission.REGISTER_USER, securityInitData2.getRoles()[1].getLedgerPermissions()[0]); + assertEquals(securityInitData.getRoles()[1].getLedgerPermissions()[0], securityInitData2.getRoles()[1].getLedgerPermissions()[0]); + assertEquals(securityInitData.getRoles()[1].getLedgerPermissions()[1], securityInitData2.getRoles()[1].getLedgerPermissions()[1]); + + } + +} diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/ShortToBytesValueResolverTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ShortToBytesValueResolverTest.java similarity index 96% rename from source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/ShortToBytesValueResolverTest.java rename to source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ShortToBytesValueResolverTest.java index 6c4ef0c8..b35cedd7 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/ShortToBytesValueResolverTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/ShortToBytesValueResolverTest.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger.data; +package test.com.jd.blockchain.ledger; import com.jd.blockchain.ledger.BytesValue; import com.jd.blockchain.ledger.DataType; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/SizeHeaderMaskTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/SizeHeaderMaskTest.java similarity index 94% rename from source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/SizeHeaderMaskTest.java rename to source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/SizeHeaderMaskTest.java index c1acfb00..b8e7875c 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/SizeHeaderMaskTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/SizeHeaderMaskTest.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger.data; +package test.com.jd.blockchain.ledger; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/StringToBytesValueResolverTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/StringToBytesValueResolverTest.java similarity index 97% rename from source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/StringToBytesValueResolverTest.java rename to source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/StringToBytesValueResolverTest.java index 6538e88e..17dd0c04 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/StringToBytesValueResolverTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/StringToBytesValueResolverTest.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger.data; +package test.com.jd.blockchain.ledger; import com.alibaba.fastjson.JSON; import com.jd.blockchain.ledger.BytesValue; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/TxContentBlobTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/TxContentBlobTest.java similarity index 97% rename from source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/TxContentBlobTest.java rename to source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/TxContentBlobTest.java index fc4120d3..0404ee38 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/TxContentBlobTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/TxContentBlobTest.java @@ -1,4 +1,4 @@ -package test.com.jd.blockchain.ledger.data; +package test.com.jd.blockchain.ledger; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/TxRequestMessageTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/TxRequestMessageTest.java similarity index 99% rename from source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/TxRequestMessageTest.java rename to source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/TxRequestMessageTest.java index 6083089f..533eb0b7 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/TxRequestMessageTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/TxRequestMessageTest.java @@ -6,7 +6,7 @@ * Date: 2018/9/3 下午3:07 * Description: */ -package test.com.jd.blockchain.ledger.data; +package test.com.jd.blockchain.ledger; import static org.junit.Assert.assertEquals; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/TxResponseMessageTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/TxResponseMessageTest.java similarity index 97% rename from source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/TxResponseMessageTest.java rename to source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/TxResponseMessageTest.java index c0a944de..bcd50191 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/TxResponseMessageTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/TxResponseMessageTest.java @@ -6,7 +6,7 @@ * Date: 2018/9/6 上午11:00 * Description: */ -package test.com.jd.blockchain.ledger.data; +package test.com.jd.blockchain.ledger; import static org.junit.Assert.assertEquals; diff --git a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/UserRegisterOpTemplateTest.java b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/UserRegisterOpTemplateTest.java similarity index 98% rename from source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/UserRegisterOpTemplateTest.java rename to source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/UserRegisterOpTemplateTest.java index 27b455f3..95be8d5c 100644 --- a/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/data/UserRegisterOpTemplateTest.java +++ b/source/ledger/ledger-model/src/test/java/test/com/jd/blockchain/ledger/UserRegisterOpTemplateTest.java @@ -6,7 +6,7 @@ * Date: 2018/8/30 上午11:04 * Description: */ -package test.com.jd.blockchain.ledger.data; +package test.com.jd.blockchain.ledger; import static org.junit.Assert.assertEquals; diff --git a/source/ledger/ledger-model/src/test/resources/bftsmart.config b/source/ledger/ledger-model/src/test/resources/bftsmart.config new file mode 100644 index 00000000..df69caf5 --- /dev/null +++ b/source/ledger/ledger-model/src/test/resources/bftsmart.config @@ -0,0 +1,144 @@ +# 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 ### +############################################ + +#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 ###### +############################################ + +#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 + + +#Number of servers in the group +system.servers.num = 4 + +#Maximum number of faulty replicas +system.servers.f = 1 + +#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 + +#Configuration of all node servers; +#PubKey of node server with specified ID, with base58 encoding. +system.server.0.pubkey= +system.server.0.network.host=127.0.0.1 +system.server.0.network.port=8900 +system.server.0.network.secure=false + +system.server.1.pubkey= +system.server.1.network.host=127.0.0.1 +system.server.1.network.port=8910 +system.server.1.network.secure=false + +system.server.2.pubkey= +system.server.2.network.host=127.0.0.1 +system.server.2.network.port=8920 +system.server.2.network.secure=false + +system.server.3.pubkey= +system.server.3.network.host=127.0.0.1 +system.server.3.network.port=8920 +system.server.3.network.secure=false diff --git a/source/ledger/ledger-model/src/test/resources/keys/parti2.pub b/source/ledger/ledger-model/src/test/resources/keys/parti2.pub new file mode 100644 index 00000000..dde44b8e --- /dev/null +++ b/source/ledger/ledger-model/src/test/resources/keys/parti2.pub @@ -0,0 +1 @@ +3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x \ No newline at end of file diff --git a/source/ledger/ledger-model/src/test/resources/ledger.init b/source/ledger/ledger-model/src/test/resources/ledger.init new file mode 100644 index 00000000..9ff0a35c --- /dev/null +++ b/source/ledger/ledger-model/src/test/resources/ledger.init @@ -0,0 +1,164 @@ + +#账本的种子;一段16进制字符,最长可以包含64个字符;可以用字符“-”分隔,以便更容易读取; +ledger.seed=932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffe + +#账本的描述名称;此属性不参与共识,仅仅在当前参与方的本地节点用于描述用途; +ledger.name=test + +#声明账本的创建时间;格式为 “yyyy-MM-dd HH:mm:ss.SSSZ”,表示”年-月-日 时:分:秒:毫秒时区“;例如:“2019-08-01 14:26:58.069+0800”,其中,+0800 表示时区是东8区 +created-time=2019-08-01 14:26:58.069+0800 + + +#----------------------------------------------- +# 初始的角色名称列表;可选项; +# 角色名称不区分大小写,最长不超过20个字符;多个角色名称之间用半角的逗点“,”分隔; +# 系统会预置一个默认角色“DEFAULT”,所有未指定角色的用户都以赋予该角色的权限;若初始化时未配置默认角色的权限,则为默认角色分配所有权限; +# +# 注:如果声明了角色,但未声明角色对应的权限清单,这会忽略该角色的初始化; +# +security.roles=DEFAULT, ADMIN, MANAGER, GUEST + +# 赋予角色的账本权限清单;可选项; +# 可选的权限如下; +# AUTHORIZE_ROLES, SET_CONSENSUS, SET_CRYPTO, REGISTER_PARTICIPANT, +# REGISTER_USER, REGISTER_DATA_ACCOUNT, REGISTER_CONTRACT, UPGRADE_CONTRACT, +# SET_USER_ATTRIBUTES, WRITE_DATA_ACCOUNT, +# APPROVE_TX, CONSENSUS_TX +# 多项权限之间用逗点“,”分隔; +# +security.role.DEFAULT.ledger-privileges=REGISTER_USER, REGISTER_DATA_ACCOUNT + +# 赋予角色的交易权限清单;可选项; +# 可选的权限如下; +# DIRECT_OPERATION, CONTRACT_OPERATION +# 多项权限之间用逗点“,”分隔; +# +security.role.DEFAULT.tx-privileges=DIRECT_OPERATION, CONTRACT_OPERATION + +# 其它角色的配置示例; +# 系统管理员角色:只能操作全局性的参数配置和用户注册,只能执行直接操作指令; +security.role.ADMIN.ledger-privileges=CONFIGURE_ROLES, AUTHORIZE_USER_ROLES, SET_CONSENSUS, SET_CRYPTO, REGISTER_PARTICIPANT, REGISTER_USER +security.role.ADMIN.tx-privileges=DIRECT_OPERATION + +# 业务主管角色:只能够执行账本数据相关的操作,包括注册用户、注册数据账户、注册合约、升级合约、写入数据等;能够执行直接操作指令和调用合约; +security.role.MANAGER.ledger-privileges=CONFIGURE_ROLES, AUTHORIZE_USER_ROLES, REGISTER_USER, REGISTER_DATA_ACCOUNT, REGISTER_CONTRACT, UPGRADE_CONTRACT, SET_USER_ATTRIBUTES, WRITE_DATA_ACCOUNT, +security.role.MANAGER.tx-privileges=DIRECT_OPERATION, CONTRACT_OPERATION + +# 访客角色:不具备任何的账本权限,只有数据读取的操作;也只能够通过调用合约来读取数据; +security.role.GUEST.ledger-privileges= +security.role.GUEST.tx-privileges=CONTRACT_OPERATION + + + +#----------------------------------------------- +#共识服务提供者;必须; +consensus.service-provider=com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider + +#共识服务的参数配置;必须; +consensus.conf=classpath:bftsmart.config + +#密码服务提供者列表,以英文逗点“,”分隔;必须; +crypto.service-providers=com.jd.blockchain.crypto.service.classic.ClassicCryptoService, \ +com.jd.blockchain.crypto.service.sm.SMCryptoService + +#从存储中加载账本数据时,是否校验哈希;可选; +crypto.verify-hash=true + +#哈希算法; +crypto.hash-algorithm=SHA256 + + +#参与方的个数,后续以 cons_parti.id 分别标识每一个参与方的配置; +cons_parti.count=4 + +#第0个参与方的名称; +cons_parti.0.name=jd.com +#第0个参与方的公钥文件路径; +cons_parti.0.pubkey-path=keys/jd-com.pub +#第0个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; +cons_parti.0.pubkey=3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9 +#第0个参与方的角色清单;可选项; +cons_parti.0.roles=ADMIN, MANAGER +#第0个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; +cons_parti.0.roles-policy=UNION +#第0个参与方的共识服务的主机地址; +cons_parti.0.consensus.host=127.0.0.1 +#第0个参与方的共识服务的端口; +cons_parti.0.consensus.port=8900 +#第0个参与方的共识服务是否开启安全连接; +cons_parti.0.consensus.secure=true +#第0个参与方的账本初始服务的主机; +cons_parti.0.initializer.host=127.0.0.1 +#第0个参与方的账本初始服务的端口; +cons_parti.0.initializer.port=8800 +#第0个参与方的账本初始服务是否开启安全连接; +cons_parti.0.initializer.secure=true + +#第1个参与方的名称; +cons_parti.1.name=at.com +#第1个参与方的公钥文件路径; +cons_parti.1.pubkey-path=keys/at-com.pub +#第1个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; +cons_parti.1.pubkey=3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX +#第1个参与方的角色清单;可选项; +cons_parti.1.roles=MANAGER +#第1个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; +cons_parti.1.roles-policy=UNION +#第1个参与方的共识服务的主机地址; +cons_parti.1.consensus.host=127.0.0.1 +#第1个参与方的共识服务的端口; +cons_parti.1.consensus.port=8910 +#第1个参与方的共识服务是否开启安全连接; +cons_parti.1.consensus.secure=false +#第1个参与方的账本初始服务的主机; +cons_parti.1.initializer.host=127.0.0.1 +#第1个参与方的账本初始服务的端口; +cons_parti.1.initializer.port=8810 +#第1个参与方的账本初始服务是否开启安全连接; +cons_parti.1.initializer.secure=false + +#第2个参与方的名称; +cons_parti.2.name=bt.com +#第2个参与方的公钥文件路径; +cons_parti.2.pubkey-path=classpath:keys/parti2.pub +#第2个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; +cons_parti.2.pubkey= +#第2个参与方的角色清单;可选项; +cons_parti.2.roles=MANAGER +#第2个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; +cons_parti.2.roles-policy=UNION +#第2个参与方的共识服务的主机地址; +cons_parti.2.consensus.host=127.0.0.1 +#第2个参与方的共识服务的端口; +cons_parti.2.consensus.port=8920 +#第2个参与方的共识服务是否开启安全连接; +cons_parti.2.consensus.secure=false +#第2个参与方的账本初始服务的主机; +cons_parti.2.initializer.host=127.0.0.1 +#第2个参与方的账本初始服务的端口; +cons_parti.2.initializer.port=8820 +#第2个参与方的账本初始服务是否开启安全连接; +cons_parti.2.initializer.secure=true + +#第3个参与方的名称; +cons_parti.3.name=xt.com +#第3个参与方的公钥文件路径; +cons_parti.3.pubkey-path=keys/xt-com.pub +#第3个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; +cons_parti.3.pubkey=3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk +#第3个参与方的角色清单;可选项; +cons_parti.3.roles=GUEST +#第3个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; +cons_parti.3.roles-policy=INTERSECT +#第3个参与方的共识服务的主机地址; +cons_parti.3.consensus.host=127.0.0.1 +#第3个参与方的共识服务的端口; +cons_parti.3.consensus.port=8930 +#第3个参与方的共识服务是否开启安全连接; +cons_parti.3.consensus.secure=false +#第3个参与方的账本初始服务的主机; +cons_parti.3.initializer.host=127.0.0.1 +#第3个参与方的账本初始服务的端口; +cons_parti.3.initializer.port=8830 +#第3个参与方的账本初始服务是否开启安全连接; +cons_parti.3.initializer.secure=false diff --git a/source/peer/pom.xml b/source/peer/pom.xml index f428d188..a7127e68 100644 --- a/source/peer/pom.xml +++ b/source/peer/pom.xml @@ -54,18 +54,12 @@ org.springframework.boot spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-logging - - - + org.springframework.boot diff --git a/source/peer/src/main/java/com/jd/blockchain/peer/consensus/ConsensusRealmImpl.java b/source/peer/src/main/java/com/jd/blockchain/peer/consensus/ConsensusRealmImpl.java index 108365a6..d5d5fca9 100644 --- a/source/peer/src/main/java/com/jd/blockchain/peer/consensus/ConsensusRealmImpl.java +++ b/source/peer/src/main/java/com/jd/blockchain/peer/consensus/ConsensusRealmImpl.java @@ -16,7 +16,7 @@ public class ConsensusRealmImpl implements ConsensusRealm { public ConsensusRealmImpl(ParticipantNode[] nodeList) { this.nodes = nodeList; - String[] addrs = new String[nodes.length]; + Bytes[] addrs = new Bytes[nodes.length]; int i = 0; for (ParticipantNode n : nodes) { addrs[i++] = n.getAddress(); diff --git a/source/peer/src/main/java/com/jd/blockchain/peer/ledger/LedgerConfigurer.java b/source/peer/src/main/java/com/jd/blockchain/peer/ledger/LedgerConfigurer.java index 5a2bc247..f6c8bcb9 100644 --- a/source/peer/src/main/java/com/jd/blockchain/peer/ledger/LedgerConfigurer.java +++ b/source/peer/src/main/java/com/jd/blockchain/peer/ledger/LedgerConfigurer.java @@ -3,10 +3,10 @@ package com.jd.blockchain.peer.ledger; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.jd.blockchain.ledger.core.impl.DefaultOperationHandleRegisteration; -import com.jd.blockchain.ledger.core.impl.LedgerManager; -import com.jd.blockchain.ledger.core.impl.OperationHandleRegisteration; -import com.jd.blockchain.ledger.core.impl.TransactionEngineImpl; +import com.jd.blockchain.ledger.core.DefaultOperationHandleRegisteration; +import com.jd.blockchain.ledger.core.LedgerManager; +import com.jd.blockchain.ledger.core.OperationHandleRegisteration; +import com.jd.blockchain.ledger.core.TransactionEngineImpl; import com.jd.blockchain.service.TransactionEngine; @Configuration diff --git a/source/peer/src/main/java/com/jd/blockchain/peer/web/LedgerQueryController.java b/source/peer/src/main/java/com/jd/blockchain/peer/web/LedgerQueryController.java index 341136b0..992cf1a0 100644 --- a/source/peer/src/main/java/com/jd/blockchain/peer/web/LedgerQueryController.java +++ b/source/peer/src/main/java/com/jd/blockchain/peer/web/LedgerQueryController.java @@ -14,15 +14,14 @@ import org.springframework.web.bind.annotation.RestController; import com.jd.blockchain.contract.ContractException; import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.core.ContractAccountSet; +import com.jd.blockchain.ledger.core.ContractAccountQuery; import com.jd.blockchain.ledger.core.DataAccount; -import com.jd.blockchain.ledger.core.DataAccountSet; -import com.jd.blockchain.ledger.core.LedgerAdministration; +import com.jd.blockchain.ledger.core.DataAccountQuery; import com.jd.blockchain.ledger.core.LedgerRepository; import com.jd.blockchain.ledger.core.LedgerService; import com.jd.blockchain.ledger.core.ParticipantCertData; import com.jd.blockchain.ledger.core.TransactionSet; -import com.jd.blockchain.ledger.core.UserAccountSet; +import com.jd.blockchain.ledger.core.UserAccountQuery; import com.jd.blockchain.transaction.BlockchainQueryService; import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.QueryUtil; @@ -57,7 +56,7 @@ public class LedgerQueryController implements BlockchainQueryService { @Override public ParticipantNode[] getConsensusParticipants(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); - LedgerAdministration ledgerAdministration = ledger.getAdminInfo(); + LedgerAdminInfo ledgerAdministration = ledger.getAdminInfo(); long participantCount = ledgerAdministration.getParticipantCount(); if (participantCount <= 0) { return null; @@ -73,12 +72,20 @@ public class LedgerQueryController implements BlockchainQueryService { } return null; } + + @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/admininfo") + @Override + public LedgerAdminInfo getLedgerAdminInfo(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { + LedgerRepository ledger = ledgerService.getLedger(ledgerHash); + LedgerAdminInfo ledgerAdministration = ledger.getAdminInfo(); + return ledgerAdministration; + } @RequestMapping(method = RequestMethod.GET, path = "ledgers/{ledgerHash}/metadata") @Override public LedgerMetadata getLedgerMetadata(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); - LedgerAdministration ledgerAdministration = ledger.getAdminInfo(); + LedgerAdminInfo ledgerAdministration = ledger.getAdminInfo(); LedgerMetadata ledgerMetadata = ledgerAdministration.getMetadata(); return ledgerMetadata; } @@ -138,7 +145,7 @@ public class LedgerQueryController implements BlockchainQueryService { @PathVariable(name = "blockHeight") long height) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getBlock(height); - DataAccountSet dataAccountSet = ledger.getDataAccountSet(block); + DataAccountQuery dataAccountSet = ledger.getDataAccountSet(block); return dataAccountSet.getTotalCount(); } @@ -148,7 +155,7 @@ public class LedgerQueryController implements BlockchainQueryService { @PathVariable(name = "blockHash") HashDigest blockHash) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getBlock(blockHash); - DataAccountSet dataAccountSet = ledger.getDataAccountSet(block); + DataAccountQuery dataAccountSet = ledger.getDataAccountSet(block); return dataAccountSet.getTotalCount(); } @@ -157,7 +164,7 @@ public class LedgerQueryController implements BlockchainQueryService { public long getDataAccountTotalCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getLatestBlock(); - DataAccountSet dataAccountSet = ledger.getDataAccountSet(block); + DataAccountQuery dataAccountSet = ledger.getDataAccountSet(block); return dataAccountSet.getTotalCount(); } @@ -167,7 +174,7 @@ public class LedgerQueryController implements BlockchainQueryService { @PathVariable(name = "blockHeight") long height) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getBlock(height); - UserAccountSet userAccountSet = ledger.getUserAccountSet(block); + UserAccountQuery userAccountSet = ledger.getUserAccountSet(block); return userAccountSet.getTotalCount(); } @@ -177,7 +184,7 @@ public class LedgerQueryController implements BlockchainQueryService { @PathVariable(name = "blockHash") HashDigest blockHash) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getBlock(blockHash); - UserAccountSet userAccountSet = ledger.getUserAccountSet(block); + UserAccountQuery userAccountSet = ledger.getUserAccountSet(block); return userAccountSet.getTotalCount(); } @@ -186,7 +193,7 @@ public class LedgerQueryController implements BlockchainQueryService { public long getUserTotalCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getLatestBlock(); - UserAccountSet userAccountSet = ledger.getUserAccountSet(block); + UserAccountQuery userAccountSet = ledger.getUserAccountSet(block); return userAccountSet.getTotalCount(); } @@ -196,7 +203,7 @@ public class LedgerQueryController implements BlockchainQueryService { @PathVariable(name = "blockHeight") long height) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getBlock(height); - ContractAccountSet contractAccountSet = ledger.getContractAccountSet(block); + ContractAccountQuery contractAccountSet = ledger.getContractAccountSet(block); return contractAccountSet.getTotalCount(); } @@ -206,7 +213,7 @@ public class LedgerQueryController implements BlockchainQueryService { @PathVariable(name = "blockHash") HashDigest blockHash) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getBlock(blockHash); - ContractAccountSet contractAccountSet = ledger.getContractAccountSet(block); + ContractAccountQuery contractAccountSet = ledger.getContractAccountSet(block); return contractAccountSet.getTotalCount(); } @@ -215,7 +222,7 @@ public class LedgerQueryController implements BlockchainQueryService { public long getContractTotalCount(@PathVariable(name = "ledgerHash") HashDigest ledgerHash) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getLatestBlock(); - ContractAccountSet contractAccountSet = ledger.getContractAccountSet(block); + ContractAccountQuery contractAccountSet = ledger.getContractAccountSet(block); return contractAccountSet.getTotalCount(); } @@ -313,7 +320,7 @@ public class LedgerQueryController implements BlockchainQueryService { @PathVariable(name = "address") String address) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getLatestBlock(); - UserAccountSet userAccountSet = ledger.getUserAccountSet(block); + UserAccountQuery userAccountSet = ledger.getUserAccountSet(block); return userAccountSet.getUser(address); } @@ -323,7 +330,7 @@ public class LedgerQueryController implements BlockchainQueryService { @PathVariable(name = "address") String address) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getLatestBlock(); - DataAccountSet dataAccountSet = ledger.getDataAccountSet(block); + DataAccountQuery dataAccountSet = ledger.getDataAccountSet(block); return dataAccountSet.getDataAccount(Bytes.fromBase58(address)); } @@ -337,7 +344,7 @@ public class LedgerQueryController implements BlockchainQueryService { } LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getLatestBlock(); - DataAccountSet dataAccountSet = ledger.getDataAccountSet(block); + DataAccountQuery dataAccountSet = ledger.getDataAccountSet(block); DataAccount dataAccount = dataAccountSet.getDataAccount(Bytes.fromBase58(address)); KVDataEntry[] entries = new KVDataEntry[keys.length]; @@ -386,7 +393,7 @@ public class LedgerQueryController implements BlockchainQueryService { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getLatestBlock(); - DataAccountSet dataAccountSet = ledger.getDataAccountSet(block); + DataAccountQuery dataAccountSet = ledger.getDataAccountSet(block); DataAccount dataAccount = dataAccountSet.getDataAccount(Bytes.fromBase58(address)); KVDataEntry[] entries = new KVDataEntry[keys.length]; @@ -421,7 +428,7 @@ public class LedgerQueryController implements BlockchainQueryService { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getLatestBlock(); - DataAccountSet dataAccountSet = ledger.getDataAccountSet(block); + DataAccountQuery dataAccountSet = ledger.getDataAccountSet(block); DataAccount dataAccount = dataAccountSet.getDataAccount(Bytes.fromBase58(address)); int pages[] = QueryUtil.calFromIndexAndCount(fromIndex, count, (int) dataAccount.getDataEntriesTotalCount()); @@ -435,7 +442,7 @@ public class LedgerQueryController implements BlockchainQueryService { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getLatestBlock(); - DataAccountSet dataAccountSet = ledger.getDataAccountSet(block); + DataAccountQuery dataAccountSet = ledger.getDataAccountSet(block); DataAccount dataAccount = dataAccountSet.getDataAccount(Bytes.fromBase58(address)); return dataAccount.getDataEntriesTotalCount(); @@ -447,7 +454,7 @@ public class LedgerQueryController implements BlockchainQueryService { @PathVariable(name = "address") String address) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getLatestBlock(); - ContractAccountSet contractAccountSet = ledger.getContractAccountSet(block); + ContractAccountQuery contractAccountSet = ledger.getContractAccountSet(block); return contractAccountSet.getContract(Bytes.fromBase58(address)); } @@ -466,7 +473,7 @@ public class LedgerQueryController implements BlockchainQueryService { @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getLatestBlock(); - UserAccountSet userAccountSet = ledger.getUserAccountSet(block); + UserAccountQuery userAccountSet = ledger.getUserAccountSet(block); int pages[] = QueryUtil.calFromIndexAndCount(fromIndex, count, (int) userAccountSet.getTotalCount()); return userAccountSet.getAccounts(pages[0], pages[1]); } @@ -486,7 +493,7 @@ public class LedgerQueryController implements BlockchainQueryService { @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getLatestBlock(); - DataAccountSet dataAccountSet = ledger.getDataAccountSet(block); + DataAccountQuery dataAccountSet = ledger.getDataAccountSet(block); int pages[] = QueryUtil.calFromIndexAndCount(fromIndex, count, (int) dataAccountSet.getTotalCount()); return dataAccountSet.getAccounts(pages[0], pages[1]); } @@ -498,7 +505,7 @@ public class LedgerQueryController implements BlockchainQueryService { @RequestParam(name = "count", required = false, defaultValue = "-1") int count) { LedgerRepository ledger = ledgerService.getLedger(ledgerHash); LedgerBlock block = ledger.getLatestBlock(); - ContractAccountSet contractAccountSet = ledger.getContractAccountSet(block); + ContractAccountQuery contractAccountSet = ledger.getContractAccountSet(block); int pages[] = QueryUtil.calFromIndexAndCount(fromIndex, count, (int) contractAccountSet.getTotalCount()); return contractAccountSet.getAccounts(pages[0], pages[1]); } diff --git a/source/peer/src/main/java/com/jd/blockchain/peer/web/ManagementController.java b/source/peer/src/main/java/com/jd/blockchain/peer/web/ManagementController.java index 04b71c41..c65ab837 100644 --- a/source/peer/src/main/java/com/jd/blockchain/peer/web/ManagementController.java +++ b/source/peer/src/main/java/com/jd/blockchain/peer/web/ManagementController.java @@ -32,7 +32,8 @@ import com.jd.blockchain.consensus.service.NodeServer; import com.jd.blockchain.consensus.service.ServerSettings; import com.jd.blockchain.consensus.service.StateMachineReplicate; import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.core.LedgerAdminAccount; +import com.jd.blockchain.ledger.LedgerAdminInfo; +import com.jd.blockchain.ledger.core.LedgerAdminDataQuery; import com.jd.blockchain.ledger.core.LedgerManage; import com.jd.blockchain.ledger.core.LedgerRepository; import com.jd.blockchain.peer.ConsensusRealm; @@ -109,6 +110,8 @@ public class ManagementController implements LedgerBindingConfigAware, PeerManag DataContractRegistry.register(BftsmartConsensusSettings.class); DataContractRegistry.register(BftsmartNodeSettings.class); + + DataContractRegistry.register(LedgerAdminDataQuery.class); } @@ -212,11 +215,11 @@ public class ManagementController implements LedgerBindingConfigAware, PeerManag LedgerRepository ledgerRepository = ledgerManager.register(ledgerHash, dbConnNew.getStorageService()); // load provider; - LedgerAdminAccount ledgerAdminAccount = ledgerRepository.getAdminAccount(); - String consensusProvider = ledgerAdminAccount.getSetting().getConsensusProvider(); + LedgerAdminInfo ledgerAdminAccount = ledgerRepository.getAdminInfo(); + String consensusProvider = ledgerAdminAccount.getSettings().getConsensusProvider(); ConsensusProvider provider = ConsensusProviders.getProvider(consensusProvider); // find current node; - Bytes csSettingBytes = ledgerAdminAccount.getSetting().getConsensusSetting(); + Bytes csSettingBytes = ledgerAdminAccount.getSettings().getConsensusSetting(); ConsensusSettings csSettings = provider.getSettingsFactory().getConsensusSettingsEncoder() .decode(csSettingBytes.toBytes()); NodeSettings currentNode = null; @@ -235,7 +238,7 @@ public class ManagementController implements LedgerBindingConfigAware, PeerManag NodeServer server = provider.getServerFactory().setupServer(serverSettings, consensusMessageHandler, consensusStateManager); ledgerPeers.put(ledgerHash, server); - ledgerCryptoSettings.put(ledgerHash, ledgerAdminAccount.getSetting().getCryptoSetting()); + ledgerCryptoSettings.put(ledgerHash, ledgerAdminAccount.getSettings().getCryptoSetting()); return server; } diff --git a/source/pom.xml b/source/pom.xml index af02b0af..9dd10642 100644 --- a/source/pom.xml +++ b/source/pom.xml @@ -8,11 +8,6 @@ spring-boot-starter-parent 2.0.6.RELEASE - - - - - com.jd.blockchain jdchain-root @@ -45,9 +40,6 @@ 0.7.0.RELEASE 1.0.0-SNAPSHOT 2.4 - - 3.3.0 1.2.2 1.8.8 @@ -85,6 +77,10 @@ + + org.springframework.boot + spring-boot-starter-logging + junit junit @@ -140,7 +136,6 @@ org.mockito mockito-core ${mockito.version} - test diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/LedgerInitSettings.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/LedgerInitSettings.java index d4f287ab..cc6ca054 100644 --- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/LedgerInitSettings.java +++ b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/LedgerInitSettings.java @@ -1,96 +1,96 @@ -package com.jd.blockchain.sdk; - - -import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.ledger.ParticipantNode; - -/** - * 账本初始化配置 - * - * @author shaozhuguang - * @date 2019-04-23 - * @since 1.0.0 - * - */ -public class LedgerInitSettings { - - /** - * 账本初始化种子 - */ - private String seed; - - /** - * 共识参与方的默克尔树的根; - */ - private HashDigest participantsHash; - - /** - * 算法配置 - */ - private CryptoSetting cryptoSetting; - - /** - * 共识协议 - */ - private String consensusProtocol; - - /** - * 共识配置 - */ - private ConsensusSettings consensusSettings; - - /** - * 共识参与方 - */ - private ParticipantNode[] participantNodes; - - public void setSeed(String seed) { - this.seed = seed; - } - - public String getSeed() { - return seed; - } - - public HashDigest getParticipantsHash() { - return participantsHash; - } - - public void setParticipantsHash(HashDigest participantsHash) { - this.participantsHash = participantsHash; - } - - public CryptoSetting getCryptoSetting() { - return cryptoSetting; - } - - public void setCryptoSetting(CryptoSetting cryptoSetting) { - this.cryptoSetting = cryptoSetting; - } - - public String getConsensusProtocol() { - return consensusProtocol; - } - - public void setConsensusProtocol(String consensusProtocol) { - this.consensusProtocol = consensusProtocol; - } - - public ConsensusSettings getConsensusSettings() { - return consensusSettings; - } - - public void setConsensusSettings(ConsensusSettings consensusSettings) { - this.consensusSettings = consensusSettings; - } - - public ParticipantNode[] getParticipantNodes() { - return participantNodes; - } - - public void setParticipantNodes(ParticipantNode[] participantNodes) { - this.participantNodes = participantNodes; - } -} +//package com.jd.blockchain.sdk; +// +// +//import com.jd.blockchain.consensus.ConsensusSettings; +//import com.jd.blockchain.crypto.HashDigest; +//import com.jd.blockchain.ledger.CryptoSetting; +//import com.jd.blockchain.ledger.ParticipantNode; +// +///** +// * 账本初始化配置 +// * +// * @author shaozhuguang +// * @date 2019-04-23 +// * @since 1.0.0 +// * +// */ +//public class LedgerInitSettings { +// +// /** +// * 账本初始化种子 +// */ +// private String seed; +// +// /** +// * 共识参与方的默克尔树的根; +// */ +// private HashDigest participantsHash; +// +// /** +// * 算法配置 +// */ +// private CryptoSetting cryptoSetting; +// +// /** +// * 共识协议 +// */ +// private String consensusProtocol; +// +// /** +// * 共识配置 +// */ +// private ConsensusSettings consensusSettings; +// +// /** +// * 共识参与方 +// */ +// private ParticipantNode[] participantNodes; +// +// public void setSeed(String seed) { +// this.seed = seed; +// } +// +// public String getSeed() { +// return seed; +// } +// +// public HashDigest getParticipantsHash() { +// return participantsHash; +// } +// +// public void setParticipantsHash(HashDigest participantsHash) { +// this.participantsHash = participantsHash; +// } +// +// public CryptoSetting getCryptoSetting() { +// return cryptoSetting; +// } +// +// public void setCryptoSetting(CryptoSetting cryptoSetting) { +// this.cryptoSetting = cryptoSetting; +// } +// +// public String getConsensusProtocol() { +// return consensusProtocol; +// } +// +// public void setConsensusProtocol(String consensusProtocol) { +// this.consensusProtocol = consensusProtocol; +// } +// +// public ConsensusSettings getConsensusSettings() { +// return consensusSettings; +// } +// +// public void setConsensusSettings(ConsensusSettings consensusSettings) { +// this.consensusSettings = consensusSettings; +// } +// +// public ParticipantNode[] getParticipantNodes() { +// return participantNodes; +// } +// +// public void setParticipantNodes(ParticipantNode[] participantNodes) { +// this.participantNodes = participantNodes; +// } +//} diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/converters/ClientResolveUtil.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/converters/ClientResolveUtil.java index 7cce33c1..460bdc9b 100644 --- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/converters/ClientResolveUtil.java +++ b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/converters/ClientResolveUtil.java @@ -8,19 +8,41 @@ */ package com.jd.blockchain.sdk.converters; +import java.lang.reflect.Field; + +import org.apache.commons.codec.binary.Base64; + import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.jd.blockchain.crypto.CryptoProvider; import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.*; -import com.jd.blockchain.transaction.*; +import com.jd.blockchain.ledger.BlockchainIdentityData; +import com.jd.blockchain.ledger.BytesData; +import com.jd.blockchain.ledger.BytesValue; +import com.jd.blockchain.ledger.BytesValueEncoding; +import com.jd.blockchain.ledger.ContractCodeDeployOperation; +import com.jd.blockchain.ledger.ContractEventSendOperation; +import com.jd.blockchain.ledger.CryptoSetting; +import com.jd.blockchain.ledger.DataAccountKVSetOperation; +import com.jd.blockchain.ledger.DataAccountRegisterOperation; +import com.jd.blockchain.ledger.DataType; +import com.jd.blockchain.ledger.KVDataEntry; +import com.jd.blockchain.ledger.LedgerInitOperation; +import com.jd.blockchain.ledger.Operation; +import com.jd.blockchain.ledger.ParticipantNode; +import com.jd.blockchain.ledger.UserRegisterOperation; +import com.jd.blockchain.transaction.ContractCodeDeployOpTemplate; +import com.jd.blockchain.transaction.ContractEventSendOpTemplate; +import com.jd.blockchain.transaction.DataAccountKVSetOpTemplate; +import com.jd.blockchain.transaction.DataAccountRegisterOpTemplate; +import com.jd.blockchain.transaction.KVData; +import com.jd.blockchain.transaction.LedgerInitData; +import com.jd.blockchain.transaction.LedgerInitOpTemplate; +import com.jd.blockchain.transaction.UserRegisterOpTemplate; import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.codec.Base58Utils; import com.jd.blockchain.utils.codec.HexUtils; import com.jd.blockchain.utils.io.BytesUtils; -import org.apache.commons.codec.binary.Base64; - -import java.lang.reflect.Field; /** * @@ -31,357 +53,358 @@ import java.lang.reflect.Field; public class ClientResolveUtil { - public static KVDataEntry[] read(KVDataEntry[] kvDataEntries) { - if (kvDataEntries == null || kvDataEntries.length == 0) { - return kvDataEntries; - } - KVDataEntry[] resolveKvDataEntries = new KVDataEntry[kvDataEntries.length]; - // kvDataEntries是代理对象,需要处理 - for (int i = 0; i < kvDataEntries.length; i++) { - KVDataEntry kvDataEntry = kvDataEntries[i]; - String key = kvDataEntry.getKey(); - long version = kvDataEntry.getVersion(); - DataType dataType = kvDataEntry.getType(); - KvData innerKvData = new KvData(key, version, dataType); - Object valueObj = kvDataEntry.getValue(); - switch (dataType) { - case NIL: - break; - case BYTES: - case TEXT: - case JSON: - case XML: - innerKvData.setValue(valueObj.toString()); - break; - case INT32: - innerKvData.setValue(Integer.parseInt(valueObj.toString())); - break; - case INT64: - innerKvData.setValue(Long.parseLong(valueObj.toString())); - break; - default: - throw new IllegalStateException("Unsupported value type[" + dataType + "] to resolve!"); - } - resolveKvDataEntries[i] = innerKvData; - } - return resolveKvDataEntries; - } - - public static Operation read(Operation operation) { - - try { - // Class - Class clazz = operation.getClass(); - Field field = clazz.getSuperclass().getDeclaredField("h"); - field.setAccessible(true); - Object object = field.get(operation); - if (object instanceof JSONObject) { - JSONObject jsonObject = (JSONObject) object; - if (jsonObject.containsKey("accountID")) { - return convertDataAccountRegisterOperation(jsonObject); - } else if (jsonObject.containsKey("userID")) { - return convertUserRegisterOperation(jsonObject); - } else if (jsonObject.containsKey("contractID")) { - return convertContractCodeDeployOperation(jsonObject); - } else if (jsonObject.containsKey("writeSet")) { - return convertDataAccountKVSetOperation(jsonObject); - } else if (jsonObject.containsKey("initSetting")) { - return convertLedgerInitOperation(jsonObject); - } else if (jsonObject.containsKey("contractAddress")) { - return convertContractEventSendOperation(jsonObject); - } - } - } catch (Exception e) { - throw new RuntimeException(e); - } - - return null; - } - - public static Object readValueByBytesValue(BytesValue bytesValue) { - DataType dataType = bytesValue.getType(); - Bytes saveVal = bytesValue.getValue(); - Object showVal; - switch (dataType) { - case BYTES: - // return hex - showVal = HexUtils.encode(saveVal.toBytes()); - break; - case TEXT: - case JSON: - showVal = saveVal.toUTF8String(); - break; - case INT64: - showVal = BytesUtils.toLong(saveVal.toBytes()); - break; - default: - showVal = HexUtils.encode(saveVal.toBytes()); - break; - } - return showVal; - } - - public static DataAccountRegisterOperation convertDataAccountRegisterOperation(JSONObject jsonObject) { - JSONObject account = jsonObject.getJSONObject("accountID"); - return new DataAccountRegisterOpTemplate(blockchainIdentity(account)); - } - - public static DataAccountKVSetOperation convertDataAccountKVSetOperation(JSONObject jsonObject) { - // 写入集合处理 - JSONArray writeSetObj = jsonObject.getJSONArray("writeSet"); - JSONObject accountAddrObj = jsonObject.getJSONObject("accountAddress"); - String addressBase58 = accountAddrObj.getString("value"); - Bytes address = Bytes.fromBase58(addressBase58); - - DataAccountKVSetOpTemplate kvOperation = new DataAccountKVSetOpTemplate(address); - for (int i = 0; i clazz = operation.getClass(); + Field field = clazz.getSuperclass().getDeclaredField("h"); + field.setAccessible(true); + Object object = field.get(operation); + if (object instanceof JSONObject) { + JSONObject jsonObject = (JSONObject) object; + if (jsonObject.containsKey("accountID")) { + return convertDataAccountRegisterOperation(jsonObject); + } else if (jsonObject.containsKey("userID")) { + return convertUserRegisterOperation(jsonObject); + } else if (jsonObject.containsKey("contractID")) { + return convertContractCodeDeployOperation(jsonObject); + } else if (jsonObject.containsKey("writeSet")) { + return convertDataAccountKVSetOperation(jsonObject); + } else if (jsonObject.containsKey("initSetting")) { + return convertLedgerInitOperation(jsonObject); + } else if (jsonObject.containsKey("contractAddress")) { + return convertContractEventSendOperation(jsonObject); + } + } + } catch (Exception e) { + throw new RuntimeException(e); + } + + return null; + } + + public static Object readValueByBytesValue(BytesValue bytesValue) { + DataType dataType = bytesValue.getType(); + Bytes saveVal = bytesValue.getValue(); + Object showVal; + switch (dataType) { + case BYTES: + // return hex + showVal = HexUtils.encode(saveVal.toBytes()); + break; + case TEXT: + case JSON: + showVal = saveVal.toUTF8String(); + break; + case INT64: + showVal = BytesUtils.toLong(saveVal.toBytes()); + break; + default: + showVal = HexUtils.encode(saveVal.toBytes()); + break; + } + return showVal; + } + + public static DataAccountRegisterOperation convertDataAccountRegisterOperation(JSONObject jsonObject) { + JSONObject account = jsonObject.getJSONObject("accountID"); + return new DataAccountRegisterOpTemplate(blockchainIdentity(account)); + } + + public static DataAccountKVSetOperation convertDataAccountKVSetOperation(JSONObject jsonObject) { + // 写入集合处理 + JSONArray writeSetObj = jsonObject.getJSONArray("writeSet"); + JSONObject accountAddrObj = jsonObject.getJSONObject("accountAddress"); + String addressBase58 = accountAddrObj.getString("value"); + Bytes address = Bytes.fromBase58(addressBase58); + + DataAccountKVSetOpTemplate kvOperation = new DataAccountKVSetOpTemplate(address); + for (int i = 0; i < writeSetObj.size(); i++) { + JSONObject currWriteSetObj = writeSetObj.getJSONObject(i); + long expectedVersion = currWriteSetObj.getLong("expectedVersion"); + JSONObject valueObj = currWriteSetObj.getJSONObject("value"); + String typeStr = valueObj.getString("type"); + // Base58Utils.decode(valueObj.getJSONObject("value").getString("value")) + String realValBase58 = valueObj.getJSONObject("value").getString("value"); + String key = currWriteSetObj.getString("key"); + DataType dataType = DataType.valueOf(typeStr); + BytesValue bytesValue = BytesData.fromType(dataType, Base58Utils.decode(realValBase58)); + KVData kvData = new KVData(key, bytesValue, expectedVersion); + kvOperation.set(kvData); + } + + return kvOperation; + } + + public static LedgerInitOperation convertLedgerInitOperation(JSONObject jsonObject) { + JSONObject legerInitObj = jsonObject.getJSONObject("initSetting"); + LedgerInitData ledgerInitSettingData = new LedgerInitData(); + String ledgerSeedStr = legerInitObj.getString("ledgerSeed"); + + // 种子需要做Base64转换 + ledgerInitSettingData.setLedgerSeed(Base64.decodeBase64(BytesUtils.toBytes(ledgerSeedStr))); + + String consensusProvider = legerInitObj.getString("consensusProvider"); + + ledgerInitSettingData.setConsensusProvider(consensusProvider); + + JSONObject cryptoSettingObj = legerInitObj.getJSONObject("cryptoSetting"); + boolean autoVerifyHash = cryptoSettingObj.getBoolean("autoVerifyHash"); + short hashAlgorithm = cryptoSettingObj.getShort("hashAlgorithm"); + + CryptoConfig cryptoConfig = new CryptoConfig(); + + cryptoConfig.setAutoVerifyHash(autoVerifyHash); + + cryptoConfig.setHashAlgorithm(hashAlgorithm); + + ledgerInitSettingData.setCryptoSetting(cryptoConfig); + + JSONObject consensusSettingsObj = legerInitObj.getJSONObject("consensusSettings"); + Bytes consensusSettings = Bytes.fromBase58(consensusSettingsObj.getString("value")); + + ledgerInitSettingData.setConsensusSettings(consensusSettings); + + JSONArray consensusParticipantsArray = legerInitObj.getJSONArray("consensusParticipants"); + + if (!consensusParticipantsArray.isEmpty()) { + ParticipantNode[] participantNodes = new ParticipantNode[consensusParticipantsArray.size()]; + for (int i = 0; i < consensusParticipantsArray.size(); i++) { + JSONObject currConsensusParticipant = consensusParticipantsArray.getJSONObject(i); + Bytes address = Bytes.fromBase58(currConsensusParticipant.getString("address")); + String name = currConsensusParticipant.getString("name"); + int id = currConsensusParticipant.getInteger("id"); + JSONObject pubKeyObj = currConsensusParticipant.getJSONObject("pubKey"); + String pubKeyBase58 = pubKeyObj.getString("value"); + // 生成ParticipantNode对象 + ParticipantCertData participantCertData = new ParticipantCertData(id, addressBase58, name, new PubKey(Bytes.fromBase58(pubKeyBase58).toBytes())); + new PubKey(Bytes.fromBase58(pubKeyBase58).toBytes())); + participantNodes[i] = participantCertData; + } + ledgerInitSettingData.setConsensusParticipants(participantNodes); + } + + return new LedgerInitOpTemplate(ledgerInitSettingData); + } + + public static UserRegisterOperation convertUserRegisterOperation(JSONObject jsonObject) { + JSONObject user = jsonObject.getJSONObject("userID"); + return new UserRegisterOpTemplate(blockchainIdentity(user)); + } + + public static ContractCodeDeployOperation convertContractCodeDeployOperation(JSONObject jsonObject) { + JSONObject contract = jsonObject.getJSONObject("contractID"); + BlockchainIdentityData blockchainIdentity = blockchainIdentity(contract); + + String chainCodeStr = jsonObject.getString("chainCode"); + ContractCodeDeployOpTemplate contractCodeDeployOpTemplate = new ContractCodeDeployOpTemplate(blockchainIdentity, + BytesUtils.toBytes(chainCodeStr)); + return contractCodeDeployOpTemplate; + } + + public static ContractEventSendOperation convertContractEventSendOperation(JSONObject jsonObject) { + JSONObject contractAddressObj = jsonObject.getJSONObject("contractAddress"); + String contractAddress = contractAddressObj.getString("value"); + String argsStr = jsonObject.getString("args"); + String event = jsonObject.getString("event"); + return new ContractEventSendOpTemplate(Bytes.fromBase58(contractAddress), event, + BytesValueEncoding.encodeArray(new Object[] { argsStr }, null)); + } + + private static BlockchainIdentityData blockchainIdentity(JSONObject jsonObject) { + JSONObject addressObj = jsonObject.getJSONObject("address"); + // base58值 + String addressBase58 = addressObj.getString("value"); + Bytes address = Bytes.fromBase58(addressBase58); + + JSONObject pubKeyObj = jsonObject.getJSONObject("pubKey"); + // base58值 + String pubKeyBase58 = pubKeyObj.getString("value"); + PubKey pubKey = new PubKey(Bytes.fromBase58(pubKeyBase58).toBytes()); + + // 生成对应的对象 + return new BlockchainIdentityData(address, pubKey); + } + + public static class CryptoConfig implements CryptoSetting { + + private short hashAlgorithm; + + private boolean autoVerifyHash; + + @Override + public CryptoProvider[] getSupportedProviders() { + return new CryptoProvider[0]; + } + + @Override + public short getHashAlgorithm() { + return hashAlgorithm; + } + + @Override + public boolean getAutoVerifyHash() { + return autoVerifyHash; + } + + public void setHashAlgorithm(short hashAlgorithm) { + this.hashAlgorithm = hashAlgorithm; + } + + public void setAutoVerifyHash(boolean autoVerifyHash) { + this.autoVerifyHash = autoVerifyHash; + } + } + + public static class ParticipantCertData implements ParticipantNode { + private int id; + private Bytes address; + private String name; + private PubKey pubKey; private ParticipantNodeState participantNodeState; - public ParticipantCertData() { - } + public ParticipantCertData() { + } - public ParticipantCertData(ParticipantNode participantNode) { - this.address = participantNode.getAddress(); - this.name = participantNode.getName(); - this.pubKey = participantNode.getPubKey(); - } + public ParticipantCertData(ParticipantNode participantNode) { + this.address = participantNode.getAddress(); + this.name = participantNode.getName(); + this.pubKey = participantNode.getPubKey(); + } - public ParticipantCertData(int id, String address, String name, PubKey pubKey, ParticipantNodeState participantNodeState) { - this.id = id; - this.address = address; - this.name = name; - this.pubKey = pubKey; + public ParticipantCertData(int id, String address, String name, PubKey pubKey) { + this.id = id; + this.address = address; + this.name = name; + this.pubKey = pubKey; this.participantNodeState = participantNodeState; - } + } - @Override - public String getAddress() { - return address; - } + @Override + public Bytes getAddress() { + return address; + } - @Override - public String getName() { - return name; - } + @Override + public String getName() { + return name; + } - @Override - public PubKey getPubKey() { - return pubKey; - } + @Override + public PubKey getPubKey() { + return pubKey; + } - public int getId() { - return id; - } + public int getId() { + return id; + } - public void setId(int id) { - this.id = id; - } + public void setId(int id) { + this.id = id; + } @Override public ParticipantNodeState getParticipantNodeState() { return participantNodeState; } - } + } - public static class KvData implements KVDataEntry { + public static class KvData implements KVDataEntry { - private String key; + private String key; - private long version; + private long version; - private DataType dataType; + private DataType dataType; - private Object value; + private Object value; - public KvData() { - } + public KvData() { + } - public KvData(String key, long version, DataType dataType) { - this(key, version, dataType, null); - } + public KvData(String key, long version, DataType dataType) { + this(key, version, dataType, null); + } - public KvData(String key, long version, DataType dataType, Object value) { - this.key = key; - this.version = version; - this.dataType = dataType; - this.value = value; - } + public KvData(String key, long version, DataType dataType, Object value) { + this.key = key; + this.version = version; + this.dataType = dataType; + this.value = value; + } - public void setKey(String key) { - this.key = key; - } + public void setKey(String key) { + this.key = key; + } - public void setVersion(long version) { - this.version = version; - } + public void setVersion(long version) { + this.version = version; + } - public void setDataType(DataType dataType) { - this.dataType = dataType; - } + public void setDataType(DataType dataType) { + this.dataType = dataType; + } - public void setValue(Object value) { - this.value = value; - } + public void setValue(Object value) { + this.value = value; + } - @Override - public String getKey() { - return key; - } + @Override + public String getKey() { + return key; + } - @Override - public long getVersion() { - return version; - } + @Override + public long getVersion() { + return version; + } - @Override - public DataType getType() { - return dataType; - } + @Override + public DataType getType() { + return dataType; + } - @Override - public Object getValue() { - return value; - } - } + @Override + public Object getValue() { + return value; + } + } } \ No newline at end of file diff --git a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/proxy/BlockchainServiceProxy.java b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/proxy/BlockchainServiceProxy.java index c850b57a..ff1c9176 100644 --- a/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/proxy/BlockchainServiceProxy.java +++ b/source/sdk/sdk-base/src/main/java/com/jd/blockchain/sdk/proxy/BlockchainServiceProxy.java @@ -1,7 +1,19 @@ package com.jd.blockchain.sdk.proxy; import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.*; +import com.jd.blockchain.ledger.AccountHeader; +import com.jd.blockchain.ledger.ContractInfo; +import com.jd.blockchain.ledger.KVDataEntry; +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.TransactionState; +import com.jd.blockchain.ledger.TransactionTemplate; +import com.jd.blockchain.ledger.UserInfo; import com.jd.blockchain.sdk.BlockchainEventHandle; import com.jd.blockchain.sdk.BlockchainEventListener; import com.jd.blockchain.sdk.BlockchainService; @@ -32,6 +44,11 @@ public abstract class BlockchainServiceProxy implements BlockchainService { public LedgerInfo getLedger(HashDigest ledgerHash) { return getQueryService(ledgerHash).getLedger(ledgerHash); } + + @Override + public LedgerAdminInfo getLedgerAdminInfo(HashDigest ledgerHash) { + return getQueryService(ledgerHash).getLedgerAdminInfo(ledgerHash); + } @Override public ParticipantNode[] getConsensusParticipants(HashDigest ledgerHash) { diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/contract/samples/AssetContract.java b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/contract/samples/AssetContract.java index a6b91415..065e86d2 100644 --- a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/contract/samples/AssetContract.java +++ b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/contract/samples/AssetContract.java @@ -4,7 +4,7 @@ import com.jd.blockchain.contract.Contract; import com.jd.blockchain.contract.ContractEvent; /** - * 示例:一个“资产管理”智能合约; + * 示例:一个“资产管理”智能合约; * * @author huanghaiquan * @@ -15,10 +15,8 @@ public interface AssetContract { /** * 发行资产; * - * @param amount - * 新发行的资产数量; - * @param assetHolderAddress - * 新发行的资产的持有账户; + * @param amount 新发行的资产数量; + * @param assetHolderAddress 新发行的资产的持有账户; */ @ContractEvent(name = "issue-asset") void issue(long amount, String assetHolderAddress); @@ -26,14 +24,12 @@ public interface AssetContract { /** * 转移资产 * - * @param fromAddress - * 转出账户; - * @param toAddress - * 转入账户; - * @param amount - * 转移的资产数额; + * @param fromAddress 转出账户; + * @param toAddress 转入账户; + * @param amount 转移的资产数额; + * @return 返回转出账户的余额; */ @ContractEvent(name = "transfer-asset") - void transfer(String fromAddress, String toAddress, long amount); + long transfer(String fromAddress, String toAddress, long amount); } \ No newline at end of file diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/contract/samples/AssetContractImpl.java b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/contract/samples/AssetContractImpl.java index 02258ed2..d662378d 100644 --- a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/contract/samples/AssetContractImpl.java +++ b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/contract/samples/AssetContractImpl.java @@ -11,6 +11,7 @@ import com.jd.blockchain.crypto.HashDigest; import com.jd.blockchain.ledger.BlockchainIdentity; import com.jd.blockchain.ledger.KVDataEntry; import com.jd.blockchain.ledger.KVDataObject; +import com.jd.blockchain.utils.Bytes; /** * 示例:一个“资产管理”智能合约的实现; @@ -48,59 +49,54 @@ public class AssetContractImpl implements EventProcessingAware, AssetContract { // 查询当前值; KVDataEntry[] kvEntries = eventContext.getLedger().getDataEntries(currentLedgerHash(), ASSET_ADDRESS, KEY_TOTAL, assetHolderAddress); - + // 计算资产的发行总数; KVDataObject currTotal = (KVDataObject) kvEntries[0]; long newTotal = currTotal.longValue() + amount; - eventContext.getLedger().dataAccount(ASSET_ADDRESS).setInt64(KEY_TOTAL, newTotal, - currTotal.getVersion()); - + eventContext.getLedger().dataAccount(ASSET_ADDRESS).setInt64(KEY_TOTAL, newTotal, currTotal.getVersion()); + // 分配到持有者账户; KVDataObject holderAmount = (KVDataObject) kvEntries[1]; long newHodlerAmount = holderAmount.longValue() + amount; - eventContext.getLedger().dataAccount(ASSET_ADDRESS).setInt64(assetHolderAddress, newHodlerAmount, - holderAmount.getVersion()).setText("K2", "info2", -1).setText("k3", "info3", 3); - + eventContext.getLedger().dataAccount(ASSET_ADDRESS) + .setInt64(assetHolderAddress, newHodlerAmount, holderAmount.getVersion()).setText("K2", "info2", -1) + .setText("k3", "info3", 3); + } @Override - public void transfer(String fromAddress, String toAddress, long amount) { - // if (amount < 0) { - // throw new ContractError("The amount is negative!"); - // } - // if (amount == 0) { - // return; - // } - // - // //校验“转出账户”是否已签名; - // checkSignerPermission(fromAddress); - // - // // 查询现有的余额; - // Set keys = new HashSet<>(); - // keys.add(fromAddress); - // keys.add(toAddress); - // StateMap origBalances = - // eventContext.getLedger().getStates(currentLedgerHash(), ASSET_ADDRESS, keys); - // KVDataObject fromBalance = origBalances.get(fromAddress); - // KVDataObject toBalance = origBalances.get(toAddress); - // - // //检查是否余额不足; - // if ((fromBalance.longValue() - amount) < 0) { - // throw new ContractError("Insufficient balance!"); - // } - // - // // 把数据的更改写入到账本; - // SimpleStateMap newBalances = new SimpleStateMap(origBalances.getAccount(), - // origBalances.getAccountVersion(), - // origBalances.getStateVersion()); - // KVDataObject newFromBalance = fromBalance.newLong(fromBalance.longValue() - - // amount); - // KVDataObject newToBalance = toBalance.newLong(toBalance.longValue() + - // amount); - // newBalances.setValue(newFromBalance); - // newBalances.setValue(newToBalance); - // - // eventContext.getLedger().updateState(ASSET_ADDRESS).setStates(newBalances); + public long transfer(String fromAddress, String toAddress, long amount) { + if (amount < 0) { + throw new ContractException("The amount is negative!"); + } + if (amount > 20000) { + throw new ContractException("The amount exceeds the limit of 20000!"); + } + + // 校验“转出账户”是否已签名; + checkSignerPermission(fromAddress); + + // 查询现有的余额; + KVDataEntry[] origBalances = eventContext.getLedger().getDataEntries(currentLedgerHash(), ASSET_ADDRESS, + fromAddress, toAddress); + KVDataEntry fromBalanceKV = origBalances[0]; + KVDataEntry toBalanceKV = origBalances[1]; + long fromBalance = fromBalanceKV.getVersion() == -1 ? 0 : (long) fromBalanceKV.getValue(); + long toBalance = toBalanceKV.getVersion() == -1 ? 0 : (long) toBalanceKV.getValue(); + + // 检查是否余额不足; + + if ((fromBalance - amount) < 0) { + throw new ContractException("The balance is insufficient and the transfer failed!"); + } + fromBalance = fromBalance + amount; + toBalance = toBalance + amount; + + // 把数据的更改写入到账本; + eventContext.getLedger().dataAccount(fromAddress).setInt64(ASSET_ADDRESS, fromBalance, fromBalanceKV.getVersion()); + eventContext.getLedger().dataAccount(toAddress).setInt64(ASSET_ADDRESS, toBalance, toBalanceKV.getVersion()); + + return -1; } // ------------------------------------------------------------- @@ -117,9 +113,9 @@ public class AssetContractImpl implements EventProcessingAware, AssetContract { throw new ContractException("Permission Error! -- The requestors is not exactlly being owners!"); } - Map ownerMap = new HashMap<>(); + Map ownerMap = new HashMap<>(); for (BlockchainIdentity o : owners) { - ownerMap.put(o.getAddress().toBase58(), o); + ownerMap.put(o.getAddress(), o); } for (BlockchainIdentity r : requestors) { if (!ownerMap.containsKey(r.getAddress())) { diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_ConfigureSecurity.java b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_ConfigureSecurity.java new file mode 100644 index 00000000..d7d2170b --- /dev/null +++ b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_ConfigureSecurity.java @@ -0,0 +1,97 @@ +/** + * Copyright: Copyright 2016-2020 JD.COM All Right Reserved + * FileName: com.jd.blockchain.sdk.samples.SDKDemo_RegisterUser + * Author: shaozhuguang + * Department: 区块链研发部 + * Date: 2018/10/18 下午2:00 + * Description: 注册用户 + */ +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.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; +import com.jd.blockchain.ledger.*; +import com.jd.blockchain.sdk.BlockchainService; +import com.jd.blockchain.sdk.client.GatewayServiceFactory; +import com.jd.blockchain.utils.ConsoleUtils; + +/** + * 注册用户 + * + * @author shaozhuguang + * @create 2018/10/18 + * @since 1.0.0 + */ + +public class SDKDemo_ConfigureSecurity { + 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]); + } + + // 注册相关class + DataContractRegistry.register(TransactionContent.class); + DataContractRegistry.register(TransactionContentBody.class); + DataContractRegistry.register(TransactionRequest.class); + DataContractRegistry.register(NodeRequest.class); + DataContractRegistry.register(EndpointRequest.class); + DataContractRegistry.register(TransactionResponse.class); + + PrivKey privKey = SDKDemo_Params.privkey1; + PubKey pubKey = SDKDemo_Params.pubKey1; + + 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 signer = getSigner(); + + BlockchainKeypair user = BlockchainKeyGenerator.getInstance().generate(); + + // 注册 + txTemp.users().register(user.getIdentity()); + + txTemp.security().roles() + .configure("ADMIN") + .enable(LedgerPermission.REGISTER_USER, LedgerPermission.REGISTER_DATA_ACCOUNT) + .enable(TransactionPermission.DIRECT_OPERATION) + .configure("GUEST") + .enable(TransactionPermission.CONTRACT_OPERATION); + + txTemp.security().authorziations() + .forUser(user.getIdentity()) + .authorize("ADMIN", "MANAGER") + .forUser(CLIENT_CERT.getAddress()) + .authorize("GUEST"); + + // TX 准备就绪; + PreparedTransaction prepTx = txTemp.prepare(); + + // 使用私钥进行签名; + prepTx.sign(signer); + + // 提交交易; + TransactionResponse transactionResponse = prepTx.commit(); + + ConsoleUtils.info("register user complete, result is [%s]", transactionResponse.isSuccess()); + } + + private static AsymmetricKeypair getSigner() { + return new BlockchainKeypair(SDKDemo_Params.pubKey1, SDKDemo_Params.privkey1); + } +} \ No newline at end of file diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Contract.java b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Contract.java index 3059aaac..06ec1801 100644 --- a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Contract.java +++ b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Contract.java @@ -11,6 +11,8 @@ import com.jd.blockchain.ledger.PreparedTransaction; import com.jd.blockchain.ledger.TransactionTemplate; import com.jd.blockchain.sdk.BlockchainService; import com.jd.blockchain.sdk.client.GatewayServiceFactory; +import com.jd.blockchain.transaction.ContractReturnValue; +import com.jd.blockchain.transaction.LongValueHolder; import com.jd.blockchain.utils.io.ByteArray; import com.jd.blockchain.utils.net.NetworkAddress; import com.jd.blockchain.utils.serialize.json.JSONSerializeUtils; @@ -49,8 +51,6 @@ public class SDKDemo_Contract { BlockchainService service = serviceFactory.getBlockchainService(); HashDigest ledgerHash = getLedgerHash(); - // 发起交易; - TransactionTemplate txTemp = service.newTransaction(ledgerHash); // -------------------------------------- // 一个贸易账户,贸易结算后的利润将通过一个合约账户来执行利润分配; @@ -71,25 +71,26 @@ public class SDKDemo_Contract { // 备注信息; Remark remark = new Remark(); String remarkJSON = JSONSerializeUtils.serializeToJSON(remark); - + + // 发起交易; + TransactionTemplate txTemp = service.newTransaction(ledgerHash); + AssetContract assetContract = txTemp.contract(profitDistributionContract, AssetContract.class); assetContract.issue(1000, receiptorAccount1); - assetContract.transfer(receiptorAccount1, receiptorAccount2, 600); - -// assetContract. - - // -------------------------------------- + LongValueHolder balance = ContractReturnValue.decode(assetContract.transfer(receiptorAccount1, receiptorAccount2, 600)); // TX 准备就绪; PreparedTransaction prepTx = txTemp.prepare(); - String txHash = ByteArray.toBase64(prepTx.getHash().toBytes()); // 使用私钥进行签名; - AsymmetricKeypair keyPair = getSponsorKey(); + AsymmetricKeypair keyPair = getSponsorKey();//示例方法,取发起人的私钥; prepTx.sign(keyPair); // 提交交易; prepTx.commit(); + + //获取返回值; + System.out.println("balance = " + balance.get()); } private static HashDigest getLedgerHash() { diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Params.java b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Params.java index 491abef8..cc2c5bb2 100644 --- a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Params.java +++ b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_Params.java @@ -8,9 +8,9 @@ */ package com.jd.blockchain.sdk.samples; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.tools.keygen.KeyGenCommand; /** * @@ -33,13 +33,13 @@ public class SDKDemo_Params { "177gk2FpjufgEon92mf2oRRFXDBZkRy8SkFci7Jxc5pApZEJz3oeCoxieWatDD3Xg7i1QEN", "177gjvv7qvfCAXroFezSn23UFXLVLFofKS3y6DXkJ2DwVWS4LcRNtxRgiqWmQEeWNz4KQ3J" }; - public static PrivKey privkey0 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[0], PASSWORD); - public static PrivKey privkey1 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD); - public static PrivKey privkey2 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD); - public static PrivKey privkey3 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD); + public static PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[0], PASSWORD); + public static PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD); + public static PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD); + public static PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD); - public static PubKey pubKey0 = KeyGenCommand.decodePubKey(PUB_KEYS[0]); - public static PubKey pubKey1 = KeyGenCommand.decodePubKey(PUB_KEYS[1]); - public static PubKey pubKey2 = KeyGenCommand.decodePubKey(PUB_KEYS[2]); - public static PubKey pubKey3 = KeyGenCommand.decodePubKey(PUB_KEYS[3]); + public static PubKey pubKey0 = KeyGenUtils.decodePubKey(PUB_KEYS[0]); + public static PubKey pubKey1 = KeyGenUtils.decodePubKey(PUB_KEYS[1]); + public static PubKey pubKey2 = KeyGenUtils.decodePubKey(PUB_KEYS[2]); + public static PubKey pubKey3 = KeyGenUtils.decodePubKey(PUB_KEYS[3]); } \ No newline at end of file diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterUser.java b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterUser.java index a1362a39..778e5851 100644 --- a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterUser.java +++ b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDKDemo_RegisterUser.java @@ -20,60 +20,67 @@ import com.jd.blockchain.utils.ConsoleUtils; /** * 注册用户 + * * @author shaozhuguang * @create 2018/10/18 * @since 1.0.0 */ public class SDKDemo_RegisterUser { - public static void main(String[] args) { + 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]); - } + 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]); + } - // 注册相关class - DataContractRegistry.register(TransactionContent.class); - DataContractRegistry.register(TransactionContentBody.class); - DataContractRegistry.register(TransactionRequest.class); - DataContractRegistry.register(NodeRequest.class); - DataContractRegistry.register(EndpointRequest.class); - DataContractRegistry.register(TransactionResponse.class); + // 注册相关class + DataContractRegistry.register(TransactionContent.class); + DataContractRegistry.register(TransactionContentBody.class); + DataContractRegistry.register(TransactionRequest.class); + DataContractRegistry.register(NodeRequest.class); + DataContractRegistry.register(EndpointRequest.class); + DataContractRegistry.register(TransactionResponse.class); - PrivKey privKey = SDKDemo_Params.privkey1; - PubKey pubKey = SDKDemo_Params.pubKey1; + PrivKey privKey = SDKDemo_Params.privkey1; + PubKey pubKey = SDKDemo_Params.pubKey1; - BlockchainKeypair CLIENT_CERT = new BlockchainKeypair(SDKDemo_Params.pubKey0, SDKDemo_Params.privkey0); + 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(); + 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]); + HashDigest[] ledgerHashs = service.getLedgerHashs(); + // 在本地定义注册账号的 TX; + TransactionTemplate txTemp = service.newTransaction(ledgerHashs[0]); - //existed signer - AsymmetricKeypair keyPair = new BlockchainKeypair(pubKey, privKey); + // existed signer + AsymmetricKeypair keyPair = new BlockchainKeypair(pubKey, privKey); - BlockchainKeypair user = BlockchainKeyGenerator.getInstance().generate(); + BlockchainKeypair user = BlockchainKeyGenerator.getInstance().generate(); - // 注册 - txTemp.users().register(user.getIdentity()); + // 注册 + txTemp.users().register(user.getIdentity()); - // TX 准备就绪; - PreparedTransaction prepTx = txTemp.prepare(); + // 定义角色权限; + txTemp.security().roles().configure("MANAGER") + .enable(LedgerPermission.REGISTER_USER, LedgerPermission.REGISTER_DATA_ACCOUNT) + .enable(TransactionPermission.CONTRACT_OPERATION); + txTemp.security().authorziations().forUser(user.getIdentity()).authorize("MANAGER"); - // 使用私钥进行签名; - prepTx.sign(keyPair); + // TX 准备就绪; + PreparedTransaction prepTx = txTemp.prepare(); - // 提交交易; - TransactionResponse transactionResponse = prepTx.commit(); + // 使用私钥进行签名; + prepTx.sign(keyPair); - ConsoleUtils.info("register user complete, result is [%s]", transactionResponse.isSuccess()); - } + // 提交交易; + TransactionResponse transactionResponse = prepTx.commit(); + + ConsoleUtils.info("register user complete, result is [%s]", transactionResponse.isSuccess()); + } } \ No newline at end of file diff --git a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Base_Demo.java b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Base_Demo.java index bbd4ed71..c2a7ce73 100644 --- a/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Base_Demo.java +++ b/source/sdk/sdk-samples/src/main/java/com/jd/blockchain/sdk/samples/SDK_Base_Demo.java @@ -1,6 +1,7 @@ package com.jd.blockchain.sdk.samples; import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.ledger.BlockchainKeypair; @@ -9,7 +10,6 @@ import com.jd.blockchain.ledger.TransactionResponse; import com.jd.blockchain.ledger.TransactionTemplate; import com.jd.blockchain.sdk.BlockchainService; import com.jd.blockchain.sdk.client.GatewayServiceFactory; -import com.jd.blockchain.tools.keygen.KeyGenCommand; public abstract class SDK_Base_Demo { @@ -25,9 +25,9 @@ public abstract class SDK_Base_Demo { public void init() { // 生成连接网关的账号 - PrivKey privKey = KeyGenCommand.decodePrivKeyWithRawPassword(SDKDemo_Constant.PRIV_KEYS[0], SDKDemo_Constant.PASSWORD); + PrivKey privKey = KeyGenUtils.decodePrivKeyWithRawPassword(SDKDemo_Constant.PRIV_KEYS[0], SDKDemo_Constant.PASSWORD); - PubKey pubKey = KeyGenCommand.decodePubKey(SDKDemo_Constant.PUB_KEYS[0]); + PubKey pubKey = KeyGenUtils.decodePubKey(SDKDemo_Constant.PUB_KEYS[0]); adminKey = new BlockchainKeypair(pubKey, privKey); diff --git a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDKDemo_Contract_Test_.java b/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDKDemo_Contract_Test_.java index 2f7755da..4390c48c 100644 --- a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDKDemo_Contract_Test_.java +++ b/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDKDemo_Contract_Test_.java @@ -8,6 +8,7 @@ import org.junit.Test; import com.jd.blockchain.contract.TransferContract; import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.ledger.BlockchainKeyGenerator; @@ -18,9 +19,8 @@ import com.jd.blockchain.ledger.TransactionTemplate; import com.jd.blockchain.sdk.BlockchainService; import com.jd.blockchain.sdk.client.GatewayServiceFactory; import com.jd.blockchain.sdk.samples.SDKDemo_Constant; -import com.jd.blockchain.tools.keygen.KeyGenCommand; -import com.jd.blockchain.transaction.LongValueHolder; import com.jd.blockchain.transaction.GenericValueHolder; +import com.jd.blockchain.transaction.LongValueHolder; import com.jd.blockchain.utils.Bytes; public class SDKDemo_Contract_Test_ { @@ -34,10 +34,10 @@ public class SDKDemo_Contract_Test_ { @Before public void init() { // 生成连接网关的账号 - PrivKey privKey = KeyGenCommand.decodePrivKeyWithRawPassword(SDKDemo_Constant.PRIV_KEYS[0], + PrivKey privKey = KeyGenUtils.decodePrivKeyWithRawPassword(SDKDemo_Constant.PRIV_KEYS[0], SDKDemo_Constant.PASSWORD); - PubKey pubKey = KeyGenCommand.decodePubKey(SDKDemo_Constant.PUB_KEYS[0]); + PubKey pubKey = KeyGenUtils.decodePubKey(SDKDemo_Constant.PUB_KEYS[0]); adminKey = new BlockchainKeypair(pubKey, privKey); diff --git a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_KeyPair_Para.java b/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_KeyPair_Para.java index 450e5ff4..706cd370 100644 --- a/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_KeyPair_Para.java +++ b/source/sdk/sdk-samples/src/test/java/test/com/jd/blockchain/sdk/test/SDK_GateWay_KeyPair_Para.java @@ -1,8 +1,8 @@ package test.com.jd.blockchain.sdk.test; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.tools.keygen.KeyGenCommand; /** * Created by zhangshuang3 on 2018/10/17. @@ -21,14 +21,14 @@ public class SDK_GateWay_KeyPair_Para { "177gjtwLgmSx5v1hFb46ijh7L9kdbKUpJYqdKVf9afiEmAuLgo8Rck9yu5UuUcHknWJuWaF", "177gk1pudweTq5zgJTh8y3ENCTwtSFsKyX7YnpuKPo7rKgCkCBXVXh5z2syaTCPEMbuWRns" }; - public static PrivKey privkey0 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[0], PASSWORD); - public static PrivKey privkey1 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD); - public static PrivKey privkey2 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD); - public static PrivKey privkey3 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD); + public static PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[0], PASSWORD); + public static PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD); + public static PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD); + public static PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD); - public static PubKey pubKey0 = KeyGenCommand.decodePubKey(PUB_KEYS[0]); - public static PubKey pubKey1 = KeyGenCommand.decodePubKey(PUB_KEYS[1]); - public static PubKey pubKey2 = KeyGenCommand.decodePubKey(PUB_KEYS[2]); - public static PubKey pubKey3 = KeyGenCommand.decodePubKey(PUB_KEYS[3]); + public static PubKey pubKey0 = KeyGenUtils.decodePubKey(PUB_KEYS[0]); + public static PubKey pubKey1 = KeyGenUtils.decodePubKey(PUB_KEYS[1]); + public static PubKey pubKey2 = KeyGenUtils.decodePubKey(PUB_KEYS[2]); + public static PubKey pubKey3 = KeyGenUtils.decodePubKey(PUB_KEYS[3]); } diff --git a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/MemoryKVStorage.java b/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/MemoryKVStorage.java index 65920967..0c2192a3 100644 --- a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/MemoryKVStorage.java +++ b/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/MemoryKVStorage.java @@ -12,11 +12,6 @@ import com.jd.blockchain.utils.io.BytesMap; public class MemoryKVStorage implements ExPolicyKVStorage, VersioningKVStorage, KVStorageService, BytesMap { -// private Set keys = new HashSet<>(); - -// private Set keys = Collections.synchronizedSet(new HashSet<>()); - -// private Map storageMap = new ConcurrentHashMap<>(); private ExistancePolicyKVStorageMap exStorage = new ExistancePolicyKVStorageMap(); private VersioningKVStorageMap verStorage = new VersioningKVStorageMap(); @@ -38,10 +33,6 @@ public class MemoryKVStorage implements ExPolicyKVStorage, VersioningKVStorage, @Override public long set(Bytes key, byte[] value, long version) { return verStorage.set(key, value, version); -// if (v > -1) { -// keys.add(key); -// } -// return v; } @Override @@ -57,10 +48,6 @@ public class MemoryKVStorage implements ExPolicyKVStorage, VersioningKVStorage, @Override public boolean set(Bytes key, byte[] value, ExPolicy ex) { return exStorage.set(key, value, ex); -// if (ok) { -// keys.add(key); -// } -// return ok; } @Override @@ -81,12 +68,10 @@ public class MemoryKVStorage implements ExPolicyKVStorage, VersioningKVStorage, HashSet keySet = new HashSet<>(exStorage.keySet()); keySet.addAll(verStorage.keySet()); return keySet; -// return storageMap.keySet(); } public int getStorageCount() { return exStorage.getCount() + verStorage.getCount(); -// return storageMap.size(); } // public void printStoragedKeys() { diff --git a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/VersioningKVData.java b/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/VersioningKVData.java new file mode 100644 index 00000000..684c75fe --- /dev/null +++ b/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/VersioningKVData.java @@ -0,0 +1,35 @@ +package com.jd.blockchain.storage.service.utils; + +import com.jd.blockchain.storage.service.VersioningKVEntry; +import com.jd.blockchain.utils.Bytes; + +public class VersioningKVData implements VersioningKVEntry { + + private Bytes key; + + private long version; + + private byte[] value; + + public VersioningKVData(Bytes key, long version, byte[] value) { + this.key = key; + this.version = version; + this.value = value; + } + + @Override + public Bytes getKey() { + return key; + } + + @Override + public long getVersion() { + return version; + } + + @Override + public byte[] getValue() { + return value; + } + + } \ No newline at end of file diff --git a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/VersioningKVStorageMap.java b/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/VersioningKVStorageMap.java index 2569007f..3c4855e3 100644 --- a/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/VersioningKVStorageMap.java +++ b/source/storage/storage-service/src/main/java/com/jd/blockchain/storage/service/utils/VersioningKVStorageMap.java @@ -215,38 +215,6 @@ public class VersioningKVStorageMap implements VersioningKVStorage, BytesMap callback0 = node0.startInit(0, privkey0, initSetting, testDb0, consolePrompter); - PrivKey privkey1 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD); + PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD); DBConnectionConfig testDb1 = new DBConnectionConfig(); testDb1.setConnectionUri(memoryConnString[1]); AsyncCallback callback1 = node1.startInit(1, privkey1, initSetting, testDb1, consolePrompter); - PrivKey privkey2 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD); + PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD); DBConnectionConfig testDb2 = new DBConnectionConfig(); testDb2.setConnectionUri(memoryConnString[2]); AsyncCallback callback2 = node2.startInit(2, privkey2, initSetting, testDb2, consolePrompter); - PrivKey privkey3 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD); + PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD); DBConnectionConfig testDb03 = new DBConnectionConfig(); testDb03.setConnectionUri(memoryConnString[3]); AsyncCallback callback3 = node3.startInit(3, privkey3, initSetting, testDb03, consolePrompter); @@ -113,21 +113,21 @@ public class LedgerInitializeTest { LedgerBlock genesisBlock = ledger0.getLatestBlock(); - UserAccountSet userset0 = ledger0.getUserAccountSet(genesisBlock); + UserAccountQuery userset0 = ledger0.getUserAccountSet(genesisBlock); - PubKey pubKey0 = KeyGenCommand.decodePubKey(PUB_KEYS[0]); + PubKey pubKey0 = KeyGenUtils.decodePubKey(PUB_KEYS[0]); Bytes address0 = AddressEncoding.generateAddress(pubKey0); UserAccount user0_0 = userset0.getUser(address0); - PubKey pubKey1 = KeyGenCommand.decodePubKey(PUB_KEYS[1]); + PubKey pubKey1 = KeyGenUtils.decodePubKey(PUB_KEYS[1]); Bytes address1 = AddressEncoding.generateAddress(pubKey1); UserAccount user1_0 = userset0.getUser(address1); - PubKey pubKey2 = KeyGenCommand.decodePubKey(PUB_KEYS[2]); + PubKey pubKey2 = KeyGenUtils.decodePubKey(PUB_KEYS[2]); Bytes address2 = AddressEncoding.generateAddress(pubKey2); UserAccount user2_0 = userset0.getUser(address2); - PubKey pubKey3 = KeyGenCommand.decodePubKey(PUB_KEYS[3]); + PubKey pubKey3 = KeyGenUtils.decodePubKey(PUB_KEYS[3]); Bytes address3 = AddressEncoding.generateAddress(pubKey3); UserAccount user3_0 = userset0.getUser(address3); } @@ -182,8 +182,8 @@ public class LedgerInitializeTest { public NodeContext(NetworkAddress address, Map serviceRegisterMap) { this.initCsServiceFactory = new MultiThreadInterInvokerFactory(serviceRegisterMap); - LedgerInitializeWebController initController = new LedgerInitializeWebController(ledgerManager, - memoryDBConnFactory, initCsServiceFactory); + LedgerInitializeWebController initController = new LedgerInitializeWebController(memoryDBConnFactory, + initCsServiceFactory); serviceRegisterMap.put(address, initController); this.initProcess = initController; } @@ -203,19 +203,18 @@ public class LedgerInitializeTest { return invoker.start(); } - public AsyncCallback startInit(int currentId, PrivKey privKey, LedgerInitProperties setting, + public AsyncCallback startInit(int currentId, PrivKey privKey, LedgerInitProperties initProps, DBConnectionConfig dbConnConfig, Prompter prompter, boolean autoVerifyHash) { - CryptoConfig cryptoSetting = new CryptoConfig(); - cryptoSetting.setAutoVerifyHash(autoVerifyHash); - cryptoSetting.setHashAlgorithm(Crypto.getAlgorithm("SHA256")); + initProps.getCryptoProperties().setVerifyHash(autoVerifyHash); + initProps.getCryptoProperties().setHashAlgorithm("SHA256"); - partiKey = new AsymmetricKeypair(setting.getConsensusParticipant(0).getPubKey(), privKey); + partiKey = new AsymmetricKeypair(initProps.getConsensusParticipant(0).getPubKey(), privKey); ThreadInvoker invoker = new ThreadInvoker() { @Override protected HashDigest invoke() throws Exception { - return initProcess.initialize(currentId, privKey, setting, dbConnConfig, prompter, cryptoSetting); + return initProcess.initialize(currentId, privKey, initProps, dbConnConfig, prompter); } }; @@ -251,10 +250,10 @@ public class LedgerInitializeTest { } @Override - public LedgerInitPermission requestPermission(int requesterId, SignatureDigest signature) { - ThreadInvoker invoker = new ThreadInvoker() { + public LedgerInitProposal requestPermission(int requesterId, SignatureDigest signature) { + ThreadInvoker invoker = new ThreadInvoker() { @Override - protected LedgerInitPermission invoke() { + protected LedgerInitProposal invoke() { return initCsService.requestPermission(requesterId, signature); } }; diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerInitializeWebTest.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerInitializeWebTest.java index 569472d9..f5db2162 100644 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerInitializeWebTest.java +++ b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerInitializeWebTest.java @@ -16,21 +16,23 @@ import com.jd.blockchain.consensus.ConsensusSettings; import com.jd.blockchain.crypto.AddressEncoding; import com.jd.blockchain.crypto.Crypto; import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.SignatureDigest; import com.jd.blockchain.crypto.SignatureFunction; import com.jd.blockchain.ledger.LedgerBlock; import com.jd.blockchain.ledger.LedgerInitOperation; +import com.jd.blockchain.ledger.LedgerInitProperties; import com.jd.blockchain.ledger.Operation; import com.jd.blockchain.ledger.TransactionContent; import com.jd.blockchain.ledger.UserRegisterOperation; import com.jd.blockchain.ledger.core.LedgerInitDecision; -import com.jd.blockchain.ledger.core.LedgerInitPermission; +import com.jd.blockchain.ledger.core.LedgerInitProposal; +import com.jd.blockchain.ledger.core.LedgerManager; import com.jd.blockchain.ledger.core.LedgerRepository; import com.jd.blockchain.ledger.core.UserAccount; -import com.jd.blockchain.ledger.core.UserAccountSet; -import com.jd.blockchain.ledger.core.impl.LedgerManager; +import com.jd.blockchain.ledger.core.UserAccountQuery; import com.jd.blockchain.storage.service.DbConnection; import com.jd.blockchain.storage.service.impl.composite.CompositeConnectionFactory; //import com.jd.blockchain.storage.service.utils.MemoryBasedDb; @@ -38,12 +40,11 @@ import com.jd.blockchain.tools.initializer.DBConnectionConfig; import com.jd.blockchain.tools.initializer.LedgerBindingConfig; import com.jd.blockchain.tools.initializer.LedgerInitCommand; import com.jd.blockchain.tools.initializer.LedgerInitProcess; -import com.jd.blockchain.tools.initializer.LedgerInitProperties; import com.jd.blockchain.tools.initializer.Prompter; import com.jd.blockchain.tools.initializer.web.HttpInitConsensServiceFactory; +import com.jd.blockchain.tools.initializer.web.LedgerInitConfiguration; import com.jd.blockchain.tools.initializer.web.LedgerInitConsensusService; import com.jd.blockchain.tools.initializer.web.LedgerInitializeWebController; -import com.jd.blockchain.tools.keygen.KeyGenCommand; import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.concurrent.ThreadInvoker; import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; @@ -101,21 +102,23 @@ public class LedgerInitializeWebTest { node2.setPrompter(prompter); node3.setPrompter(prompter); - PrivKey privkey0 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[0], PASSWORD); - PrivKey privkey1 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD); - PrivKey privkey2 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD); - PrivKey privkey3 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD); + PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[0], PASSWORD); + PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD); + PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD); + PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD); - PubKey pubKey0 = KeyGenCommand.decodePubKey(PUB_KEYS[0]); - PubKey pubKey1 = KeyGenCommand.decodePubKey(PUB_KEYS[1]); - PubKey pubKey2 = KeyGenCommand.decodePubKey(PUB_KEYS[2]); - PubKey pubKey3 = KeyGenCommand.decodePubKey(PUB_KEYS[3]); + PubKey pubKey0 = KeyGenUtils.decodePubKey(PUB_KEYS[0]); + PubKey pubKey1 = KeyGenUtils.decodePubKey(PUB_KEYS[1]); + PubKey pubKey2 = KeyGenUtils.decodePubKey(PUB_KEYS[2]); + PubKey pubKey3 = KeyGenUtils.decodePubKey(PUB_KEYS[3]); // 测试生成“账本初始化许可”; - LedgerInitPermission permission0 = testPreparePermisssion(node0, privkey0, initSetting, csProps); - LedgerInitPermission permission1 = testPreparePermisssion(node1, privkey1, initSetting, csProps); - LedgerInitPermission permission2 = testPreparePermisssion(node2, privkey2, initSetting, csProps); - LedgerInitPermission permission3 = testPreparePermisssion(node3, privkey3, initSetting, csProps); + LedgerInitConfiguration initConfig = LedgerInitConfiguration.create(initSetting); + initConfig.setConsensusSettings(csProvider, csProps); + LedgerInitProposal permission0 = testPreparePermisssion(node0, privkey0, initConfig); + LedgerInitProposal permission1 = testPreparePermisssion(node1, privkey1, initConfig); + LedgerInitProposal permission2 = testPreparePermisssion(node2, privkey2, initConfig); + LedgerInitProposal permission3 = testPreparePermisssion(node3, privkey3, initConfig); TransactionContent initTxContent0 = node0.getInitTxContent(); TransactionContent initTxContent1 = node1.getInitTxContent(); @@ -205,9 +208,9 @@ public class LedgerInitializeWebTest { testRequestDecision(node3, node2, initCsService2); } - private LedgerInitPermission testPreparePermisssion(NodeWebContext node, PrivKey privKey, - LedgerInitProperties setting, ConsensusSettings csProps) { - LedgerInitPermission permission = node.preparePermision(privKey, setting, csProps); + private LedgerInitProposal testPreparePermisssion(NodeWebContext node, PrivKey privKey, + LedgerInitConfiguration setting) { + LedgerInitProposal permission = node.preparePermision(privKey, setting); return permission; } @@ -215,7 +218,7 @@ public class LedgerInitializeWebTest { private void testRequestPermission(NodeWebContext fromNode, PrivKey fromPrivkey, NodeWebContext targetNode, LedgerInitConsensusService targetNodeService) { SignatureDigest reqSignature = fromNode.createPermissionRequestSignature(fromNode.getId(), fromPrivkey); - LedgerInitPermission targetPermission = targetNodeService.requestPermission(fromNode.getId(), reqSignature); + LedgerInitProposal targetPermission = targetNodeService.requestPermission(fromNode.getId(), reqSignature); } private void testRequestDecision(NodeWebContext fromNode, NodeWebContext targetNode, @@ -259,10 +262,10 @@ public class LedgerInitializeWebTest { NetworkAddress initAddr3 = initSetting.getConsensusParticipant(3).getInitializerAddress(); NodeWebContext node3 = new NodeWebContext(3, initAddr3); - PrivKey privkey0 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[0], PASSWORD); - PrivKey privkey1 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD); - PrivKey privkey2 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD); - PrivKey privkey3 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD); + PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[0], PASSWORD); + PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD); + PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD); + PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD); CountDownLatch quitLatch = new CountDownLatch(4); @@ -298,21 +301,21 @@ public class LedgerInitializeWebTest { LedgerBlock genesisBlock = ledger0.getLatestBlock(); - UserAccountSet userset0 = ledger0.getUserAccountSet(genesisBlock); + UserAccountQuery userset0 = ledger0.getUserAccountSet(genesisBlock); - PubKey pubKey0 = KeyGenCommand.decodePubKey(PUB_KEYS[0]); + PubKey pubKey0 = KeyGenUtils.decodePubKey(PUB_KEYS[0]); Bytes address0 = AddressEncoding.generateAddress(pubKey0); UserAccount user0_0 = userset0.getUser(address0); - PubKey pubKey1 = KeyGenCommand.decodePubKey(PUB_KEYS[1]); + PubKey pubKey1 = KeyGenUtils.decodePubKey(PUB_KEYS[1]); Bytes address1 = AddressEncoding.generateAddress(pubKey1); UserAccount user1_0 = userset0.getUser(address1); - PubKey pubKey2 = KeyGenCommand.decodePubKey(PUB_KEYS[2]); + PubKey pubKey2 = KeyGenUtils.decodePubKey(PUB_KEYS[2]); Bytes address2 = AddressEncoding.generateAddress(pubKey2); UserAccount user2_0 = userset0.getUser(address2); - PubKey pubKey3 = KeyGenCommand.decodePubKey(PUB_KEYS[3]); + PubKey pubKey3 = KeyGenUtils.decodePubKey(PUB_KEYS[3]); Bytes address3 = AddressEncoding.generateAddress(pubKey3); UserAccount user3_0 = userset0.getUser(address3); } @@ -374,7 +377,7 @@ public class LedgerInitializeWebTest { return controller.getInitTxContent(); } - public LedgerInitPermission getLocalPermission() { + public LedgerInitProposal getLocalPermission() { return controller.getLocalPermission(); } @@ -457,9 +460,8 @@ public class LedgerInitializeWebTest { return invoker.start(); } - public LedgerInitPermission preparePermision(PrivKey privKey, LedgerInitProperties setting, - ConsensusSettings csProps) { - return controller.prepareLocalPermission(id, privKey, setting, csProps); + public LedgerInitProposal preparePermision(PrivKey privKey, LedgerInitConfiguration initConfig) { + return controller.prepareLocalPermission(id, privKey, initConfig); } public boolean consensusPermission(PrivKey privKey) { diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerPerformanceTest.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerPerformanceTest.java index baae348a..b0adc187 100644 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerPerformanceTest.java +++ b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/LedgerPerformanceTest.java @@ -7,24 +7,36 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.DoubleStream; -import com.jd.blockchain.crypto.*; import com.jd.blockchain.ledger.*; -import com.jd.blockchain.ledger.core.CryptoConfig; import org.springframework.core.io.ClassPathResource; import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.consensus.ConsensusProvider; import com.jd.blockchain.consensus.ConsensusProviders; import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.ledger.core.LedgerDataSet; +import com.jd.blockchain.crypto.AsymmetricKeypair; +import com.jd.blockchain.crypto.Crypto; +import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.KeyGenUtils; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.ledger.LedgerInitProperties; +import com.jd.blockchain.ledger.LedgerPermission; +import com.jd.blockchain.ledger.LedgerSecurityException; +import com.jd.blockchain.ledger.TransactionPermission; +import com.jd.blockchain.ledger.core.DefaultOperationHandleRegisteration; +import com.jd.blockchain.ledger.core.LedgerDataQuery; import com.jd.blockchain.ledger.core.LedgerEditor; +import com.jd.blockchain.ledger.core.LedgerManager; import com.jd.blockchain.ledger.core.LedgerRepository; -import com.jd.blockchain.ledger.core.impl.DefaultOperationHandleRegisteration; -import com.jd.blockchain.ledger.core.impl.LedgerManager; -import com.jd.blockchain.ledger.core.impl.TransactionBatchProcessor; +import com.jd.blockchain.ledger.core.LedgerSecurityManager; +import com.jd.blockchain.ledger.core.MultiIDsPolicy; +import com.jd.blockchain.ledger.core.SecurityPolicy; +import com.jd.blockchain.ledger.core.TransactionBatchProcessor; import com.jd.blockchain.service.TransactionBatchResultHandle; import com.jd.blockchain.storage.service.DbConnectionFactory; import com.jd.blockchain.storage.service.impl.redis.JedisConnection; @@ -33,12 +45,11 @@ import com.jd.blockchain.storage.service.impl.redis.RedisStorageService; import com.jd.blockchain.storage.service.impl.rocksdb.RocksDBConnectionFactory; import com.jd.blockchain.storage.service.utils.MemoryDBConnFactory; import com.jd.blockchain.tools.initializer.DBConnectionConfig; -import com.jd.blockchain.tools.initializer.LedgerInitProperties; import com.jd.blockchain.tools.initializer.Prompter; import com.jd.blockchain.tools.initializer.web.LedgerInitConsensusService; -import com.jd.blockchain.tools.keygen.KeyGenCommand; import com.jd.blockchain.transaction.TxBuilder; import com.jd.blockchain.utils.ArgumentSet; +import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.ConsoleUtils; import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; import com.jd.blockchain.utils.io.FileUtils; @@ -80,6 +91,8 @@ public class LedgerPerformanceTest { DataContractRegistry.register(ParticipantStateUpdateOperation.class); } + public static final LedgerSecurityManager DEFAULT_SECURITY_MANAGER = new FreedomLedgerSecurityManager(); + public static void test(String[] args) { NodeContext[] nodes = null; try { @@ -269,10 +282,10 @@ public class LedgerPerformanceTest { ConsoleUtils.info("\r\n\r\n================= 准备测试交易 [执行合约] ================="); LedgerBlock latestBlock = ledger.getLatestBlock(); - LedgerDataSet previousDataSet = ledger.getDataSet(latestBlock); + LedgerDataQuery previousDataSet = ledger.getDataSet(latestBlock); LedgerEditor newEditor = ledger.createNextBlock(); - TransactionBatchProcessor txProc = new TransactionBatchProcessor(newEditor, previousDataSet, opHandler, - ledgerManager); + TransactionBatchProcessor txProc = new TransactionBatchProcessor(DEFAULT_SECURITY_MANAGER, newEditor, + previousDataSet, opHandler, ledgerManager); // 准备请求 int totalCount = batchSize * batchCount; @@ -302,15 +315,15 @@ public class LedgerPerformanceTest { long batchStartTs = System.currentTimeMillis(); for (int i = 0; i < batchCount; i++) { LedgerBlock latestBlock = ledger.getLatestBlock(); - LedgerDataSet previousDataSet = ledger.getDataSet(latestBlock); + LedgerDataQuery previousDataSet = ledger.getDataSet(latestBlock); if (statistic) { ConsoleUtils.info("------ 开始执行交易, 即将生成区块[高度:%s] ------", (latestBlock.getHeight() + 1)); } long startTs = System.currentTimeMillis(); LedgerEditor newEditor = ledger.createNextBlock(); - TransactionBatchProcessor txProc = new TransactionBatchProcessor(newEditor, previousDataSet, opHandler, - ledgerManager); + TransactionBatchProcessor txProc = new TransactionBatchProcessor(DEFAULT_SECURITY_MANAGER, newEditor, + previousDataSet, opHandler, ledgerManager); testTxExec(txList, i * batchSize, batchSize, txProc); @@ -486,9 +499,8 @@ public class LedgerPerformanceTest { LedgerInitProperties initSetting = loadInitSetting(); Properties props = loadConsensusSetting(config); ConsensusProvider csProvider = getConsensusProvider(provider); - ConsensusSettings csProps = csProvider.getSettingsFactory() - .getConsensusSettingsBuilder() - .createSettings(props, Utils.loadParticipantNodes()); + ConsensusSettings csProps = csProvider.getSettingsFactory().getConsensusSettingsBuilder().createSettings(props, + Utils.loadParticipantNodes()); DBSetting dbsetting0; DBSetting dbsetting1; @@ -538,19 +550,19 @@ public class LedgerPerformanceTest { NodeContext node3 = new NodeContext(initSetting.getConsensusParticipant(3).getInitializerAddress(), serviceRegisterMap, dbsetting3.connectionFactory); - PrivKey privkey0 = KeyGenCommand.decodePrivKeyWithRawPassword(Utils.PRIV_KEYS[0], Utils.PASSWORD); + PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(Utils.PRIV_KEYS[0], Utils.PASSWORD); AsyncCallback callback0 = node0.startInit(0, privkey0, initSetting, csProps, csProvider, dbsetting0.connectionConfig, consolePrompter, !optimized, hashAlg); - PrivKey privkey1 = KeyGenCommand.decodePrivKeyWithRawPassword(Utils.PRIV_KEYS[1], Utils.PASSWORD); + PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(Utils.PRIV_KEYS[1], Utils.PASSWORD); AsyncCallback callback1 = node1.startInit(1, privkey1, initSetting, csProps, csProvider, dbsetting1.connectionConfig, consolePrompter, !optimized, hashAlg); - PrivKey privkey2 = KeyGenCommand.decodePrivKeyWithRawPassword(Utils.PRIV_KEYS[2], Utils.PASSWORD); + PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(Utils.PRIV_KEYS[2], Utils.PASSWORD); AsyncCallback callback2 = node2.startInit(2, privkey2, initSetting, csProps, csProvider, dbsetting2.connectionConfig, consolePrompter, !optimized, hashAlg); - PrivKey privkey3 = KeyGenCommand.decodePrivKeyWithRawPassword(Utils.PRIV_KEYS[3], Utils.PASSWORD); + PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(Utils.PRIV_KEYS[3], Utils.PASSWORD); AsyncCallback callback3 = node3.startInit(3, privkey3, initSetting, csProps, csProvider, dbsetting3.connectionConfig, consolePrompter, !optimized, hashAlg); @@ -622,4 +634,94 @@ public class LedgerPerformanceTest { } } + + private static class FreedomLedgerSecurityManager implements LedgerSecurityManager { + + public static final FreedomLedgerSecurityManager INSTANCE = new FreedomLedgerSecurityManager(); + + @Override + public SecurityPolicy createSecurityPolicy(Set endpoints, Set nodes) { + return new FreedomSecurityPolicy(endpoints, nodes); + } + + } + + private static class FreedomSecurityPolicy implements SecurityPolicy { + + private Set endpoints; + private Set nodes; + + public FreedomSecurityPolicy(Set endpoints, Set nodes) { + this.endpoints = endpoints; + this.nodes = nodes; + } + + @Override + public Set getEndpoints() { + return endpoints; + } + + @Override + public Set getNodes() { + return nodes; + } + + @Override + public boolean isEndpointEnable(LedgerPermission permission, MultiIDsPolicy midPolicy) { + return true; + } + + @Override + public boolean isEndpointEnable(TransactionPermission permission, MultiIDsPolicy midPolicy) { + return true; + } + + @Override + public boolean isNodeEnable(LedgerPermission permission, MultiIDsPolicy midPolicy) { + return true; + } + + @Override + public boolean isNodeEnable(TransactionPermission permission, MultiIDsPolicy midPolicy) { + return true; + } + + @Override + public void checkEndpointPermission(LedgerPermission permission, MultiIDsPolicy midPolicy) + throws LedgerSecurityException { + } + + @Override + public void checkEndpointPermission(TransactionPermission permission, MultiIDsPolicy midPolicy) + throws LedgerSecurityException { + } + + @Override + public void checkNodePermission(LedgerPermission permission, MultiIDsPolicy midPolicy) throws LedgerSecurityException { + } + + @Override + public void checkNodePermission(TransactionPermission permission, MultiIDsPolicy midPolicy) + throws LedgerSecurityException { + } + + @Override + public boolean isEndpointValid(MultiIDsPolicy midPolicy) { + return true; + } + + @Override + public boolean isNodeValid(MultiIDsPolicy midPolicy) { + return true; + } + + @Override + public void checkEndpointValidity(MultiIDsPolicy midPolicy) throws LedgerSecurityException { + } + + @Override + public void checkNodeValidity(MultiIDsPolicy midPolicy) throws LedgerSecurityException { + } + + } } diff --git a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/Utils.java b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/Utils.java index 67f4781a..663cef6d 100644 --- a/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/Utils.java +++ b/source/test/test-integration/src/main/java/test/com/jd/blockchain/intgr/perf/Utils.java @@ -6,30 +6,41 @@ import java.util.Map; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; -import com.jd.blockchain.crypto.*; -import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; -import com.jd.blockchain.crypto.service.sm.SMCryptoService; -import com.jd.blockchain.ledger.ParticipantNode; import com.jd.blockchain.ledger.ParticipantNodeState; -import com.jd.blockchain.tools.keygen.KeyGenCommand; import org.springframework.core.io.ClassPathResource; import com.jd.blockchain.consensus.ConsensusProvider; import com.jd.blockchain.consensus.ConsensusSettings; +import com.jd.blockchain.crypto.AddressEncoding; +import com.jd.blockchain.crypto.AsymmetricKeypair; +import com.jd.blockchain.crypto.Crypto; +import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.CryptoProvider; +import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.KeyGenUtils; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; +import com.jd.blockchain.crypto.SignatureDigest; +import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; +import com.jd.blockchain.crypto.service.sm.SMCryptoService; import com.jd.blockchain.ledger.CryptoSetting; +import com.jd.blockchain.ledger.LedgerInitProperties; +import com.jd.blockchain.ledger.ParticipantNode; import com.jd.blockchain.ledger.core.CryptoConfig; +import com.jd.blockchain.ledger.core.LedgerConfiguration; import com.jd.blockchain.ledger.core.LedgerInitDecision; -import com.jd.blockchain.ledger.core.LedgerInitPermission; +import com.jd.blockchain.ledger.core.LedgerInitProposal; +import com.jd.blockchain.ledger.core.LedgerManager; import com.jd.blockchain.ledger.core.LedgerRepository; -import com.jd.blockchain.ledger.core.impl.LedgerManager; import com.jd.blockchain.storage.service.DbConnectionFactory; import com.jd.blockchain.tools.initializer.DBConnectionConfig; import com.jd.blockchain.tools.initializer.LedgerInitProcess; -import com.jd.blockchain.tools.initializer.LedgerInitProperties; import com.jd.blockchain.tools.initializer.Prompter; import com.jd.blockchain.tools.initializer.web.InitConsensusServiceFactory; +import com.jd.blockchain.tools.initializer.web.LedgerInitConfiguration; import com.jd.blockchain.tools.initializer.web.LedgerInitConsensusService; import com.jd.blockchain.tools.initializer.web.LedgerInitializeWebController; +import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.concurrent.ThreadInvoker; import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; import com.jd.blockchain.utils.io.FileUtils; @@ -39,8 +50,7 @@ public class Utils { public static final String PASSWORD = "abc"; - public static final String[] PUB_KEYS = { - "3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9", + public static final String[] PUB_KEYS = { "3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9", "3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX", "3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x", "3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk" }; @@ -78,7 +88,7 @@ public class Utils { public static ParticipantNode[] loadParticipantNodes() { ParticipantNode[] participantNodes = new ParticipantNode[PUB_KEYS.length]; for (int i = 0; i < PUB_KEYS.length; i++) { - participantNodes[i] = new PartNode(i, KeyGenCommand.decodePubKey(PUB_KEYS[i]), ParticipantNodeState.CONSENSUSED); + participantNodes[i] = new PartNode(i, KeyGenCommand.decodePubKey(PUB_KEYS[i])); } return participantNodes; } @@ -111,8 +121,8 @@ public class Utils { DbConnectionFactory dbConnFactory) { this.dbConnFactory = dbConnFactory; this.initCsServiceFactory = new MultiThreadInterInvokerFactory(serviceRegisterMap); - LedgerInitializeWebController initController = new LedgerInitializeWebController(ledgerManager, - dbConnFactory, initCsServiceFactory); + LedgerInitializeWebController initController = new LedgerInitializeWebController(dbConnFactory, + initCsServiceFactory); serviceRegisterMap.put(address, initController); this.initProcess = initController; } @@ -162,12 +172,16 @@ public class Utils { ConsensusSettings csProps, ConsensusProvider consensusProvider, DBConnectionConfig dbConnConfig, Prompter prompter, CryptoSetting cryptoSetting) { + LedgerInitConfiguration ledgerInitConfig = LedgerInitConfiguration.create(setting); + ledgerInitConfig.getLedgerSettings().setCryptoSetting(cryptoSetting); + partiKey = new AsymmetricKeypair(setting.getConsensusParticipant(0).getPubKey(), privKey); ThreadInvoker invoker = new ThreadInvoker() { @Override protected HashDigest invoke() throws Exception { - return initProcess.initialize(currentId, privKey, setting, dbConnConfig, prompter, cryptoSetting); + + return initProcess.initialize(currentId, privKey, setting, dbConnConfig, prompter); } }; @@ -203,10 +217,10 @@ public class Utils { } @Override - public LedgerInitPermission requestPermission(int requesterId, SignatureDigest signature) { - ThreadInvoker invoker = new ThreadInvoker() { + public LedgerInitProposal requestPermission(int requesterId, SignatureDigest signature) { + ThreadInvoker invoker = new ThreadInvoker() { @Override - protected LedgerInitPermission invoke() { + protected LedgerInitProposal invoke() { return initCsService.requestPermission(requesterId, signature); } }; @@ -230,7 +244,7 @@ public class Utils { private int id; - private String address; + private Bytes address; private String name; @@ -246,7 +260,7 @@ public class Utils { this.id = id; this.name = name; this.pubKey = pubKey; - this.address = pubKey.toBase58(); + this.address = AddressEncoding.generateAddress(pubKey); this.participantNodeState = participantNodeState; } @@ -256,7 +270,7 @@ public class Utils { } @Override - public String getAddress() { + public Bytes getAddress() { return address; } diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationBase.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationBase.java index d5d8f3af..b4550ee5 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationBase.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationBase.java @@ -35,8 +35,8 @@ import com.jd.blockchain.contract.ReadContract; import com.jd.blockchain.crypto.AddressEncoding; import com.jd.blockchain.crypto.AsymmetricKeypair; import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.ledger.core.LedgerManager; import com.jd.blockchain.ledger.core.LedgerRepository; -import com.jd.blockchain.ledger.core.impl.LedgerManager; import com.jd.blockchain.sdk.BlockchainService; import com.jd.blockchain.storage.service.DbConnection; import com.jd.blockchain.storage.service.DbConnectionFactory; diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationBaseTest.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationBaseTest.java index 0fb2d461..46df4b5a 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationBaseTest.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationBaseTest.java @@ -14,15 +14,15 @@ import com.jd.blockchain.consensus.ConsensusProvider; import com.jd.blockchain.consensus.ConsensusSettings; import com.jd.blockchain.crypto.AsymmetricKeypair; import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.gateway.GatewayConfigProperties.KeyPairConfig; import com.jd.blockchain.ledger.LedgerBlock; +import com.jd.blockchain.ledger.LedgerInitProperties; import com.jd.blockchain.ledger.core.LedgerRepository; import com.jd.blockchain.tools.initializer.DBConnectionConfig; import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.tools.initializer.LedgerInitProperties; import com.jd.blockchain.tools.initializer.Prompter; -import com.jd.blockchain.tools.keygen.KeyGenCommand; import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; import com.jd.blockchain.utils.net.NetworkAddress; @@ -68,7 +68,7 @@ public class IntegrationBaseTest { peerStarting2.waitReturn(); peerStarting3.waitReturn(); - String encodedBase58Pwd = KeyGenCommand.encodePasswordAsBase58(LedgerInitializeWeb4SingleStepsTest.PASSWORD); + String encodedBase58Pwd = KeyGenUtils.encodePasswordAsBase58(LedgerInitializeWeb4SingleStepsTest.PASSWORD); KeyPairConfig gwkey0 = new KeyPairConfig(); gwkey0.setPubKeyValue(LedgerInitializeWeb4SingleStepsTest.PUB_KEYS[0]); @@ -140,16 +140,16 @@ public class IntegrationBaseTest { NetworkAddress initAddr3 = initSetting.getConsensusParticipant(3).getInitializerAddress(); NodeWebContext nodeCtx3 = new NodeWebContext(3, initAddr3); - PrivKey privkey0 = KeyGenCommand.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[0], + PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[0], LedgerInitializeWeb4SingleStepsTest.PASSWORD); - PrivKey privkey1 = KeyGenCommand.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[1], + PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[1], LedgerInitializeWeb4SingleStepsTest.PASSWORD); - PrivKey privkey2 = KeyGenCommand.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[2], + PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[2], LedgerInitializeWeb4SingleStepsTest.PASSWORD); - PrivKey privkey3 = KeyGenCommand.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[3], + PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[3], LedgerInitializeWeb4SingleStepsTest.PASSWORD); - String encodedPassword = KeyGenCommand.encodePasswordAsBase58(LedgerInitializeWeb4SingleStepsTest.PASSWORD); + String encodedPassword = KeyGenUtils.encodePasswordAsBase58(LedgerInitializeWeb4SingleStepsTest.PASSWORD); CountDownLatch quitLatch = new CountDownLatch(4); diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest2.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest2.java index 3e5a1e85..cf2774b1 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest2.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest2.java @@ -18,12 +18,14 @@ import com.jd.blockchain.consensus.ConsensusProvider; import com.jd.blockchain.consensus.ConsensusSettings; import com.jd.blockchain.crypto.AsymmetricKeypair; import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.gateway.GatewayConfigProperties.KeyPairConfig; import com.jd.blockchain.ledger.BlockchainKeyGenerator; import com.jd.blockchain.ledger.BlockchainKeypair; import com.jd.blockchain.ledger.LedgerBlock; import com.jd.blockchain.ledger.LedgerInfo; +import com.jd.blockchain.ledger.LedgerInitProperties; import com.jd.blockchain.ledger.PreparedTransaction; import com.jd.blockchain.ledger.TransactionResponse; import com.jd.blockchain.ledger.TransactionTemplate; @@ -32,9 +34,7 @@ import com.jd.blockchain.sdk.BlockchainService; import com.jd.blockchain.sdk.client.GatewayServiceFactory; import com.jd.blockchain.tools.initializer.DBConnectionConfig; import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.tools.initializer.LedgerInitProperties; import com.jd.blockchain.tools.initializer.Prompter; -import com.jd.blockchain.tools.keygen.KeyGenCommand; import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; import com.jd.blockchain.utils.net.NetworkAddress; @@ -85,7 +85,7 @@ public class IntegrationTest2 { peerStarting2.waitReturn(); peerStarting3.waitReturn(); - String encodedBase58Pwd = KeyGenCommand.encodePasswordAsBase58(LedgerInitializeWeb4SingleStepsTest.PASSWORD); + String encodedBase58Pwd = KeyGenUtils.encodePasswordAsBase58(LedgerInitializeWeb4SingleStepsTest.PASSWORD); KeyPairConfig gwkey0 = new KeyPairConfig(); gwkey0.setPubKeyValue(LedgerInitializeWeb4SingleStepsTest.PUB_KEYS[0]); @@ -178,16 +178,16 @@ public class IntegrationTest2 { NetworkAddress initAddr3 = initSetting.getConsensusParticipant(3).getInitializerAddress(); NodeWebContext nodeCtx3 = new NodeWebContext(3, initAddr3); - PrivKey privkey0 = KeyGenCommand.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[0], + PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[0], LedgerInitializeWeb4SingleStepsTest.PASSWORD); - PrivKey privkey1 = KeyGenCommand.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[1], + PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[1], LedgerInitializeWeb4SingleStepsTest.PASSWORD); - PrivKey privkey2 = KeyGenCommand.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[2], + PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[2], LedgerInitializeWeb4SingleStepsTest.PASSWORD); - PrivKey privkey3 = KeyGenCommand.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[3], + PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[3], LedgerInitializeWeb4SingleStepsTest.PASSWORD); - String encodedPassword = KeyGenCommand.encodePasswordAsBase58(LedgerInitializeWeb4SingleStepsTest.PASSWORD); + String encodedPassword = KeyGenUtils.encodePasswordAsBase58(LedgerInitializeWeb4SingleStepsTest.PASSWORD); CountDownLatch quitLatch = new CountDownLatch(4); diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4Bftsmart.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4Bftsmart.java index a7157d39..ec352082 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4Bftsmart.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4Bftsmart.java @@ -4,6 +4,7 @@ import com.jd.blockchain.consensus.ConsensusProviders; import com.jd.blockchain.consensus.bftsmart.BftsmartConsensusSettings; import com.jd.blockchain.crypto.AsymmetricKeypair; import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.gateway.GatewayConfigProperties; @@ -16,7 +17,6 @@ import com.jd.blockchain.sdk.BlockchainService; import com.jd.blockchain.sdk.client.GatewayServiceFactory; import com.jd.blockchain.storage.service.DbConnectionFactory; import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.tools.keygen.KeyGenCommand; import com.jd.blockchain.utils.concurrent.ThreadInvoker; import org.junit.Test; @@ -76,7 +76,7 @@ public class IntegrationTest4Bftsmart { DbConnectionFactory dbConnectionFactory2 = peerNodes[2].getDBConnectionFactory(); DbConnectionFactory dbConnectionFactory3 = peerNodes[3].getDBConnectionFactory(); - String encodedBase58Pwd = KeyGenCommand.encodePasswordAsBase58(LedgerInitializeTest.PASSWORD); + String encodedBase58Pwd = KeyGenUtils.encodePasswordAsBase58(LedgerInitializeTest.PASSWORD); GatewayConfigProperties.KeyPairConfig gwkey0 = new GatewayConfigProperties.KeyPairConfig(); gwkey0.setPubKeyValue(IntegrationBase.PUB_KEYS[0]); @@ -108,9 +108,9 @@ public class IntegrationTest4Bftsmart { GatewayServiceFactory gwsrvFact = GatewayServiceFactory.connect(gateway.getServiceAddress()); - PrivKey privkey0 = KeyGenCommand.decodePrivKeyWithRawPassword(IntegrationBase.PRIV_KEYS[0], IntegrationBase.PASSWORD); + PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(IntegrationBase.PRIV_KEYS[0], IntegrationBase.PASSWORD); - PubKey pubKey0 = KeyGenCommand.decodePubKey(IntegrationBase.PUB_KEYS[0]); + PubKey pubKey0 = KeyGenUtils.decodePubKey(IntegrationBase.PUB_KEYS[0]); AsymmetricKeypair adminKey = new AsymmetricKeypair(pubKey0, privkey0); diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4Contract.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4Contract.java index b2067f62..dc2c3ea1 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4Contract.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4Contract.java @@ -2,6 +2,7 @@ package test.com.jd.blockchain.intgr; import com.jd.blockchain.crypto.AsymmetricKeypair; import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.gateway.GatewayConfigProperties; @@ -11,7 +12,6 @@ import com.jd.blockchain.sdk.BlockchainService; import com.jd.blockchain.sdk.client.GatewayServiceFactory; import com.jd.blockchain.storage.service.DbConnectionFactory; import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.tools.keygen.KeyGenCommand; import com.jd.blockchain.utils.concurrent.ThreadInvoker; import org.junit.Test; @@ -46,7 +46,7 @@ public class IntegrationTest4Contract { DbConnectionFactory dbConnectionFactory2 = peerNodes[2].getDBConnectionFactory(); DbConnectionFactory dbConnectionFactory3 = peerNodes[3].getDBConnectionFactory(); - String encodedBase58Pwd = KeyGenCommand.encodePasswordAsBase58(LedgerInitializeTest.PASSWORD); + String encodedBase58Pwd = KeyGenUtils.encodePasswordAsBase58(LedgerInitializeTest.PASSWORD); GatewayConfigProperties.KeyPairConfig gwkey0 = new GatewayConfigProperties.KeyPairConfig(); gwkey0.setPubKeyValue(IntegrationBase.PUB_KEYS[0]); @@ -78,9 +78,9 @@ public class IntegrationTest4Contract { GatewayServiceFactory gwsrvFact = GatewayServiceFactory.connect(gateway.getServiceAddress()); - PrivKey privkey0 = KeyGenCommand.decodePrivKeyWithRawPassword(IntegrationBase.PRIV_KEYS[0], IntegrationBase.PASSWORD); + PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(IntegrationBase.PRIV_KEYS[0], IntegrationBase.PASSWORD); - PubKey pubKey0 = KeyGenCommand.decodePubKey(IntegrationBase.PUB_KEYS[0]); + PubKey pubKey0 = KeyGenUtils.decodePubKey(IntegrationBase.PUB_KEYS[0]); AsymmetricKeypair adminKey = new AsymmetricKeypair(pubKey0, privkey0); diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4MQ.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4MQ.java index 38619459..dedb4738 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4MQ.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTest4MQ.java @@ -5,6 +5,7 @@ import com.jd.blockchain.consensus.bftsmart.BftsmartConsensusSettings; import com.jd.blockchain.consensus.mq.settings.MsgQueueConsensusSettings; import com.jd.blockchain.crypto.AsymmetricKeypair; import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.gateway.GatewayConfigProperties.KeyPairConfig; @@ -14,7 +15,6 @@ import com.jd.blockchain.sdk.BlockchainService; import com.jd.blockchain.sdk.client.GatewayServiceFactory; import com.jd.blockchain.storage.service.DbConnectionFactory; import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.tools.keygen.KeyGenCommand; import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; import com.jd.blockchain.utils.io.FileUtils; @@ -81,7 +81,7 @@ public class IntegrationTest4MQ { DbConnectionFactory dbConnectionFactory2 = peerNodes[2].getDBConnectionFactory(); DbConnectionFactory dbConnectionFactory3 = peerNodes[3].getDBConnectionFactory(); - String encodedBase58Pwd = KeyGenCommand.encodePasswordAsBase58(LedgerInitializeTest.PASSWORD); + String encodedBase58Pwd = KeyGenUtils.encodePasswordAsBase58(LedgerInitializeTest.PASSWORD); KeyPairConfig gwkey0 = new KeyPairConfig(); gwkey0.setPubKeyValue(IntegrationBase.PUB_KEYS[0]); @@ -116,9 +116,9 @@ public class IntegrationTest4MQ { GatewayServiceFactory gwsrvFact = GatewayServiceFactory.connect(gateway.getServiceAddress()); - PrivKey privkey0 = KeyGenCommand.decodePrivKeyWithRawPassword(IntegrationBase.PRIV_KEYS[0], IntegrationBase.PASSWORD); + PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(IntegrationBase.PRIV_KEYS[0], IntegrationBase.PASSWORD); - PubKey pubKey0 = KeyGenCommand.decodePubKey(IntegrationBase.PUB_KEYS[0]); + PubKey pubKey0 = KeyGenUtils.decodePubKey(IntegrationBase.PUB_KEYS[0]); AsymmetricKeypair adminKey = new AsymmetricKeypair(pubKey0, privkey0); diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTestAll4Redis.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTestAll4Redis.java index 9dd3ea10..43df7bde 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTestAll4Redis.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTestAll4Redis.java @@ -2,20 +2,17 @@ package test.com.jd.blockchain.intgr; import com.jd.blockchain.crypto.*; import com.jd.blockchain.gateway.GatewayConfigProperties.KeyPairConfig; -import com.jd.blockchain.ledger.BytesValue; import com.jd.blockchain.ledger.*; import com.jd.blockchain.ledger.core.DataAccount; -import com.jd.blockchain.ledger.core.DataAccountSet; +import com.jd.blockchain.ledger.core.DataAccountQuery; import com.jd.blockchain.ledger.core.LedgerManage; +import com.jd.blockchain.ledger.core.LedgerManager; import com.jd.blockchain.ledger.core.LedgerRepository; -import com.jd.blockchain.ledger.core.impl.LedgerManager; import com.jd.blockchain.sdk.BlockchainService; import com.jd.blockchain.sdk.client.GatewayServiceFactory; import com.jd.blockchain.storage.service.DbConnection; import com.jd.blockchain.storage.service.DbConnectionFactory; import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.tools.initializer.LedgerInitProperties; -import com.jd.blockchain.tools.keygen.KeyGenCommand; import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.codec.HexUtils; import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; @@ -99,7 +96,7 @@ public class IntegrationTestAll4Redis { DbConnectionFactory dbConnectionFactory2 = peer2.getDBConnectionFactory(); DbConnectionFactory dbConnectionFactory3 = peer3.getDBConnectionFactory(); - String encodedBase58Pwd = KeyGenCommand.encodePasswordAsBase58(LedgerInitializeWeb4SingleStepsTest.PASSWORD); + String encodedBase58Pwd = KeyGenUtils.encodePasswordAsBase58(LedgerInitializeWeb4SingleStepsTest.PASSWORD); KeyPairConfig gwkey0 = new KeyPairConfig(); gwkey0.setPubKeyValue(PUB_KEYS[0]); @@ -118,15 +115,15 @@ public class IntegrationTestAll4Redis { dbConnectionFactory3 }); testConsistencyAmongNodes(ledgers); - PrivKey privkey0 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[0], PASSWORD); - PrivKey privkey1 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD); - PrivKey privkey2 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD); - PrivKey privkey3 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD); + PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[0], PASSWORD); + PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD); + PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD); + PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD); - PubKey pubKey0 = KeyGenCommand.decodePubKey(PUB_KEYS[0]); - PubKey pubKey1 = KeyGenCommand.decodePubKey(PUB_KEYS[1]); - PubKey pubKey2 = KeyGenCommand.decodePubKey(PUB_KEYS[2]); - PubKey pubKey3 = KeyGenCommand.decodePubKey(PUB_KEYS[3]); + PubKey pubKey0 = KeyGenUtils.decodePubKey(PUB_KEYS[0]); + PubKey pubKey1 = KeyGenUtils.decodePubKey(PUB_KEYS[1]); + PubKey pubKey2 = KeyGenUtils.decodePubKey(PUB_KEYS[2]); + PubKey pubKey3 = KeyGenUtils.decodePubKey(PUB_KEYS[3]); AsymmetricKeypair adminKey = new AsymmetricKeypair(pubKey0, privkey0); @@ -448,7 +445,7 @@ public class IntegrationTestAll4Redis { assertEquals(txResp.getBlockHeight(), backgroundLedgerBlock.getHeight()); // 验证合约中的赋值,外部可以获得; - DataAccountSet dataAccountSet = ledgerRepository.getDataAccountSet(backgroundLedgerBlock); + DataAccountQuery dataAccountSet = ledgerRepository.getDataAccountSet(backgroundLedgerBlock); AsymmetricKeypair key = Crypto.getSignatureFunction("ED25519").generateKeypair(); PubKey pubKey = key.getPubKey(); Bytes dataAddress = AddressEncoding.generateAddress(pubKey); diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTestDataAccount.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTestDataAccount.java index 41d8c800..e11891a9 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTestDataAccount.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/IntegrationTestDataAccount.java @@ -16,6 +16,7 @@ import com.jd.blockchain.consensus.ConsensusProvider; import com.jd.blockchain.consensus.ConsensusSettings; import com.jd.blockchain.crypto.AsymmetricKeypair; import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.gateway.GatewayConfigProperties.KeyPairConfig; @@ -24,20 +25,19 @@ import com.jd.blockchain.ledger.BlockchainKeypair; import com.jd.blockchain.ledger.DataAccountKVSetOperation; import com.jd.blockchain.ledger.KVDataEntry; import com.jd.blockchain.ledger.LedgerBlock; +import com.jd.blockchain.ledger.LedgerInitProperties; import com.jd.blockchain.ledger.PreparedTransaction; import com.jd.blockchain.ledger.TransactionResponse; import com.jd.blockchain.ledger.TransactionTemplate; -import com.jd.blockchain.ledger.core.DataAccountSet; +import com.jd.blockchain.ledger.core.DataAccountQuery; +import com.jd.blockchain.ledger.core.LedgerManager; import com.jd.blockchain.ledger.core.LedgerRepository; -import com.jd.blockchain.ledger.core.impl.LedgerManager; import com.jd.blockchain.sdk.BlockchainService; import com.jd.blockchain.sdk.client.GatewayServiceFactory; import com.jd.blockchain.storage.service.DbConnection; import com.jd.blockchain.tools.initializer.DBConnectionConfig; import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.tools.initializer.LedgerInitProperties; import com.jd.blockchain.tools.initializer.Prompter; -import com.jd.blockchain.tools.keygen.KeyGenCommand; import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; import com.jd.blockchain.utils.io.BytesUtils; @@ -99,7 +99,7 @@ public class IntegrationTestDataAccount { peerStarting2.waitReturn(); peerStarting3.waitReturn(); - String encodedBase58Pwd = KeyGenCommand.encodePasswordAsBase58(LedgerInitializeWeb4SingleStepsTest.PASSWORD); + String encodedBase58Pwd = KeyGenUtils.encodePasswordAsBase58(LedgerInitializeWeb4SingleStepsTest.PASSWORD); KeyPairConfig gwkey0 = new KeyPairConfig(); gwkey0.setPubKeyValue(LedgerInitializeWeb4SingleStepsTest.PUB_KEYS[0]); @@ -123,9 +123,9 @@ public class IntegrationTestDataAccount { testConsistencyAmongNodes(context); // temp test add - PrivKey privkey0 = KeyGenCommand.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[0], + PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[0], LedgerInitializeWeb4SingleStepsTest.PASSWORD); - PubKey pubKey0 = KeyGenCommand.decodePubKey(LedgerInitializeWeb4SingleStepsTest.PUB_KEYS[0]); + PubKey pubKey0 = KeyGenUtils.decodePubKey(LedgerInitializeWeb4SingleStepsTest.PUB_KEYS[0]); AsymmetricKeypair adminKey = new AsymmetricKeypair(pubKey0, privkey0); // regist data account @@ -187,7 +187,7 @@ public class IntegrationTestDataAccount { LedgerRepository ledgerRepository = ledgerManager.register(ledgerHashs[0], memoryBasedDb.getStorageService()); - DataAccountSet dataAccountSet = ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock()); + DataAccountQuery dataAccountSet = ledgerRepository.getDataAccountSet(ledgerRepository.retrieveLatestBlock()); TransactionTemplate txTpl = blockchainService.newTransaction(ledgerHashs[0]); @@ -275,16 +275,16 @@ public class IntegrationTestDataAccount { NetworkAddress initAddr3 = initSetting.getConsensusParticipant(3).getInitializerAddress(); NodeWebContext nodeCtx3 = new NodeWebContext(3, initAddr3); - PrivKey privkey0 = KeyGenCommand.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[0], + PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[0], LedgerInitializeWeb4SingleStepsTest.PASSWORD); - PrivKey privkey1 = KeyGenCommand.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[1], + PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[1], LedgerInitializeWeb4SingleStepsTest.PASSWORD); - PrivKey privkey2 = KeyGenCommand.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[2], + PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[2], LedgerInitializeWeb4SingleStepsTest.PASSWORD); - PrivKey privkey3 = KeyGenCommand.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[3], + PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeWeb4SingleStepsTest.PRIV_KEYS[3], LedgerInitializeWeb4SingleStepsTest.PASSWORD); - String encodedPassword = KeyGenCommand.encodePasswordAsBase58(LedgerInitializeWeb4SingleStepsTest.PASSWORD); + String encodedPassword = KeyGenUtils.encodePasswordAsBase58(LedgerInitializeWeb4SingleStepsTest.PASSWORD); CountDownLatch quitLatch = new CountDownLatch(4); diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/batch/bftsmart/BftsmartLedgerInit.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/batch/bftsmart/BftsmartLedgerInit.java index 11f7d8e6..4d45e4a0 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/batch/bftsmart/BftsmartLedgerInit.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/batch/bftsmart/BftsmartLedgerInit.java @@ -10,6 +10,7 @@ package test.com.jd.blockchain.intgr.batch.bftsmart; import com.jd.blockchain.crypto.AsymmetricKeypair; import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.gateway.GatewayConfigProperties; @@ -21,7 +22,6 @@ import com.jd.blockchain.sdk.client.GatewayServiceFactory; import com.jd.blockchain.storage.service.DbConnectionFactory; import com.jd.blockchain.tools.initializer.LedgerBindingConfig; import com.jd.blockchain.tools.initializer.LedgerInitCommand; -import com.jd.blockchain.tools.keygen.KeyGenCommand; import com.jd.blockchain.utils.concurrent.ThreadInvoker; import com.jd.blockchain.utils.io.FileUtils; import com.jd.blockchain.utils.net.NetworkAddress; @@ -177,9 +177,9 @@ public class BftsmartLedgerInit { GatewayServiceFactory gwsrvFact = GatewayServiceFactory.connect(gateway.getServiceAddress()); - PrivKey privkey0 = KeyGenCommand.decodePrivKeyWithRawPassword(BftsmartConfig.PRIV_KEY[0], IntegrationBase.PASSWORD); + PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(BftsmartConfig.PRIV_KEY[0], IntegrationBase.PASSWORD); - PubKey pubKey0 = KeyGenCommand.decodePubKey(BftsmartConfig.PUB_KEY[0]); + PubKey pubKey0 = KeyGenUtils.decodePubKey(BftsmartConfig.PUB_KEY[0]); AsymmetricKeypair adminKey = new AsymmetricKeypair(pubKey0, privkey0); @@ -233,7 +233,7 @@ public class BftsmartLedgerInit { } public GatewayTestRunner initGateWay(PeerTestRunner peerNode) { - String encodedBase58Pwd = KeyGenCommand.encodePasswordAsBase58(LedgerInitializeTest.PASSWORD); + String encodedBase58Pwd = KeyGenUtils.encodePasswordAsBase58(LedgerInitializeTest.PASSWORD); GatewayConfigProperties.KeyPairConfig gwkey0 = new GatewayConfigProperties.KeyPairConfig(); gwkey0.setPubKeyValue(BftsmartConfig.PUB_KEY[0]); diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/batch/bftsmart/BftsmartTestBase.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/batch/bftsmart/BftsmartTestBase.java index f94f9364..9a485a22 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/batch/bftsmart/BftsmartTestBase.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/batch/bftsmart/BftsmartTestBase.java @@ -8,8 +8,8 @@ */ package test.com.jd.blockchain.intgr.batch.bftsmart; -import static com.jd.blockchain.tools.keygen.KeyGenCommand.encodePrivKey; -import static com.jd.blockchain.tools.keygen.KeyGenCommand.encodePubKey; +import static com.jd.blockchain.crypto.KeyGenUtils.encodePrivKey; +import static com.jd.blockchain.crypto.KeyGenUtils.encodePubKey; import org.junit.Test; diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeTest.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeTest.java index 09ddf134..e667b51a 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeTest.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeTest.java @@ -13,13 +13,12 @@ import org.junit.Test; import org.springframework.core.io.ClassPathResource; import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.consensus.ConsensusProvider; -import com.jd.blockchain.consensus.ConsensusSettings; import com.jd.blockchain.crypto.AddressEncoding; import com.jd.blockchain.crypto.AsymmetricKeypair; import com.jd.blockchain.crypto.Crypto; import com.jd.blockchain.crypto.CryptoProvider; import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.SignatureDigest; @@ -27,23 +26,24 @@ import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; import com.jd.blockchain.crypto.service.sm.SMCryptoService; import com.jd.blockchain.ledger.LedgerBlock; import com.jd.blockchain.ledger.LedgerInitOperation; +import com.jd.blockchain.ledger.LedgerInitProperties; +import com.jd.blockchain.ledger.RolesConfigureOperation; +import com.jd.blockchain.ledger.UserAuthorizeOperation; import com.jd.blockchain.ledger.UserRegisterOperation; import com.jd.blockchain.ledger.core.CryptoConfig; import com.jd.blockchain.ledger.core.LedgerInitDecision; -import com.jd.blockchain.ledger.core.LedgerInitPermission; +import com.jd.blockchain.ledger.core.LedgerInitProposal; +import com.jd.blockchain.ledger.core.LedgerManager; import com.jd.blockchain.ledger.core.LedgerRepository; import com.jd.blockchain.ledger.core.UserAccount; -import com.jd.blockchain.ledger.core.UserAccountSet; -import com.jd.blockchain.ledger.core.impl.LedgerManager; +import com.jd.blockchain.ledger.core.UserAccountQuery; import com.jd.blockchain.storage.service.utils.MemoryDBConnFactory; import com.jd.blockchain.tools.initializer.DBConnectionConfig; import com.jd.blockchain.tools.initializer.LedgerInitProcess; -import com.jd.blockchain.tools.initializer.LedgerInitProperties; import com.jd.blockchain.tools.initializer.Prompter; import com.jd.blockchain.tools.initializer.web.InitConsensusServiceFactory; import com.jd.blockchain.tools.initializer.web.LedgerInitConsensusService; import com.jd.blockchain.tools.initializer.web.LedgerInitializeWebController; -import com.jd.blockchain.tools.keygen.KeyGenCommand; import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.concurrent.ThreadInvoker; import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; @@ -59,6 +59,8 @@ public class LedgerInitializeTest { static { DataContractRegistry.register(LedgerInitOperation.class); DataContractRegistry.register(UserRegisterOperation.class); + DataContractRegistry.register(RolesConfigureOperation.class); + DataContractRegistry.register(UserAuthorizeOperation.class); } private static final String[] SUPPORTED_PROVIDERS = { ClassicCryptoService.class.getName(), @@ -101,22 +103,22 @@ public class LedgerInitializeTest { NodeContext node3 = new NodeContext(initSetting.getConsensusParticipant(3).getInitializerAddress(), serviceRegisterMap); - PrivKey privkey0 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[0], PASSWORD); + PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[0], PASSWORD); DBConnectionConfig testDb0 = new DBConnectionConfig(); testDb0.setConnectionUri(dbConnections[0]); AsyncCallback callback0 = node0.startInit(0, privkey0, initSetting, testDb0, consolePrompter); - PrivKey privkey1 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD); + PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD); DBConnectionConfig testDb1 = new DBConnectionConfig(); testDb1.setConnectionUri(dbConnections[1]); AsyncCallback callback1 = node1.startInit(1, privkey1, initSetting, testDb1, consolePrompter); - PrivKey privkey2 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD); + PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD); DBConnectionConfig testDb2 = new DBConnectionConfig(); testDb2.setConnectionUri(dbConnections[2]); AsyncCallback callback2 = node2.startInit(2, privkey2, initSetting, testDb2, consolePrompter); - PrivKey privkey3 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD); + PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD); DBConnectionConfig testDb03 = new DBConnectionConfig(); testDb03.setConnectionUri(dbConnections[3]); AsyncCallback callback3 = node3.startInit(3, privkey3, initSetting, testDb03, consolePrompter); @@ -145,24 +147,24 @@ public class LedgerInitializeTest { assertEquals(0, genesisBlock.getHeight()); assertEquals(ledgerHash0, genesisBlock.getHash()); - UserAccountSet userset0 = ledger0.getUserAccountSet(genesisBlock); + UserAccountQuery userset0 = ledger0.getUserAccountSet(genesisBlock); - PubKey pubKey0 = KeyGenCommand.decodePubKey(PUB_KEYS[0]); + PubKey pubKey0 = KeyGenUtils.decodePubKey(PUB_KEYS[0]); Bytes address0 = AddressEncoding.generateAddress(pubKey0); UserAccount user0_0 = userset0.getUser(address0); assertNotNull(user0_0); - PubKey pubKey1 = KeyGenCommand.decodePubKey(PUB_KEYS[1]); + PubKey pubKey1 = KeyGenUtils.decodePubKey(PUB_KEYS[1]); Bytes address1 = AddressEncoding.generateAddress(pubKey1); UserAccount user1_0 = userset0.getUser(address1); assertNotNull(user1_0); - PubKey pubKey2 = KeyGenCommand.decodePubKey(PUB_KEYS[2]); + PubKey pubKey2 = KeyGenUtils.decodePubKey(PUB_KEYS[2]); Bytes address2 = AddressEncoding.generateAddress(pubKey2); UserAccount user2_0 = userset0.getUser(address2); assertNotNull(user2_0); - PubKey pubKey3 = KeyGenCommand.decodePubKey(PUB_KEYS[3]); + PubKey pubKey3 = KeyGenUtils.decodePubKey(PUB_KEYS[3]); Bytes address3 = AddressEncoding.generateAddress(pubKey3); UserAccount user3_0 = userset0.getUser(address3); assertNotNull(user3_0); @@ -227,7 +229,7 @@ public class LedgerInitializeTest { public NodeContext(NetworkAddress address, Map serviceRegisterMap) { this.initCsServiceFactory = new MultiThreadInterInvokerFactory(serviceRegisterMap); - LedgerInitializeWebController initController = new LedgerInitializeWebController(ledgerManager, storageDb, + LedgerInitializeWebController initController = new LedgerInitializeWebController(storageDb, initCsServiceFactory); serviceRegisterMap.put(address, initController); this.initProcess = initController; @@ -259,13 +261,16 @@ public class LedgerInitializeTest { cryptoSetting.setSupportedProviders(supportedProviders); cryptoSetting.setAutoVerifyHash(autoVerifyHash); cryptoSetting.setHashAlgorithm(Crypto.getAlgorithm("SHA256")); + + setting.getCryptoProperties().setHashAlgorithm("SHA256"); + setting.getCryptoProperties().setVerifyHash(autoVerifyHash); partiKey = new AsymmetricKeypair(setting.getConsensusParticipant(0).getPubKey(), privKey); ThreadInvoker invoker = new ThreadInvoker() { @Override protected HashDigest invoke() throws Exception { - return initProcess.initialize(currentId, privKey, setting, dbConnConfig, prompter, cryptoSetting); + return initProcess.initialize(currentId, privKey, setting, dbConnConfig, prompter); } }; @@ -301,10 +306,10 @@ public class LedgerInitializeTest { } @Override - public LedgerInitPermission requestPermission(int requesterId, SignatureDigest signature) { - ThreadInvoker invoker = new ThreadInvoker() { + public LedgerInitProposal requestPermission(int requesterId, SignatureDigest signature) { + ThreadInvoker invoker = new ThreadInvoker() { @Override - protected LedgerInitPermission invoke() { + protected LedgerInitProposal invoke() { return initCsService.requestPermission(requesterId, signature); } }; diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeWeb4Nodes.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeWeb4Nodes.java index a37afc62..6909c155 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeWeb4Nodes.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeWeb4Nodes.java @@ -4,16 +4,15 @@ import com.jd.blockchain.consensus.ConsensusProvider; import com.jd.blockchain.consensus.ConsensusSettings; import com.jd.blockchain.crypto.AddressEncoding; import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.ledger.*; import com.jd.blockchain.ledger.core.*; -import com.jd.blockchain.ledger.core.impl.LedgerManager; import com.jd.blockchain.storage.service.DbConnection; import com.jd.blockchain.storage.service.impl.composite.CompositeConnectionFactory; import com.jd.blockchain.tools.initializer.*; import com.jd.blockchain.tools.initializer.web.LedgerInitializeWebController; -import com.jd.blockchain.tools.keygen.KeyGenCommand; import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.concurrent.ThreadInvoker; import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; @@ -88,10 +87,10 @@ public class LedgerInitializeWeb4Nodes { NetworkAddress initAddr3 = initSetting.getConsensusParticipant(3).getInitializerAddress(); NodeWebContext node3 = new NodeWebContext(3, initAddr3); - PrivKey privkey0 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[0], PASSWORD); - PrivKey privkey1 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD); - PrivKey privkey2 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD); - PrivKey privkey3 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD); + PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[0], PASSWORD); + PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD); + PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD); + PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD); CountDownLatch quitLatch = new CountDownLatch(4); @@ -139,27 +138,27 @@ public class LedgerInitializeWeb4Nodes { assertEquals(0, genesisBlock.getHeight()); assertEquals(ledgerHash0, genesisBlock.getHash()); - UserAccountSet userset0 = ledger0.getUserAccountSet(genesisBlock); + UserAccountQuery userset0 = ledger0.getUserAccountSet(genesisBlock); - PubKey pubKey0 = KeyGenCommand.decodePubKey(PUB_KEYS[0]); + PubKey pubKey0 = KeyGenUtils.decodePubKey(PUB_KEYS[0]); Bytes address0 = AddressEncoding.generateAddress(pubKey0); System.out.printf("localNodeAddress0 = %s \r\n", address0.toBase58()); UserAccount user0_0 = userset0.getUser(address0); assertNotNull(user0_0); - PubKey pubKey1 = KeyGenCommand.decodePubKey(PUB_KEYS[1]); + PubKey pubKey1 = KeyGenUtils.decodePubKey(PUB_KEYS[1]); Bytes address1 = AddressEncoding.generateAddress(pubKey1); UserAccount user1_0 = userset0.getUser(address1); assertNotNull(user1_0); System.out.printf("localNodeAddress1 = %s \r\n", address1.toBase58()); - PubKey pubKey2 = KeyGenCommand.decodePubKey(PUB_KEYS[2]); + PubKey pubKey2 = KeyGenUtils.decodePubKey(PUB_KEYS[2]); Bytes address2 = AddressEncoding.generateAddress(pubKey2); UserAccount user2_0 = userset0.getUser(address2); assertNotNull(user2_0); System.out.printf("localNodeAddress2 = %s \r\n", address2.toBase58()); - PubKey pubKey3 = KeyGenCommand.decodePubKey(PUB_KEYS[3]); + PubKey pubKey3 = KeyGenUtils.decodePubKey(PUB_KEYS[3]); Bytes address3 = AddressEncoding.generateAddress(pubKey3); UserAccount user3_0 = userset0.getUser(address3); assertNotNull(user3_0); @@ -213,7 +212,7 @@ public class LedgerInitializeWeb4Nodes { return controller.getInitTxContent(); } - public LedgerInitPermission getLocalPermission() { + public LedgerInitProposal getLocalPermission() { return controller.getLocalPermission(); } diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeWeb4SingleStepsTest.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeWeb4SingleStepsTest.java index 2cf5701d..f627a8d2 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeWeb4SingleStepsTest.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/initializer/LedgerInitializeWeb4SingleStepsTest.java @@ -10,7 +10,6 @@ import java.io.InputStream; import java.util.Properties; import java.util.concurrent.CountDownLatch; -import com.jd.blockchain.transaction.SignatureUtils; import org.springframework.boot.SpringApplication; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.io.ClassPathResource; @@ -19,30 +18,31 @@ import com.jd.blockchain.binaryproto.BinaryProtocol; import com.jd.blockchain.consensus.ConsensusProvider; import com.jd.blockchain.consensus.ConsensusSettings; import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.SignatureDigest; import com.jd.blockchain.ledger.LedgerInitOperation; +import com.jd.blockchain.ledger.LedgerInitProperties; import com.jd.blockchain.ledger.Operation; import com.jd.blockchain.ledger.TransactionContent; import com.jd.blockchain.ledger.UserRegisterOperation; import com.jd.blockchain.ledger.core.LedgerInitDecision; -import com.jd.blockchain.ledger.core.LedgerInitPermission; +import com.jd.blockchain.ledger.core.LedgerInitProposal; +import com.jd.blockchain.ledger.core.LedgerManager; import com.jd.blockchain.ledger.core.LedgerRepository; -import com.jd.blockchain.ledger.core.impl.LedgerManager; import com.jd.blockchain.storage.service.DbConnection; import com.jd.blockchain.storage.service.impl.composite.CompositeConnectionFactory; import com.jd.blockchain.tools.initializer.DBConnectionConfig; import com.jd.blockchain.tools.initializer.LedgerBindingConfig; import com.jd.blockchain.tools.initializer.LedgerInitCommand; import com.jd.blockchain.tools.initializer.LedgerInitProcess; -import com.jd.blockchain.tools.initializer.LedgerInitProperties; import com.jd.blockchain.tools.initializer.Prompter; import com.jd.blockchain.tools.initializer.web.HttpInitConsensServiceFactory; +import com.jd.blockchain.tools.initializer.web.LedgerInitConfiguration; import com.jd.blockchain.tools.initializer.web.LedgerInitConsensusService; import com.jd.blockchain.tools.initializer.web.LedgerInitializeWebController; -import com.jd.blockchain.tools.keygen.KeyGenCommand; -import com.jd.blockchain.transaction.TxRequestBuilder; +import com.jd.blockchain.transaction.SignatureUtils; import com.jd.blockchain.utils.concurrent.ThreadInvoker; import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; import com.jd.blockchain.utils.io.BytesUtils; @@ -79,9 +79,8 @@ public class LedgerInitializeWeb4SingleStepsTest { // 加载共识配置; Properties props = loadConsensusSetting(consensusConfig.getConfigPath()); ConsensusProvider csProvider = LedgerInitConsensusConfig.getConsensusProvider(consensusConfig.getProvider()); - ConsensusSettings csProps = csProvider.getSettingsFactory() - .getConsensusSettingsBuilder() - .createSettings(props, Utils.loadParticipantNodes()); + ConsensusSettings csProps = csProvider.getSettingsFactory().getConsensusSettingsBuilder().createSettings(props, + Utils.loadParticipantNodes()); // 启动服务器; NetworkAddress initAddr0 = initSetting.getConsensusParticipant(0).getInitializerAddress(); @@ -105,21 +104,23 @@ public class LedgerInitializeWeb4SingleStepsTest { node2.setPrompter(prompter); node3.setPrompter(prompter); - PrivKey privkey0 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[0], PASSWORD); - PrivKey privkey1 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD); - PrivKey privkey2 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD); - PrivKey privkey3 = KeyGenCommand.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD); + PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[0], PASSWORD); + PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[1], PASSWORD); + PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[2], PASSWORD); + PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(PRIV_KEYS[3], PASSWORD); - PubKey pubKey0 = KeyGenCommand.decodePubKey(PUB_KEYS[0]); - PubKey pubKey1 = KeyGenCommand.decodePubKey(PUB_KEYS[1]); - PubKey pubKey2 = KeyGenCommand.decodePubKey(PUB_KEYS[2]); - PubKey pubKey3 = KeyGenCommand.decodePubKey(PUB_KEYS[3]); + PubKey pubKey0 = KeyGenUtils.decodePubKey(PUB_KEYS[0]); + PubKey pubKey1 = KeyGenUtils.decodePubKey(PUB_KEYS[1]); + PubKey pubKey2 = KeyGenUtils.decodePubKey(PUB_KEYS[2]); + PubKey pubKey3 = KeyGenUtils.decodePubKey(PUB_KEYS[3]); // 测试生成“账本初始化许可”; - LedgerInitPermission permission0 = testPreparePermisssion(node0, privkey0, initSetting, csProps); - LedgerInitPermission permission1 = testPreparePermisssion(node1, privkey1, initSetting, csProps); - LedgerInitPermission permission2 = testPreparePermisssion(node2, privkey2, initSetting, csProps); - LedgerInitPermission permission3 = testPreparePermisssion(node3, privkey3, initSetting, csProps); + LedgerInitConfiguration initConfig = LedgerInitConfiguration.create(initSetting); + initConfig.setConsensusSettings(csProvider, csProps); + LedgerInitProposal permission0 = testPreparePermisssion(node0, privkey0, initConfig); + LedgerInitProposal permission1 = testPreparePermisssion(node1, privkey1, initConfig); + LedgerInitProposal permission2 = testPreparePermisssion(node2, privkey2, initConfig); + LedgerInitProposal permission3 = testPreparePermisssion(node3, privkey3, initConfig); TransactionContent initTxContent0 = node0.getInitTxContent(); TransactionContent initTxContent1 = node1.getInitTxContent(); @@ -240,9 +241,9 @@ public class LedgerInitializeWeb4SingleStepsTest { testRequestDecision(node3, node2, initCsService2); } - private LedgerInitPermission testPreparePermisssion(NodeWebContext node, PrivKey privKey, - LedgerInitProperties setting, ConsensusSettings csProps) { - LedgerInitPermission permission = node.preparePermision(privKey, setting, csProps); + private LedgerInitProposal testPreparePermisssion(NodeWebContext node, PrivKey privKey, + LedgerInitConfiguration setting) { + LedgerInitProposal permission = node.preparePermision(privKey, setting); assertEquals(node.getId(), permission.getParticipantId()); assertNotNull(permission.getTransactionSignature()); @@ -253,7 +254,7 @@ public class LedgerInitializeWeb4SingleStepsTest { private void testRequestPermission(NodeWebContext fromNode, PrivKey fromPrivkey, NodeWebContext targetNode, LedgerInitConsensusService targetNodeService) { SignatureDigest reqSignature = fromNode.createPermissionRequestSignature(fromNode.getId(), fromPrivkey); - LedgerInitPermission targetPermission = targetNodeService.requestPermission(fromNode.getId(), reqSignature); + LedgerInitProposal targetPermission = targetNodeService.requestPermission(fromNode.getId(), reqSignature); assertEquals(targetNode.getId(), targetPermission.getParticipantId()); assertEquals(targetNode.getLocalPermission().getTransactionSignature(), targetPermission.getTransactionSignature()); @@ -312,7 +313,7 @@ public class LedgerInitializeWeb4SingleStepsTest { return controller.getInitTxContent(); } - public LedgerInitPermission getLocalPermission() { + public LedgerInitProposal getLocalPermission() { return controller.getLocalPermission(); } @@ -385,9 +386,8 @@ public class LedgerInitializeWeb4SingleStepsTest { return invoker.start(); } - public LedgerInitPermission preparePermision(PrivKey privKey, LedgerInitProperties setting, - ConsensusSettings csProps) { - return controller.prepareLocalPermission(id, privKey, setting, csProps); + public LedgerInitProposal preparePermision(PrivKey privKey, LedgerInitConfiguration setting) { + return controller.prepareLocalPermission(id, privKey, setting); } public boolean consensusPermission(PrivKey privKey) { diff --git a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/ledger/LedgerBlockGeneratingTest.java b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/ledger/LedgerBlockGeneratingTest.java index 306d065f..0e1b2755 100644 --- a/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/ledger/LedgerBlockGeneratingTest.java +++ b/source/test/test-integration/src/test/java/test/com/jd/blockchain/intgr/ledger/LedgerBlockGeneratingTest.java @@ -18,24 +18,24 @@ import com.jd.blockchain.consensus.ConsensusProviders; import com.jd.blockchain.consensus.ConsensusSettings; import com.jd.blockchain.crypto.AsymmetricKeypair; import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.ledger.BlockchainKeyGenerator; import com.jd.blockchain.ledger.BlockchainKeypair; import com.jd.blockchain.ledger.LedgerBlock; +import com.jd.blockchain.ledger.LedgerInitProperties; import com.jd.blockchain.ledger.TransactionRequest; import com.jd.blockchain.ledger.TransactionRequestBuilder; -import com.jd.blockchain.ledger.core.LedgerDataSet; +import com.jd.blockchain.ledger.core.DefaultOperationHandleRegisteration; +import com.jd.blockchain.ledger.core.LedgerDataQuery; import com.jd.blockchain.ledger.core.LedgerEditor; +import com.jd.blockchain.ledger.core.LedgerManager; import com.jd.blockchain.ledger.core.LedgerRepository; -import com.jd.blockchain.ledger.core.impl.DefaultOperationHandleRegisteration; -import com.jd.blockchain.ledger.core.impl.LedgerManager; -import com.jd.blockchain.ledger.core.impl.TransactionBatchProcessor; +import com.jd.blockchain.ledger.core.TransactionBatchProcessor; import com.jd.blockchain.service.TransactionBatchResultHandle; import com.jd.blockchain.tools.initializer.DBConnectionConfig; -import com.jd.blockchain.tools.initializer.LedgerInitProperties; import com.jd.blockchain.tools.initializer.Prompter; import com.jd.blockchain.tools.initializer.web.LedgerInitConsensusService; -import com.jd.blockchain.tools.keygen.KeyGenCommand; import com.jd.blockchain.transaction.TxBuilder; import com.jd.blockchain.utils.ConsoleUtils; import com.jd.blockchain.utils.concurrent.ThreadInvoker.AsyncCallback; @@ -45,6 +45,7 @@ import com.jd.blockchain.utils.net.NetworkAddress; import test.com.jd.blockchain.intgr.PresetAnswerPrompter; import test.com.jd.blockchain.intgr.initializer.LedgerInitializeTest; import test.com.jd.blockchain.intgr.initializer.LedgerInitializeTest.NodeContext; +import test.com.jd.blockchain.intgr.perf.LedgerPerformanceTest; import test.com.jd.blockchain.intgr.perf.Utils; public class LedgerBlockGeneratingTest { @@ -76,12 +77,13 @@ public class LedgerBlockGeneratingTest { LedgerBlock latestBlock = ledger.getLatestBlock(); assertEquals(height + i, latestBlock.getHeight()); - LedgerDataSet previousDataSet = ledger.getDataSet(latestBlock); + LedgerDataQuery previousDataSet = ledger.getDataSet(latestBlock); ConsoleUtils.info("------ 开始执行交易, 即将生成区块[%s] ------", (latestBlock.getHeight() + 1)); long startTs = System.currentTimeMillis(); LedgerEditor newEditor = ledger.createNextBlock(); - TransactionBatchProcessor txProc = new TransactionBatchProcessor(newEditor, previousDataSet, opHandler, + TransactionBatchProcessor txProc = new TransactionBatchProcessor( + LedgerPerformanceTest.DEFAULT_SECURITY_MANAGER, newEditor, previousDataSet, opHandler, ledgerManager); testTxExec(txList, i * batchSize, batchSize, txProc); @@ -129,9 +131,8 @@ public class LedgerBlockGeneratingTest { LedgerInitProperties initSetting = loadInitSetting(); Properties props = loadConsensusSetting(); ConsensusProvider csProvider = getConsensusProvider(); - ConsensusSettings csProps = csProvider.getSettingsFactory() - .getConsensusSettingsBuilder() - .createSettings(props, Utils.loadParticipantNodes()); + ConsensusSettings csProps = csProvider.getSettingsFactory().getConsensusSettingsBuilder().createSettings(props, + Utils.loadParticipantNodes()); NodeContext node0 = new NodeContext(initSetting.getConsensusParticipant(0).getInitializerAddress(), serviceRegisterMap); @@ -145,28 +146,28 @@ public class LedgerBlockGeneratingTest { String[] memConns = new String[] { "memory://local/0", "memory://local/1", "memory://local/2", "memory://local/3" }; - PrivKey privkey0 = KeyGenCommand.decodePrivKeyWithRawPassword(LedgerInitializeTest.PRIV_KEYS[0], + PrivKey privkey0 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeTest.PRIV_KEYS[0], LedgerInitializeTest.PASSWORD); DBConnectionConfig testDb0 = new DBConnectionConfig(); testDb0.setConnectionUri(memConns[0]); AsyncCallback callback0 = node0.startInit(0, privkey0, initSetting, testDb0, consolePrompter, !optimized); - PrivKey privkey1 = KeyGenCommand.decodePrivKeyWithRawPassword(LedgerInitializeTest.PRIV_KEYS[1], + PrivKey privkey1 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeTest.PRIV_KEYS[1], LedgerInitializeTest.PASSWORD); DBConnectionConfig testDb1 = new DBConnectionConfig(); testDb1.setConnectionUri(memConns[1]); AsyncCallback callback1 = node1.startInit(1, privkey1, initSetting, testDb1, consolePrompter, !optimized); - PrivKey privkey2 = KeyGenCommand.decodePrivKeyWithRawPassword(LedgerInitializeTest.PRIV_KEYS[2], + PrivKey privkey2 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeTest.PRIV_KEYS[2], LedgerInitializeTest.PASSWORD); DBConnectionConfig testDb2 = new DBConnectionConfig(); testDb2.setConnectionUri(memConns[2]); AsyncCallback callback2 = node2.startInit(2, privkey2, initSetting, testDb2, consolePrompter, !optimized); - PrivKey privkey3 = KeyGenCommand.decodePrivKeyWithRawPassword(LedgerInitializeTest.PRIV_KEYS[3], + PrivKey privkey3 = KeyGenUtils.decodePrivKeyWithRawPassword(LedgerInitializeTest.PRIV_KEYS[3], LedgerInitializeTest.PASSWORD); DBConnectionConfig testDb03 = new DBConnectionConfig(); testDb03.setConnectionUri(memConns[3]); diff --git a/source/test/test-integration/src/test/resources/ledger_init_test.init b/source/test/test-integration/src/test/resources/ledger_init_test.init index 7b303e35..4253311e 100644 --- a/source/test/test-integration/src/test/resources/ledger_init_test.init +++ b/source/test/test-integration/src/test/resources/ledger_init_test.init @@ -3,11 +3,53 @@ ledger.seed=932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffe #账本的描述名称;此属性不参与共识,仅仅在当前参与方的本地节点用于描述用途; -ledger.name=test-ledger +ledger.name=TEST-LEDGER #声明的账本创建时间;格式为 “yyyy-MM-dd HH:mm:ss.SSSZ”,表示”年-月-日 时:分:秒:毫秒时区“;例如:“2019-08-01 14:26:58.069+0800”,其中,+0800 表示时区是东8区 created-time=2019-08-01 14:26:58.069+0800 +#----------------------------------------------- +# 初始的角色名称列表;可选项; +# 角色名称不区分大小写,最长不超过20个字符;多个角色名称之间用半角的逗点“,”分隔; +# 系统会预置一个默认角色“DEFAULT”,所有未指定角色的用户都以赋予该角色的权限;若初始化时未配置默认角色的权限,则为默认角色分配所有权限; +# +# 注:如果声明了角色,但未声明角色对应的权限清单,这会忽略该角色的初始化; +# +security.roles=DEFAULT, ADMIN, MANAGER, GUEST + +# 赋予角色的账本权限清单;可选项; +# 可选的权限如下; +# AUTHORIZE_ROLES, SET_CONSENSUS, SET_CRYPTO, REGISTER_PARTICIPANT, +# REGISTER_USER, REGISTER_DATA_ACCOUNT, REGISTER_CONTRACT, UPGRADE_CONTRACT, +# SET_USER_ATTRIBUTES, WRITE_DATA_ACCOUNT, +# APPROVE_TX, CONSENSUS_TX +# 多项权限之间用逗点“,”分隔; +# +security.role.DEFAULT.ledger-privileges=REGISTER_USER, REGISTER_DATA_ACCOUNT + +# 赋予角色的交易权限清单;可选项; +# 可选的权限如下; +# DIRECT_OPERATION, CONTRACT_OPERATION +# 多项权限之间用逗点“,”分隔; +# +security.role.DEFAULT.tx-privileges=DIRECT_OPERATION, CONTRACT_OPERATION + +# 其它角色的配置示例; +# 系统管理员角色:只能操作全局性的参数配置和用户注册,只能执行直接操作指令; +security.role.ADMIN.ledger-privileges=CONFIGURE_ROLES, AUTHORIZE_USER_ROLES, SET_CONSENSUS, SET_CRYPTO, REGISTER_PARTICIPANT, REGISTER_USER +security.role.ADMIN.tx-privileges=DIRECT_OPERATION + +# 业务主管角色:只能够执行账本数据相关的操作,包括注册用户、注册数据账户、注册合约、升级合约、写入数据等;能够执行直接操作指令和调用合约; +security.role.MANAGER.ledger-privileges=CONFIGURE_ROLES, AUTHORIZE_USER_ROLES, REGISTER_USER, REGISTER_DATA_ACCOUNT, REGISTER_CONTRACT, UPGRADE_CONTRACT, SET_USER_ATTRIBUTES, WRITE_DATA_ACCOUNT, +security.role.MANAGER.tx-privileges=DIRECT_OPERATION, CONTRACT_OPERATION + +# 访客角色:不具备任何的账本权限,只有数据读取的操作;也只能够通过调用合约来读取数据; +security.role.GUEST.ledger-privileges= +security.role.GUEST.tx-privileges=CONTRACT_OPERATION + + + +#----------------------------------------------- #共识服务提供者;必须; consensus.service-provider=com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider @@ -18,6 +60,12 @@ consensus.conf=classpath:bftsmart.config crypto.service-providers=com.jd.blockchain.crypto.service.classic.ClassicCryptoService, \ com.jd.blockchain.crypto.service.sm.SMCryptoService +#从存储中加载账本数据时,是否校验哈希;可选; +crypto.verify-hash=true + +#哈希算法; +crypto.hash-algorithm=SHA256 + #参与方的个数,后续以 cons_parti.id 分别标识每一个参与方的配置; cons_parti.count=4 @@ -27,6 +75,10 @@ cons_parti.0.name=jd.com cons_parti.0.pubkey-path=keys/jd-com.pub #第0个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; cons_parti.0.pubkey=3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9 +#第0个参与方的角色清单;可选项; +cons_parti.0.roles=ADMIN, MANAGER +#第0个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; +cons_parti.0.roles-policy=UNION #第0个参与方的共识服务的主机地址; cons_parti.0.consensus.host=127.0.0.1 #第0个参与方的共识服务的端口; @@ -46,6 +98,10 @@ cons_parti.1.name=at.com cons_parti.1.pubkey-path=keys/at-com.pub #第1个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; cons_parti.1.pubkey=3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX +#第1个参与方的角色清单;可选项; +cons_parti.1.roles=MANAGER +#第1个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; +cons_parti.1.roles-policy=UNION #第1个参与方的共识服务的主机地址; cons_parti.1.consensus.host=127.0.0.1 #第1个参与方的共识服务的端口; @@ -65,6 +121,10 @@ cons_parti.2.name=bt.com cons_parti.2.pubkey-path=keys/bt-com.pub #第2个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; cons_parti.2.pubkey=3snPdw7i7PZi6TStiyc6mzjprnNhgs2atSGNS8wPYzhbKaUWGFJt7x +#第2个参与方的角色清单;可选项; +cons_parti.2.roles=MANAGER +#第2个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; +cons_parti.2.roles-policy=UNION #第2个参与方的共识服务的主机地址; cons_parti.2.consensus.host=127.0.0.1 #第2个参与方的共识服务的端口; @@ -84,6 +144,10 @@ cons_parti.3.name=xt.com cons_parti.3.pubkey-path=keys/xt-com.pub #第3个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; cons_parti.3.pubkey=3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk +#第3个参与方的角色清单;可选项; +cons_parti.3.roles=GUEST +#第3个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; +cons_parti.3.roles-policy=INTERSECT #第3个参与方的共识服务的主机地址; cons_parti.3.consensus.host=127.0.0.1 #第3个参与方的共识服务的端口; diff --git a/source/test/test-integration/src/test/resources/logback-test.xml b/source/test/test-integration/src/test/resources/logback-test.xml new file mode 100644 index 00000000..29013782 --- /dev/null +++ b/source/test/test-integration/src/test/resources/logback-test.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/source/test/test-ledger-core/pom.xml b/source/test/test-ledger-core/pom.xml index c7350156..4d831fdc 100644 --- a/source/test/test-ledger-core/pom.xml +++ b/source/test/test-ledger-core/pom.xml @@ -20,10 +20,16 @@ storage-redis ${project.version} + + com.jd.blockchain + storage-rocksdb + ${project.version} + com.jd.blockchain crypto-classic ${project.version} + \ No newline at end of file diff --git a/source/test/test-ledger-core/src/main/java/test/perf/com/jd/blockchain/ledger/core/MerkleDatasetPerformanceTester.java b/source/test/test-ledger-core/src/main/java/test/perf/com/jd/blockchain/ledger/core/MerkleDatasetPerformanceTester.java index ef2f6064..bd614126 100644 --- a/source/test/test-ledger-core/src/main/java/test/perf/com/jd/blockchain/ledger/core/MerkleDatasetPerformanceTester.java +++ b/source/test/test-ledger-core/src/main/java/test/perf/com/jd/blockchain/ledger/core/MerkleDatasetPerformanceTester.java @@ -3,9 +3,10 @@ package test.perf.com.jd.blockchain.ledger.core; import java.io.IOException; import java.util.Random; -import com.jd.blockchain.crypto.CryptoAlgorithm; import com.jd.blockchain.crypto.Crypto; +import com.jd.blockchain.crypto.CryptoProvider; import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; import com.jd.blockchain.ledger.core.CryptoConfig; import com.jd.blockchain.ledger.core.MerkleDataSet; import com.jd.blockchain.storage.service.DbConnection; @@ -16,6 +17,8 @@ import com.jd.blockchain.storage.service.utils.MemoryKVStorage; public class MerkleDatasetPerformanceTester { + private static final String[] SUPPORTED_PROVIDERS = { ClassicCryptoService.class.getName() }; + private static final String MKL_KEY_PREFIX = ""; public static void main(String[] args) { @@ -131,7 +134,13 @@ public class MerkleDatasetPerformanceTester { VersioningKVStorage verStorage) { Random rand = new Random(); + CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length]; + for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) { + supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]); + } + CryptoConfig cryptoConfig = new CryptoConfig(); + cryptoConfig.setSupportedProviders(supportedProviders); cryptoConfig.setHashAlgorithm(Crypto.getAlgorithm("SHA256")); cryptoConfig.setAutoVerifyHash(true); diff --git a/source/tools/pom.xml b/source/tools/pom.xml index d10fd85f..72142be9 100644 --- a/source/tools/pom.xml +++ b/source/tools/pom.xml @@ -15,7 +15,7 @@ tools-initializer tools-initializer-booter tools-capability - tools-mocker + \ No newline at end of file diff --git a/source/tools/tools-capability/src/main/java/com/jd/blockchain/capability/service/SettingsInit.java b/source/tools/tools-capability/src/main/java/com/jd/blockchain/capability/service/SettingsInit.java index 868a8e09..0c0e6db9 100644 --- a/source/tools/tools-capability/src/main/java/com/jd/blockchain/capability/service/SettingsInit.java +++ b/source/tools/tools-capability/src/main/java/com/jd/blockchain/capability/service/SettingsInit.java @@ -15,10 +15,10 @@ import com.jd.blockchain.consensus.bftsmart.BftsmartConsensusSettings; import com.jd.blockchain.consensus.bftsmart.BftsmartNodeSettings; import com.jd.blockchain.crypto.AsymmetricKeypair; import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.ledger.*; -import com.jd.blockchain.tools.keygen.KeyGenCommand; import com.jd.blockchain.utils.codec.Base58Utils; /** @@ -106,8 +106,8 @@ public class SettingsInit { CapabilitySettings.ledgerHash = hash; // 处理用户 - PrivKey privKey = KeyGenCommand.decodePrivKeyWithRawPassword(settings.getPrivKey(), settings.getPwd()); - PubKey pubKey = KeyGenCommand.decodePubKey(settings.getPubKey()); + PrivKey privKey = KeyGenUtils.decodePrivKeyWithRawPassword(settings.getPrivKey(), settings.getPwd()); + PubKey pubKey = KeyGenUtils.decodePubKey(settings.getPubKey()); CapabilitySettings.adminKey = new AsymmetricKeypair(pubKey, privKey); } diff --git a/source/tools/tools-initializer/pom.xml b/source/tools/tools-initializer/pom.xml index f4cfe07d..b4f51d28 100644 --- a/source/tools/tools-initializer/pom.xml +++ b/source/tools/tools-initializer/pom.xml @@ -72,18 +72,18 @@ org.springframework.boot spring-boot-starter-web - + - + org.springframework.boot diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/InitializerConfiguration.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/InitializerConfiguration.java index 3ad076d9..5129433f 100644 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/InitializerConfiguration.java +++ b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/InitializerConfiguration.java @@ -2,8 +2,12 @@ package com.jd.blockchain.tools.initializer; import org.springframework.context.annotation.Configuration; +/** + * Spring Boot 项目的配置类; + * + * @author huanghaiquan + * + */ @Configuration public interface InitializerConfiguration { - - } diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitCommand.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitCommand.java index 4617076a..c39da297 100644 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitCommand.java +++ b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitCommand.java @@ -2,8 +2,6 @@ package com.jd.blockchain.tools.initializer; import java.io.File; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -14,12 +12,13 @@ import org.springframework.context.ConfigurableApplicationContext; import com.jd.blockchain.crypto.AddressEncoding; import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.ledger.core.impl.LedgerManager; +import com.jd.blockchain.ledger.LedgerInitProperties; +import com.jd.blockchain.ledger.LedgerInitProperties.ParticipantProperties; +import com.jd.blockchain.ledger.core.LedgerManager; import com.jd.blockchain.tools.initializer.LedgerBindingConfig.BindingConfig; -import com.jd.blockchain.tools.initializer.LedgerInitProperties.ConsensusParticipantConfig; -import com.jd.blockchain.tools.keygen.KeyGenCommand; import com.jd.blockchain.utils.ArgumentSet; import com.jd.blockchain.utils.ArgumentSet.ArgEntry; import com.jd.blockchain.utils.ArgumentSet.Setting; @@ -88,18 +87,18 @@ public class LedgerInitCommand { // load ledger init setting; LedgerInitProperties ledgerInitProperties = LedgerInitProperties.resolve(iniArg.getValue()); String localNodePubKeyString = localConf.getLocal().getPubKeyString(); - PubKey localNodePubKey = KeyGenCommand.decodePubKey(localNodePubKeyString); + PubKey localNodePubKey = KeyGenUtils.decodePubKey(localNodePubKeyString); // 地址根据公钥生成 String localNodeAddress = AddressEncoding.generateAddress(localNodePubKey).toBase58(); // 加载全部公钥; int currId = -1; for (int i = 0; i < ledgerInitProperties.getConsensusParticipantCount(); i++) { - ConsensusParticipantConfig partiConf = ledgerInitProperties.getConsensusParticipant(i); + ParticipantProperties partiConf = ledgerInitProperties.getConsensusParticipant(i); // String partiAddress = partiConf.getAddress(); // if (partiAddress == null) { // if (partiConf.getPubKeyPath() != null) { -// PubKey pubKey = KeyGenCommand.readPubKey(partiConf.getPubKeyPath()); +// PubKey pubKey = KeyGenUtils.readPubKey(partiConf.getPubKeyPath()); // partiConf.setPubKey(pubKey); // partiAddress = partiConf.getAddress(); // } @@ -116,9 +115,9 @@ public class LedgerInitCommand { // 加载当前节点的私钥; String base58Pwd = localConf.getLocal().getPassword(); if (base58Pwd == null) { - base58Pwd = KeyGenCommand.readPasswordString(); + base58Pwd = KeyGenUtils.readPasswordString(); } - PrivKey privKey = KeyGenCommand.decodePrivKey(localConf.getLocal().getPrivKeyString(), base58Pwd); + PrivKey privKey = KeyGenUtils.decodePrivKey(localConf.getLocal().getPrivKeyString(), base58Pwd); // Output ledger binding config of peer; if (!FileUtils.existDirectory(localConf.getBindingOutDir())) { @@ -186,11 +185,12 @@ public class LedgerInitCommand { // 设置账本名称 bindingConf.setLedgerName(ledgerInitProperties.getLedgerName()); - bindingConf.getParticipant().setAddress(ledgerInitProperties.getConsensusParticipant(currId).getAddress()); + bindingConf.getParticipant() + .setAddress(ledgerInitProperties.getConsensusParticipant(currId).getAddress().toBase58()); // 设置参与方名称 bindingConf.getParticipant().setName(ledgerInitProperties.getConsensusParticipant(currId).getName()); - String encodedPrivKey = KeyGenCommand.encodePrivKey(privKey, base58Pwd); + String encodedPrivKey = KeyGenUtils.encodePrivKey(privKey, base58Pwd); bindingConf.getParticipant().setPk(encodedPrivKey); bindingConf.getParticipant().setPassword(base58Pwd); diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitProcess.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitProcess.java index 58b01af5..71cc6816 100644 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitProcess.java +++ b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/LedgerInitProcess.java @@ -3,6 +3,8 @@ package com.jd.blockchain.tools.initializer; import com.jd.blockchain.crypto.HashDigest; import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.ledger.CryptoSetting; +import com.jd.blockchain.ledger.LedgerInitProperties; +import com.jd.blockchain.tools.initializer.web.LedgerInitConfiguration; /** * @@ -27,13 +29,13 @@ public interface LedgerInitProcess { /** * @param currentId * @param privKey - * @param ledgerInitProps + * @param ledgerInitConfig * @param dbConnConfig * @param prompter * @param cryptoSetting * @return */ - HashDigest initialize(int currentId, PrivKey privKey, LedgerInitProperties ledgerInitProps, - DBConnectionConfig dbConnConfig, Prompter prompter, CryptoSetting cryptoSetting); + HashDigest initialize(int currentId, PrivKey privKey, LedgerInitConfiguration ledgerInitConfig, + DBConnectionConfig dbConnConfig, Prompter prompter); } 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 ba60ec8c..e9d3017d 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 @@ -3,7 +3,7 @@ package com.jd.blockchain.tools.initializer.web; import java.io.InputStream; import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.tools.initializer.LedgerInitException; +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; 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 ec918972..69195dad 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 @@ -8,7 +8,7 @@ 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.impl.LedgerManager; +import com.jd.blockchain.ledger.core.LedgerManager; import com.jd.blockchain.utils.io.ByteArray; import com.jd.blockchain.utils.serialize.json.JSONSerializeUtils; diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitConfiguration.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitConfiguration.java new file mode 100644 index 00000000..6dc9b98b --- /dev/null +++ b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitConfiguration.java @@ -0,0 +1,281 @@ +package com.jd.blockchain.tools.initializer.web; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Properties; +import java.util.Set; + +import com.jd.blockchain.consensus.ConsensusProvider; +import com.jd.blockchain.consensus.ConsensusProviders; +import com.jd.blockchain.consensus.ConsensusSettings; +import com.jd.blockchain.crypto.Crypto; +import com.jd.blockchain.crypto.CryptoAlgorithm; +import com.jd.blockchain.crypto.CryptoProvider; +import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; +import com.jd.blockchain.crypto.service.sm.SMCryptoService; +import com.jd.blockchain.ledger.CryptoSetting; +import com.jd.blockchain.ledger.LedgerInitException; +import com.jd.blockchain.ledger.LedgerInitProperties; +import com.jd.blockchain.ledger.LedgerInitProperties.CryptoProperties; +import com.jd.blockchain.ledger.LedgerInitProperties.ParticipantProperties; +import com.jd.blockchain.ledger.LedgerPermission; +import com.jd.blockchain.ledger.ParticipantNode; +import com.jd.blockchain.ledger.SecurityInitData; +import com.jd.blockchain.ledger.TransactionPermission; +import com.jd.blockchain.ledger.core.CryptoConfig; +import com.jd.blockchain.ledger.core.LedgerSecurityManager; +import com.jd.blockchain.transaction.LedgerInitData; +import com.jd.blockchain.utils.StringUtils; + +public class LedgerInitConfiguration { + + private static final String[] SUPPORTED_PROVIDERS = { ClassicCryptoService.class.getName(), + SMCryptoService.class.getName() }; + + private static final String DEFAULT_HASH_ALGORITHM = "SHA256"; + + private ParticipantProperties[] participants; + + private ConsensusConfig consensusConfiguration; + + private CryptoConfig cryptoConfig; + + private ConsensusConfig consensusConfig; + + private LedgerInitData ledgerSettings; + + private SecurityInitData securitySettings; + + public ParticipantProperties[] getParticipants() { + return participants; + } + + public int getParticipantCount() { + return participants.length; + } + + /** + * @param id + * @return + */ + public ParticipantProperties getParticipant(int id) { + // 注:解析的过程确保了参与方列表是升序排列,且列表中第一个参与方的 id 为 0, id 以 1 递增; + return participants[id]; + } + + public ConsensusConfig getConsensusConfiguration() { + return consensusConfiguration; + } + + public CryptoConfig getCryptoConfig() { + return cryptoConfig; + } + + public ConsensusConfig getConsensusConfig() { + return consensusConfig; + } + + public LedgerInitData getLedgerSettings() { + return ledgerSettings; + } + + public SecurityInitData getSecuritySettings() { + return securitySettings; + } + + private LedgerInitConfiguration() { + } + + public void setConsensusSettings(ConsensusProvider consensusProvider, ConsensusSettings consensusSettings) { + byte[] consensusSettingBytes = encodeConsensusSettings(consensusProvider, consensusSettings); + ledgerSettings.setConsensusProvider(consensusProvider.getName()); + ledgerSettings.setConsensusSettings(consensusSettingBytes); + } + + public static LedgerInitConfiguration create(LedgerInitProperties ledgerInitProps) { + LedgerInitConfiguration ledgerConfig = new LedgerInitConfiguration(); + + CryptoConfig cryptoConfig = createCryptoConfig(ledgerInitProps.getCryptoProperties()); + ledgerConfig.cryptoConfig = cryptoConfig; + + ConsensusConfig consensusConfig = createConsensusConfig(ledgerInitProps); + ledgerConfig.consensusConfig = consensusConfig; + + ParticipantProperties[] participants = resolveParticipants(ledgerInitProps); + ledgerConfig.participants = participants; + + LedgerInitData ledgerSettings = createLedgerInitSettings(ledgerInitProps, cryptoConfig, consensusConfig, + participants); + ledgerConfig.ledgerSettings = ledgerSettings; + + SecurityInitData securitySettings = createSecurityInitSettings(ledgerInitProps, participants); + ledgerConfig.securitySettings = securitySettings; + + return ledgerConfig; + } + + private static ConsensusConfig createConsensusConfig(LedgerInitProperties initProps) { + ConsensusProvider consensusProvider = ConsensusProviders.getProvider(initProps.getConsensusProvider()); + + Properties csProps = initProps.getConsensusConfig(); + ConsensusSettings protocolSettings = consensusProvider.getSettingsFactory().getConsensusSettingsBuilder() + .createSettings(csProps, initProps.getConsensusParticipantNodes()); + + ConsensusConfig config = new ConsensusConfig(); + config.setProvider(consensusProvider); + config.setProtocolSettings(protocolSettings); + + return config; + } + + private static CryptoConfig createCryptoConfig(CryptoProperties cryptoProperties) { + // 总是包含默认的提供者; + Set cryptoProviderNames = new LinkedHashSet(); + for (String providerName : SUPPORTED_PROVIDERS) { + cryptoProviderNames.add(providerName); + } + if (cryptoProperties.getProviders() != null) { + for (String providerName : cryptoProperties.getProviders()) { + cryptoProviderNames.add(providerName); + } + } + CryptoProvider[] cryptoProviders = new CryptoProvider[cryptoProviderNames.size()]; + int i = 0; + for (String providerName : cryptoProviderNames) { + cryptoProviders[i] = Crypto.getProvider(providerName); + i++; + } + + String hashAlgorithmName = StringUtils.trim(cryptoProperties.getHashAlgorithm()); + hashAlgorithmName = hashAlgorithmName.length() == 0 ? DEFAULT_HASH_ALGORITHM : hashAlgorithmName; + CryptoAlgorithm hashAlgorithm = Crypto.getAlgorithm(hashAlgorithmName); + + CryptoConfig cryptoConfig = new CryptoConfig(); + cryptoConfig.setSupportedProviders(cryptoProviders); + cryptoConfig.setAutoVerifyHash(cryptoProperties.isVerifyHash()); + cryptoConfig.setHashAlgorithm(hashAlgorithm); + + return cryptoConfig; + } + + private static SecurityInitData createSecurityInitSettings(LedgerInitProperties ledgerInitProps, + ParticipantProperties[] participants) { + // 设置角色; + SecurityInitData securityInitData = new SecurityInitData(); + securityInitData.setRoles(ledgerInitProps.getRoles()); + // 如果没有默认角色,则创建“默认”角色; + if (securityInitData.getRolesCount() == 0) { + securityInitData.addRole(LedgerSecurityManager.DEFAULT_ROLE, LedgerPermission.values(), + TransactionPermission.values()); + } else if (!securityInitData.containsRole(LedgerSecurityManager.DEFAULT_ROLE)) { + // 如果定义了角色,则必须显式地定义“默认”角色; + throw new LedgerInitException("Miss definition of role[DEFAULT]!"); + } + + // 设置授权; + for (ParticipantProperties partiProps : participants) { + String[] roles = partiProps.getRoles(); + for (String role : roles) { + if (!securityInitData.containsRole(role)) { + throw new LedgerInitException( + String.format("The role[%s] authenticated to participant[%s-%s] is not defined!", role, + partiProps.getId(), partiProps.getName())); + } + } + securityInitData.addUserAuthencation(partiProps.getAddress(), roles, partiProps.getRolesPolicy()); + } + + return securityInitData; + } + + private static LedgerInitData createLedgerInitSettings(LedgerInitProperties ledgerProps, + CryptoSetting cryptoSetting, ConsensusConfig consensusConfig, ParticipantProperties[] participants) { + // 创建初始化配置; + LedgerInitData initSetting = new LedgerInitData(); + initSetting.setLedgerSeed(ledgerProps.getLedgerSeed()); + initSetting.setCryptoSetting(cryptoSetting); + + initSetting.setConsensusParticipants(participants); + + initSetting.setCreatedTime(ledgerProps.getCreatedTime()); + + // 创建共识配置; + try { + byte[] consensusSettingsBytes = encodeConsensusSettings(consensusConfig.getProvider(), + consensusConfig.protocolSettings); + initSetting.setConsensusProvider(consensusConfig.getProvider().getName()); + initSetting.setConsensusSettings(consensusSettingsBytes); + } catch (Exception e) { + throw new LedgerInitException("Create default consensus config failed! --" + e.getMessage(), e); + } + + return initSetting; + } + + public static byte[] encodeConsensusSettings(ConsensusProvider consensusProvider, + ConsensusSettings consensusSettings) { + return consensusProvider.getSettingsFactory().getConsensusSettingsEncoder().encode(consensusSettings); + } + + /** + * 解析参与方列表; + * + * @param ledgerInitProps + * @return + */ + private static ParticipantProperties[] resolveParticipants(LedgerInitProperties ledgerInitProps) { + List partiList = ledgerInitProps.getConsensusParticipants(); + ParticipantProperties[] parties = new ParticipantProperties[partiList.size()]; + parties = partiList.toArray(parties); + ParticipantProperties[] orderedParties = sortAndVerify(parties); + + return orderedParties; + } + + /** + * 对参与者列表按照 id 进行升序排列,并校验id是否从 1 开始且没有跳跃; + * + * @param parties + * @return + */ + private static ParticipantProperties[] sortAndVerify(ParticipantProperties[] parties) { + Arrays.sort(parties, new Comparator() { + @Override + public int compare(ParticipantProperties o1, ParticipantProperties o2) { + return o1.getId() - o2.getId(); + } + }); + for (int i = 0; i < parties.length; i++) { + if (parties[i].getId() != i) { + throw new LedgerInitException( + "The ids of participants are not match their positions in the participant-list!"); + } + } + return parties; + } + + public static class ConsensusConfig { + + private ConsensusProvider provider; + + private ConsensusSettings protocolSettings; + + public ConsensusSettings getProtocolSettings() { + return protocolSettings; + } + + public void setProtocolSettings(ConsensusSettings protocolSettings) { + this.protocolSettings = protocolSettings; + } + + public ConsensusProvider getProvider() { + return provider; + } + + public void setProvider(ConsensusProvider provider) { + this.provider = provider; + } + } +} diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitConsensusService.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitConsensusService.java index d9699560..46ae01b5 100644 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitConsensusService.java +++ b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitConsensusService.java @@ -2,7 +2,7 @@ package com.jd.blockchain.tools.initializer.web; import com.jd.blockchain.crypto.SignatureDigest; import com.jd.blockchain.ledger.core.LedgerInitDecision; -import com.jd.blockchain.ledger.core.LedgerInitPermission; +import com.jd.blockchain.ledger.core.LedgerInitProposal; import com.jd.blockchain.utils.http.HttpAction; import com.jd.blockchain.utils.http.HttpMethod; import com.jd.blockchain.utils.http.HttpService; @@ -21,7 +21,7 @@ public interface LedgerInitConsensusService { * 请求者的私钥对 “id” + “账本种子” 做出的签名;只有签名合法且参与者是初始化配置中的参与方才能获得有效返回,否则将被拒绝; */ @HttpAction(path = "/legerinit/permission/{requesterId}", method = HttpMethod.POST, contentType = LedgerInitMessageConverter.CONTENT_TYPE_VALUE, responseConverter = PermissionResponseConverter.class) - LedgerInitPermission requestPermission(@PathParam(name = "requesterId") int requesterId, + LedgerInitProposal requestPermission(@PathParam(name = "requesterId") int requesterId, @RequestBody(converter = SignatureDigestRequestBodyConverter.class) SignatureDigest signature); /** 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 5658f9f6..6361d6a1 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 @@ -17,8 +17,8 @@ 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.LedgerInitPermission; -import com.jd.blockchain.ledger.core.LedgerInitPermissionData; +import com.jd.blockchain.ledger.core.LedgerInitProposal; +import com.jd.blockchain.ledger.core.LedgerInitProposalData; import com.jd.blockchain.utils.io.BytesUtils; /** @@ -38,10 +38,10 @@ public class LedgerInitMessageConverter implements HttpMessageConverter private static final Map, Class> SUPPORTED_CONTRACT_TYPES = new HashMap<>(); static { - DataContractRegistry.register(LedgerInitPermission.class); + DataContractRegistry.register(LedgerInitProposal.class); DataContractRegistry.register(LedgerInitDecision.class); - SUPPORTED_CONTRACT_TYPES.put(LedgerInitPermission.class, LedgerInitPermissionData.class); + SUPPORTED_CONTRACT_TYPES.put(LedgerInitProposal.class, LedgerInitProposalData.class); SUPPORTED_CONTRACT_TYPES.put(LedgerInitDecision.class, LedgerInitDecisionData.class); // SUPPORTED_CONTRACT_TYPES.add(LedgerInitResponse.class); diff --git a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitializeWebController.java b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitializeWebController.java index 116a381a..87ffc108 100644 --- a/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitializeWebController.java +++ b/source/tools/tools-initializer/src/main/java/com/jd/blockchain/tools/initializer/web/LedgerInitializeWebController.java @@ -3,14 +3,11 @@ package com.jd.blockchain.tools.initializer.web; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; -import java.util.Comparator; import java.util.List; -import java.util.Properties; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import com.jd.blockchain.transaction.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; @@ -19,47 +16,31 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.jd.blockchain.binaryproto.DataContractRegistry; -import com.jd.blockchain.consensus.ConsensusProvider; -import com.jd.blockchain.consensus.ConsensusProviders; -import com.jd.blockchain.consensus.ConsensusSettings; import com.jd.blockchain.crypto.Crypto; -import com.jd.blockchain.crypto.CryptoProvider; import com.jd.blockchain.crypto.HashDigest; import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.SignatureDigest; import com.jd.blockchain.crypto.SignatureFunction; -import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; -import com.jd.blockchain.crypto.service.sm.SMCryptoService; -import com.jd.blockchain.ledger.BlockchainIdentity; -import com.jd.blockchain.ledger.BlockchainIdentityData; -import com.jd.blockchain.ledger.CryptoSetting; -import com.jd.blockchain.ledger.LedgerBlock; -import com.jd.blockchain.ledger.LedgerInitSetting; -import com.jd.blockchain.ledger.Operation; +import com.jd.blockchain.ledger.DigitalSignature; +import com.jd.blockchain.ledger.LedgerInitException; +import com.jd.blockchain.ledger.LedgerInitProperties; +import com.jd.blockchain.ledger.LedgerInitProperties.ParticipantProperties; import com.jd.blockchain.ledger.ParticipantNode; -import com.jd.blockchain.ledger.TransactionBuilder; import com.jd.blockchain.ledger.TransactionContent; import com.jd.blockchain.ledger.TransactionRequest; -import com.jd.blockchain.ledger.TransactionState; -import com.jd.blockchain.ledger.UserRegisterOperation; -import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.LedgerEditor; import com.jd.blockchain.ledger.core.LedgerInitDecision; -import com.jd.blockchain.ledger.core.LedgerInitPermission; -import com.jd.blockchain.ledger.core.LedgerInitPermissionData; -import com.jd.blockchain.ledger.core.LedgerManage; -import com.jd.blockchain.ledger.core.LedgerTransactionContext; +import com.jd.blockchain.ledger.core.LedgerInitProposal; +import com.jd.blockchain.ledger.core.LedgerInitProposalData; +import com.jd.blockchain.ledger.core.LedgerInitializer; import com.jd.blockchain.storage.service.DbConnection; import com.jd.blockchain.storage.service.DbConnectionFactory; import com.jd.blockchain.tools.initializer.DBConnectionConfig; import com.jd.blockchain.tools.initializer.InitializingStep; -import com.jd.blockchain.tools.initializer.LedgerInitException; import com.jd.blockchain.tools.initializer.LedgerInitProcess; -import com.jd.blockchain.tools.initializer.LedgerInitProperties; -import com.jd.blockchain.tools.initializer.LedgerInitProperties.ConsensusParticipantConfig; import com.jd.blockchain.tools.initializer.Prompter; -import com.jd.blockchain.utils.Bytes; +import com.jd.blockchain.transaction.DigitalSignatureBlob; +import com.jd.blockchain.transaction.SignatureUtils; import com.jd.blockchain.utils.concurrent.InvocationResult; import com.jd.blockchain.utils.io.BytesUtils; import com.jd.blockchain.utils.net.NetworkAddress; @@ -77,42 +58,30 @@ public class LedgerInitializeWebController implements LedgerInitProcess, LedgerI DataContractRegistry.register(TransactionRequest.class); } - private static final String[] SUPPORTED_PROVIDERS = { ClassicCryptoService.class.getName(), - SMCryptoService.class.getName() }; - private static final String DEFAULT_SIGN_ALGORITHM = "ED25519"; private final SignatureFunction SIGN_FUNC; - private volatile LedgerInitPermission localPermission; + private volatile LedgerInitConfiguration ledgerInitConfig; - private TransactionContent initTxContent; + private volatile LedgerInitializer initializer; - private volatile int currentId = -1; + private volatile LedgerInitProposal localPermission; - private volatile LedgerInitSetting ledgerInitSetting; + private volatile int currentId = -1; - private volatile LedgerInitPermission[] permissions; + private volatile LedgerInitProposal[] permissions; private volatile NetworkAddress[] initializerAddresses; private volatile Prompter prompter; - private volatile ConsensusProvider consensusProvider; - - private volatile LedgerBlock genesisBlock; - private volatile LedgerInitDecision localDecision; private volatile DecisionResultHandle[] decisions; private volatile DbConnection dbConn; - private volatile LedgerEditor ledgerEditor; - - @Autowired - private LedgerManage ledgerManager; - @Autowired private DbConnectionFactory dbConnFactory; @@ -123,11 +92,10 @@ public class LedgerInitializeWebController implements LedgerInitProcess, LedgerI this.SIGN_FUNC = Crypto.getSignatureFunction(DEFAULT_SIGN_ALGORITHM); } - public LedgerInitializeWebController(LedgerManage ledgerManager, DbConnectionFactory dbConnFactory, + public LedgerInitializeWebController(DbConnectionFactory dbConnFactory, InitConsensusServiceFactory initCsServiceFactory) { this.SIGN_FUNC = Crypto.getSignatureFunction(DEFAULT_SIGN_ALGORITHM); - this.ledgerManager = ledgerManager; this.dbConnFactory = dbConnFactory; this.initCsServiceFactory = initCsServiceFactory; } @@ -137,10 +105,10 @@ public class LedgerInitializeWebController implements LedgerInitProcess, LedgerI } public TransactionContent getInitTxContent() { - return initTxContent; + return initializer.getTransactionContent(); } - public LedgerInitPermission getLocalPermission() { + public LedgerInitProposal getLocalPermission() { return localPermission; } @@ -152,40 +120,36 @@ public class LedgerInitializeWebController implements LedgerInitProcess, LedgerI this.prompter = prompter; } -// private ConsensusProvider getConsensusProvider() { -// return consensusProvider; -// } - - private void setConsensusProvider(ConsensusProvider consensusProvider) { - this.consensusProvider = consensusProvider; - } - @Override public HashDigest initialize(int currentId, PrivKey privKey, LedgerInitProperties ledgerInitProps, DBConnectionConfig dbConnConfig, Prompter prompter) { - return initialize(currentId, privKey, ledgerInitProps, dbConnConfig, prompter, createDefaultCryptoSetting()); + LedgerInitConfiguration initConfig = LedgerInitConfiguration.create(ledgerInitProps); + return initialize(currentId, privKey, initConfig, dbConnConfig, prompter); } @Override - public HashDigest initialize(int currentId, PrivKey privKey, LedgerInitProperties ledgerInitProps, - DBConnectionConfig dbConnConfig, Prompter prompter, CryptoSetting cryptoSetting) { - - if (this.ledgerInitSetting != null) { + public HashDigest initialize(int currentId, PrivKey privKey, LedgerInitConfiguration initConfig, + DBConnectionConfig dbConnConfig, Prompter prompter) { + if (initConfig == null) { + throw new IllegalArgumentException("Ledger init configuration is null"); + } + if (this.ledgerInitConfig != null) { throw new IllegalStateException("ledger init process has already started."); } setPrompter(prompter); - Properties csProps = ledgerInitProps.getConsensusConfig(); - ConsensusProvider csProvider = ConsensusProviders.getProvider(ledgerInitProps.getConsensusProvider()); - ConsensusSettings csSettings = csProvider.getSettingsFactory() - .getConsensusSettingsBuilder() - .createSettings(csProps, ledgerInitProps.getConsensusParticipantNodes()); - setConsensusProvider(csProvider); +// Properties csProps = ledgerInitProps.getConsensusConfig(); +// ConsensusProvider csProvider = ConsensusProviders.getProvider(ledgerInitProps.getConsensusProvider()); +// ConsensusSettings csSettings = csProvider.getSettingsFactory().getConsensusSettingsBuilder() +// .createSettings(csProps, ledgerInitProps.getConsensusParticipantNodes()); +// setConsensusProvider(csProvider); prompter.info("Init settings and sign permision..."); - prepareLocalPermission(currentId, privKey, ledgerInitProps, csSettings, cryptoSetting); + this.ledgerInitConfig = initConfig; + + prepareLocalPermission(currentId, privKey, ledgerInitConfig); prompter.confirm(InitializingStep.PERMISSION_READY.toString(), "Ledger init permission has already prepared! Any key to continue..."); @@ -227,12 +191,11 @@ public class LedgerInitializeWebController implements LedgerInitProcess, LedgerI public LedgerInitDecision makeLocalDecision(PrivKey privKey) { // 生成账本; - this.ledgerEditor = ledgerManager.newLedger(this.ledgerInitSetting, dbConn.getStorageService()); - this.genesisBlock = initLedgerDataset(ledgerEditor); + initializer.prepareLedger(dbConn.getStorageService(), getNodesSignatures()); // 生成签名决定; - this.localDecision = makeDecision(currentId, genesisBlock.getHash(), privKey); - this.decisions = new DecisionResultHandle[this.ledgerInitSetting.getConsensusParticipants().length]; + this.localDecision = makeDecision(currentId, initializer.getLedgerHash(), privKey); + this.decisions = new DecisionResultHandle[ledgerInitConfig.getParticipantCount()]; for (int i = 0; i < decisions.length; i++) { // 参与者的 id 是依次递增的; this.decisions[i] = new DecisionResultHandle(i); @@ -242,6 +205,18 @@ public class LedgerInitializeWebController implements LedgerInitProcess, LedgerI return localDecision; } + private DigitalSignature[] getNodesSignatures() { + ParticipantNode[] parties = this.ledgerInitConfig.getParticipants(); + DigitalSignature[] signatures = new DigitalSignature[parties.length]; + for (int i = 0; i < parties.length; i++) { + PubKey pubKey = parties[i].getPubKey(); + SignatureDigest signDigest = this.permissions[i].getTransactionSignature(); + signatures[i] = new DigitalSignatureBlob(pubKey, signDigest); + } + + return signatures; + } + public HashDigest consensusDecisions(PrivKey privKey) { // 获取其它参与方的账本生成结果; boolean allDecided = startRequestDecisions(privKey, prompter); @@ -249,13 +224,13 @@ public class LedgerInitializeWebController implements LedgerInitProcess, LedgerI prompter.error( "Rollback ledger initialization because of not all nodes make same decision! --[Current Participant=%s]", currentId); - ledgerEditor.cancel(); + initializer.cancel(); return null; } // 执行提交提交; - ledgerEditor.commit(); - return genesisBlock.getHash(); + initializer.commit(); + return initializer.getLedgerHash(); } public void closeDb() { @@ -306,87 +281,57 @@ public class LedgerInitializeWebController implements LedgerInitProcess, LedgerI return allPermitted; } - public CryptoSetting createDefaultCryptoSetting() { - CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length]; - for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) { - supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]); - } - CryptoConfig defCryptoSetting = new CryptoConfig(); - defCryptoSetting.setSupportedProviders(supportedProviders); - defCryptoSetting.setAutoVerifyHash(true); - defCryptoSetting.setHashAlgorithm(Crypto.getAlgorithm("SHA256")); - - return defCryptoSetting; - } - - public LedgerInitPermission prepareLocalPermission(int currentId, PrivKey privKey, LedgerInitProperties ledgerProps, - ConsensusSettings consensusProps) { - CryptoSetting defCryptoSetting = createDefaultCryptoSetting(); - return prepareLocalPermission(currentId, privKey, ledgerProps, consensusProps, defCryptoSetting); +// public CryptoSetting createDefaultCryptoSetting() { +// CryptoProvider[] supportedProviders = new CryptoProvider[SUPPORTED_PROVIDERS.length]; +// for (int i = 0; i < SUPPORTED_PROVIDERS.length; i++) { +// supportedProviders[i] = Crypto.getProvider(SUPPORTED_PROVIDERS[i]); +// } +// CryptoConfig defCryptoSetting = new CryptoConfig(); +// defCryptoSetting.setSupportedProviders(supportedProviders); +// defCryptoSetting.setAutoVerifyHash(true); +// defCryptoSetting.setHashAlgorithm(Crypto.getAlgorithm("SHA256")); +// +// return defCryptoSetting; +// } +// + public LedgerInitProposal prepareLocalPermission(int currentId, PrivKey privKey, + LedgerInitProperties ledgerInitProps) { + LedgerInitConfiguration ledgerInitConfiguration = LedgerInitConfiguration.create(ledgerInitProps); + return prepareLocalPermission(currentId, privKey, ledgerInitConfiguration); } - public LedgerInitPermission prepareLocalPermission(int currentId, PrivKey privKey, LedgerInitProperties ledgerProps, - ConsensusSettings csSettings, CryptoSetting cryptoSetting) { + public LedgerInitProposal prepareLocalPermission(int currentId, PrivKey privKey, + LedgerInitConfiguration ledgerInitConfig) { // 创建初始化配置; - LedgerInitSettingData initSetting = new LedgerInitSettingData(); - initSetting.setLedgerSeed(ledgerProps.getLedgerSeed()); - initSetting.setCryptoSetting(cryptoSetting); - - List partiList = ledgerProps.getConsensusParticipants(); - ConsensusParticipantConfig[] parties = new ConsensusParticipantConfig[partiList.size()]; - parties = partiList.toArray(parties); -// ConsensusParticipantConfig[] parties = partiList.toArray(new ConsensusParticipantConfig[partiList.size()]); - ConsensusParticipantConfig[] orderedParties = sortAndVerify(parties); - initSetting.setConsensusParticipants(orderedParties); - initSetting.setCreatedTime(ledgerProps.getCreatedTime()); - - // 创建默认的共识配置; - try { - // ConsensusConfig csConfig = new ConsensusConfig(); - byte[] csSettingBytes = consensusProvider.getSettingsFactory().getConsensusSettingsEncoder() - .encode(csSettings); - initSetting.setConsensusProvider(consensusProvider.getName()); - initSetting.setConsensusSettings(new Bytes(csSettingBytes)); - } catch (Exception e) { - throw new LedgerInitException("Create default consensus config failed! --" + e.getMessage(), e); - } - - if (currentId < 0 || currentId >= orderedParties.length) { + ParticipantProperties[] participants = ledgerInitConfig.getParticipants(); + if (currentId < 0 || currentId >= participants.length) { throw new LedgerInitException("Your id is out of bound of participant list!"); } this.currentId = currentId; - this.ledgerInitSetting = initSetting; // 校验当前的公钥、私钥是否匹配; byte[] testBytes = BytesUtils.toBytes(currentId); SignatureDigest testSign = SIGN_FUNC.sign(privKey, testBytes); - PubKey myPubKey = orderedParties[currentId].getPubKey(); + PubKey myPubKey = participants[currentId].getPubKey(); if (!SIGN_FUNC.verify(testSign, myPubKey, testBytes)) { throw new LedgerInitException("Your pub-key specified in the init-settings isn't match your priv-key!"); } - this.initializerAddresses = new NetworkAddress[orderedParties.length]; + this.initializerAddresses = new NetworkAddress[participants.length]; // 记录每个参与方的账本初始化服务地址; - for (int i = 0; i < orderedParties.length; i++) { - initializerAddresses[i] = orderedParties[i].getInitializerAddress(); + for (int i = 0; i < participants.length; i++) { + initializerAddresses[i] = participants[i].getInitializerAddress(); } - // 生成初始化交易,并签署许可; - TransactionBuilder initTxBuilder = new TxBuilder(null);// 账本初始化交易的账本 hash 为 null; - initTxBuilder.ledgers().create(initSetting); - for (ParticipantNode p : initSetting.getConsensusParticipants()) { - // TODO:暂时只支持注册用户的初始化操作; - BlockchainIdentity superUserId = new BlockchainIdentityData(p.getPubKey()); - initTxBuilder.users().register(superUserId); - } - // 账本初始化配置声明的创建时间来初始化交易时间戳;注:不能用本地时间,因为共识节点之间的本地时间系统不一致; - this.initTxContent = initTxBuilder.prepareContent(initSetting.getCreatedTime()); + // 初始化账本; + this.initializer = LedgerInitializer.create(ledgerInitConfig.getLedgerSettings(), + ledgerInitConfig.getSecuritySettings()); // 对初始交易签名,生成当前参与者的账本初始化许可; - SignatureDigest permissionSign = SignatureUtils.sign(initTxContent, privKey); - LedgerInitPermissionData permission = new LedgerInitPermissionData(currentId, permissionSign); + SignatureDigest permissionSign = initializer.signTransaction(privKey); + LedgerInitProposalData permission = new LedgerInitProposalData(currentId, permissionSign); this.currentId = currentId; - this.permissions = new LedgerInitPermission[initSetting.getConsensusParticipants().length]; + this.permissions = new LedgerInitProposal[ledgerInitConfig.getParticipantCount()]; this.permissions[currentId] = permission; this.localPermission = permission; @@ -405,33 +350,6 @@ public class LedgerInitializeWebController implements LedgerInitProcess, LedgerI return decision; } - private LedgerBlock initLedgerDataset(LedgerEditor ledgerEditor) { - // 初始化时,自动将参与方注册为账本的用户; - TxRequestBuilder txReqBuilder = new TxRequestBuilder(this.initTxContent); - ParticipantNode[] parties = this.ledgerInitSetting.getConsensusParticipants(); - for (int i = 0; i < parties.length; i++) { - PubKey pubKey = parties[i].getPubKey(); - SignatureDigest signDigest = this.permissions[i].getTransactionSignature(); - DigitalSignatureBlob digitalSignature = new DigitalSignatureBlob(pubKey, signDigest); - txReqBuilder.addNodeSignature(digitalSignature); - } - TransactionRequest txRequest = txReqBuilder.buildRequest(); - - LedgerTransactionContext txCtx = ledgerEditor.newTransaction(txRequest); - Operation[] ops = txRequest.getTransactionContent().getOperations(); - // 注册用户; 注:第一个操作是 LedgerInitOperation; - // TODO:暂时只支持注册用户的初始化操作; - for (int i = 1; i < ops.length; i++) { - UserRegisterOperation userRegOP = (UserRegisterOperation) ops[i]; - txCtx.getDataSet().getUserAccountSet().register(userRegOP.getUserID().getAddress(), - userRegOP.getUserID().getPubKey()); - } - - txCtx.commit(TransactionState.SUCCESS, null); - - return ledgerEditor.prepare(); - } - /** * 请求所有其它参与方的账本创建许可; * @@ -441,7 +359,7 @@ public class LedgerInitializeWebController implements LedgerInitProcess, LedgerI private boolean startRequestPermissions(int currentId, PrivKey privKey) { SignatureDigest reqAuthSign = signPermissionRequest(currentId, privKey); - ParticipantNode[] participants = ledgerInitSetting.getConsensusParticipants(); + ParticipantNode[] participants = ledgerInitConfig.getParticipants(); // 异步请求结果列表;不包括已经获得许可的参与方; InvocationResult[] results = new InvocationResult[participants.length]; @@ -493,7 +411,7 @@ public class LedgerInitializeWebController implements LedgerInitProcess, LedgerI continue; } PubKey pubKey = participants[i].getPubKey(); - LedgerInitPermission permission = (LedgerInitPermission) results[i].getValue(); + LedgerInitProposal permission = (LedgerInitProposal) results[i].getValue(); if (permission.getParticipantId() != participants[i].getId()) { prompter.error("\r\nThe id of received permission isn't equal to it's participant ! --[Id=%s][name=%s]", participants[i].getAddress(), participants[i].getName()); @@ -501,7 +419,8 @@ public class LedgerInitializeWebController implements LedgerInitProcess, LedgerI continue; } - if (!SignatureUtils.verifySignature(this.initTxContent, permission.getTransactionSignature(), pubKey)) { + if (!SignatureUtils.verifySignature(initializer.getTransactionContent(), + permission.getTransactionSignature(), pubKey)) { prompter.error("Invalid permission from participant! --[Id=%s][name=%s]", participants[i].getAddress(), participants[i].getName()); allPermitted = false; @@ -521,7 +440,8 @@ public class LedgerInitializeWebController implements LedgerInitProcess, LedgerI } public SignatureDigest signPermissionRequest(int requesterId, PrivKey privKey) { - byte[] reqAuthBytes = BytesUtils.concat(BytesUtils.toBytes(requesterId), ledgerInitSetting.getLedgerSeed()); + byte[] reqAuthBytes = BytesUtils.concat(BytesUtils.toBytes(requesterId), + ledgerInitConfig.getLedgerSettings().getLedgerSeed()); SignatureDigest reqAuthSign = SIGN_FUNC.sign(privKey, reqAuthBytes); return reqAuthSign; } @@ -534,16 +454,16 @@ public class LedgerInitializeWebController implements LedgerInitProcess, LedgerI * @param latch * @return */ - private InvocationResult doRequestPermission(int targetId, SignatureDigest reqAuthSign, + private InvocationResult doRequestPermission(int targetId, SignatureDigest reqAuthSign, CountDownLatch latch) { - InvocationResult result = new InvocationResult<>(); + InvocationResult result = new InvocationResult<>(); try { LedgerInitConsensusService initConsensus = connectToParticipant(targetId); Thread thrd = new Thread(new Runnable() { @Override public void run() { try { - LedgerInitPermission permission = initConsensus.requestPermission(currentId, reqAuthSign); + LedgerInitProposal permission = initConsensus.requestPermission(currentId, reqAuthSign); result.setValue(permission); } catch (Exception e) { result.setError(e); @@ -561,13 +481,13 @@ public class LedgerInitializeWebController implements LedgerInitProcess, LedgerI @RequestMapping(path = "/legerinit/permission/{requesterId}", method = RequestMethod.POST, produces = LedgerInitMessageConverter.CONTENT_TYPE_VALUE, consumes = LedgerInitMessageConverter.CONTENT_TYPE_VALUE) @Override - public LedgerInitPermission requestPermission(@PathVariable(name = "requesterId") int requesterId, + public LedgerInitProposal requestPermission(@PathVariable(name = "requesterId") int requesterId, @RequestBody SignatureDigest signature) { if (requesterId == currentId) { throw new LedgerInitException("There is a id conflict!"); } int retry = 0; - while (currentId == -1 || ledgerInitSetting == null || localPermission == null) { + while (currentId == -1 || ledgerInitConfig == null || localPermission == null) { // 本地尚未完成初始化; if (retry < 30) { try { @@ -581,11 +501,12 @@ public class LedgerInitializeWebController implements LedgerInitProcess, LedgerI retry++; } - ParticipantNode[] participants = ledgerInitSetting.getConsensusParticipants(); + ParticipantNode[] participants = ledgerInitConfig.getParticipants(); if (requesterId < 0 || requesterId >= participants.length) { throw new LedgerInitException("The id of requester is out of the bound of participant list!"); } - byte[] requestCodeBytes = BytesUtils.concat(BytesUtils.toBytes(requesterId), ledgerInitSetting.getLedgerSeed()); + byte[] requestCodeBytes = BytesUtils.concat(BytesUtils.toBytes(requesterId), + ledgerInitConfig.getLedgerSettings().getLedgerSeed()); PubKey requesterPubKey = participants[requesterId].getPubKey(); if (!SIGN_FUNC.verify(signature, requesterPubKey, requestCodeBytes)) { throw new LedgerInitException("The requester signature is invalid!"); @@ -724,8 +645,7 @@ public class LedgerInitializeWebController implements LedgerInitProcess, LedgerI } // 检查签名; - PubKey targetPubKey = ledgerInitSetting.getConsensusParticipants()[targetDecision.getParticipantId()] - .getPubKey(); + PubKey targetPubKey = ledgerInitConfig.getParticipant(targetDecision.getParticipantId()).getPubKey(); byte[] deciBytes = getDecisionBytes(targetDecision.getParticipantId(), targetDecision.getLedgerHash()); if ((!SIGN_FUNC.verify(targetDecision.getSignature(), targetPubKey, deciBytes)) && resultHandle.getValue() == null) { @@ -748,7 +668,7 @@ public class LedgerInitializeWebController implements LedgerInitProcess, LedgerI String.format("Reject decision because of self-synchronization! --[Id=%s]", remoteId)); } - if (this.genesisBlock == null) { + if (this.initializer == null) { // 当前参与者尚未准备就绪,返回 null; prompter.info("Not ready for genesis block! --[RemoteId=%s][CurrentId=%s]", remoteId, currentId); return null; @@ -777,28 +697,6 @@ public class LedgerInitializeWebController implements LedgerInitProcess, LedgerI } } - /** - * 对参与者列表按照 id 进行升序排列,并校验id是否从 1 开始且没有跳跃; - * - * @param parties - * @return - */ - private ConsensusParticipantConfig[] sortAndVerify(ConsensusParticipantConfig[] parties) { - Arrays.sort(parties, new Comparator() { - @Override - public int compare(ConsensusParticipantConfig o1, ConsensusParticipantConfig o2) { - return o1.getId() - o2.getId(); - } - }); - for (int i = 0; i < parties.length; i++) { - if (parties[i].getId() != i) { - throw new LedgerInitException( - "The ids of participants are not match their positions in the participant-list!"); - } - } - return parties; - } - private static class DecisionResultHandle extends InvocationResult { private final int PARTICIPANT_ID; 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 ab5b0308..f291d6c9 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 @@ -3,8 +3,8 @@ package com.jd.blockchain.tools.initializer.web; import java.io.InputStream; import com.jd.blockchain.binaryproto.BinaryProtocol; -import com.jd.blockchain.ledger.core.LedgerInitPermissionData; -import com.jd.blockchain.tools.initializer.LedgerInitException; +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; diff --git a/source/tools/tools-initializer/src/test/java/test/com/jd/blockchain/tools/initializer/LedgerInitPropertiesTest.java b/source/tools/tools-initializer/src/test/java/test/com/jd/blockchain/tools/initializer/LedgerInitPropertiesTest.java deleted file mode 100644 index 3e0a004e..00000000 --- a/source/tools/tools-initializer/src/test/java/test/com/jd/blockchain/tools/initializer/LedgerInitPropertiesTest.java +++ /dev/null @@ -1,106 +0,0 @@ -package test.com.jd.blockchain.tools.initializer; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.io.InputStream; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.TimeZone; - -import org.junit.Test; -import org.springframework.core.io.ClassPathResource; - -import com.jd.blockchain.crypto.AddressEncoding; -import com.jd.blockchain.crypto.PubKey; -import com.jd.blockchain.tools.initializer.LedgerInitProperties; -import com.jd.blockchain.tools.initializer.LedgerInitProperties.ConsensusParticipantConfig; -import com.jd.blockchain.tools.keygen.KeyGenCommand; -import com.jd.blockchain.utils.codec.HexUtils; - -public class LedgerInitPropertiesTest { - - private static String expectedCreatedTimeStr = "2019-08-01 14:26:58.069+0800"; - - private static String expectedCreatedTimeStr1 = "2019-08-01 13:26:58.069+0700"; - - @Test - public void testTimeFormat() throws ParseException { - SimpleDateFormat timeFormat = new SimpleDateFormat(LedgerInitProperties.CREATED_TIME_FORMAT); -// timeFormat.setTimeZone(TimeZone.getTimeZone("GMT+08:00")); - TimeZone.setDefault(TimeZone.getTimeZone("GMT+08:00")); - - Date time = timeFormat.parse(expectedCreatedTimeStr); - String actualTimeStr = timeFormat.format(time); - assertEquals(expectedCreatedTimeStr, actualTimeStr); - - Date time1 = timeFormat.parse(expectedCreatedTimeStr1); - String actualTimeStr1 = timeFormat.format(time1); - assertEquals(expectedCreatedTimeStr, actualTimeStr1); - } - - @Test - public void testProperties() throws IOException, ParseException { - ClassPathResource ledgerInitSettingResource = new ClassPathResource("ledger.init"); - InputStream in = ledgerInitSettingResource.getInputStream(); - try { - LedgerInitProperties initProps = LedgerInitProperties.resolve(in); - assertEquals(4, initProps.getConsensusParticipantCount()); - String expectedLedgerSeed = "932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323ffe" - .replace("-", ""); - String actualLedgerSeed = HexUtils.encode(initProps.getLedgerSeed()); - assertEquals(expectedLedgerSeed, actualLedgerSeed); - - SimpleDateFormat timeFormat = new SimpleDateFormat(LedgerInitProperties.CREATED_TIME_FORMAT); - timeFormat.setTimeZone(TimeZone.getTimeZone("GMT+08:00")); - long expectedTs = timeFormat.parse(expectedCreatedTimeStr).getTime(); - assertEquals(expectedTs, initProps.getCreatedTime()); - - String createdTimeStr = timeFormat.format(new Date(initProps.getCreatedTime())); - assertEquals(expectedCreatedTimeStr, createdTimeStr); - - assertEquals("com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider", - initProps.getConsensusProvider()); - - String[] cryptoProviders = initProps.getCryptoProviders(); - assertEquals(2, cryptoProviders.length); - assertEquals("com.jd.blockchain.crypto.service.classic.ClassicCryptoService", cryptoProviders[0]); - assertEquals("com.jd.blockchain.crypto.service.sm.SMCryptoService", cryptoProviders[1]); - - ConsensusParticipantConfig part0 = initProps.getConsensusParticipant(0); - assertEquals("jd.com", part0.getName()); - PubKey pubKey0 = KeyGenCommand.decodePubKey("3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9"); - assertEquals(pubKey0, part0.getPubKey()); - assertEquals("127.0.0.1", part0.getInitializerAddress().getHost()); - assertEquals(8800, part0.getInitializerAddress().getPort()); - assertEquals(true, part0.getInitializerAddress().isSecure()); - - ConsensusParticipantConfig part1 = initProps.getConsensusParticipant(1); - assertEquals(false, part1.getInitializerAddress().isSecure()); - PubKey pubKey1 = KeyGenCommand.decodePubKey("3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX"); - assertEquals(pubKey1, part1.getPubKey()); - - ConsensusParticipantConfig part2 = initProps.getConsensusParticipant(2); - assertEquals("7VeRAr3dSbi1xatq11ZcF7sEPkaMmtZhV9shonGJWk9T4pLe", part2.getPubKey().toBase58()); - - } finally { - in.close(); - } - } - - @Test - public void testPubKeyAddress() { - String[] pubKeys = TestConsts.PUB_KEYS; - int index = 0; - for (String pubKeyStr : pubKeys) { - System.out.println("[" + index + "][配置] = " + pubKeyStr); - PubKey pubKey = KeyGenCommand.decodePubKey(pubKeyStr); - System.out.println("[" + index + "][公钥Base58] = " + pubKey.toBase58()); - System.out.println("[" + index + "][地址] = " + AddressEncoding.generateAddress(pubKey).toBase58()); - System.out.println("--------------------------------------------------------------------"); - index++; - } - } - -} diff --git a/source/tools/tools-initializer/src/test/resources/ledger-binding.conf b/source/tools/tools-initializer/src/test/resources/ledger-binding.conf index 99df03d0..82b1ba3d 100644 --- a/source/tools/tools-initializer/src/test/resources/ledger-binding.conf +++ b/source/tools/tools-initializer/src/test/resources/ledger-binding.conf @@ -6,9 +6,9 @@ j5kLUENMvcUooZjKfz2bEYU6zoK9DAqbdDDU8aZEZFR4qf #第1个账本[j5ptBmn67B2p3yki3ji1j2ZMjnJhrUvP4kFpGmcXgvrhmk]的配置; #账本的当前共识参与方的ID; -binding.j5ptBmn67B2p3yki3ji1j2ZMjnJhrUvP4kFpGmcXgvrhmk.name = Test-Ledger-01 +binding.j5ptBmn67B2p3yki3ji1j2ZMjnJhrUvP4kFpGmcXgvrhmk.name= PRODUCT-INFO binding.j5ptBmn67B2p3yki3ji1j2ZMjnJhrUvP4kFpGmcXgvrhmk.parti.address=1 -binding.j5ptBmn67B2p3yki3ji1j2ZMjnJhrUvP4kFpGmcXgvrhmk.parti.name=parti-1 +binding.j5ptBmn67B2p3yki3ji1j2ZMjnJhrUvP4kFpGmcXgvrhmk.parti.name=PARTI-01 #账本的当前共识参与方的私钥文件的保存路径; binding.j5ptBmn67B2p3yki3ji1j2ZMjnJhrUvP4kFpGmcXgvrhmk.parti.pk-path=keys/jd-com.priv #账本的当前共识参与方的私钥内容(Base58编码);如果指定了,优先选用此属性,其次是 pk-path 属性; @@ -23,9 +23,9 @@ binding.j5ptBmn67B2p3yki3ji1j2ZMjnJhrUvP4kFpGmcXgvrhmk.db.pwd=kksfweffj #第2个账本[j5kLUENMvcUooZjKfz2bEYU6zoK9DAqbdDDU8aZEZFR4qf]的配置; #账本的当前共识参与方的ID; -binding.j5kLUENMvcUooZjKfz2bEYU6zoK9DAqbdDDU8aZEZFR4qf.name=Test-Ledger-02 +binding.j5kLUENMvcUooZjKfz2bEYU6zoK9DAqbdDDU8aZEZFR4qf.name= BASIC-INFO binding.j5kLUENMvcUooZjKfz2bEYU6zoK9DAqbdDDU8aZEZFR4qf.parti.address=2 -binding.j5kLUENMvcUooZjKfz2bEYU6zoK9DAqbdDDU8aZEZFR4qf.parti.name=parti-2 +binding.j5kLUENMvcUooZjKfz2bEYU6zoK9DAqbdDDU8aZEZFR4qf.parti.name=PARTI-02 #账本的当前共识参与方的私钥文件的保存路径; binding.j5kLUENMvcUooZjKfz2bEYU6zoK9DAqbdDDU8aZEZFR4qf.parti.pk-path=keys/jd-com-1.priv #账本的当前共识参与方的私钥内容(Base58编码);如果指定了,优先选用此属性,其次是 pk-path 属性; diff --git a/source/tools/tools-initializer/src/test/resources/ledger.init b/source/tools/tools-initializer/src/test/resources/ledger.init index 2d574f93..ebbd8872 100644 --- a/source/tools/tools-initializer/src/test/resources/ledger.init +++ b/source/tools/tools-initializer/src/test/resources/ledger.init @@ -5,9 +5,52 @@ ledger.seed=932dfe23-fe23232f-283f32fa-dd32aa76-8322ca2f-56236cda-7136b322-cb323 #账本的描述名称;此属性不参与共识,仅仅在当前参与方的本地节点用于描述用途; ledger.name=test -#声明的账本创建时间;格式为 “yyyy-MM-dd HH:mm:ss.SSSZ”,表示”年-月-日 时:分:秒:毫秒时区“;例如:“2019-08-01 14:26:58.069+0800”,其中,+0800 表示时区是东8区 +#声明账本的创建时间;格式为 “yyyy-MM-dd HH:mm:ss.SSSZ”,表示”年-月-日 时:分:秒:毫秒时区“;例如:“2019-08-01 14:26:58.069+0800”,其中,+0800 表示时区是东8区 created-time=2019-08-01 14:26:58.069+0800 + +#----------------------------------------------- +# 初始的角色名称列表;可选项; +# 角色名称不区分大小写,最长不超过20个字符;多个角色名称之间用半角的逗点“,”分隔; +# 系统会预置一个默认角色“DEFAULT”,所有未指定角色的用户都以赋予该角色的权限;若初始化时未配置默认角色的权限,则为默认角色分配所有权限; +# +# 注:如果声明了角色,但未声明角色对应的权限清单,这会忽略该角色的初始化; +# +security.roles=DEFAULT, ADMIN, MANAGER, GUEST + +# 赋予角色的账本权限清单;可选项; +# 可选的权限如下; +# AUTHORIZE_ROLES, SET_CONSENSUS, SET_CRYPTO, REGISTER_PARTICIPANT, +# REGISTER_USER, REGISTER_DATA_ACCOUNT, REGISTER_CONTRACT, UPGRADE_CONTRACT, +# SET_USER_ATTRIBUTES, WRITE_DATA_ACCOUNT, +# APPROVE_TX, CONSENSUS_TX +# 多项权限之间用逗点“,”分隔; +# +security.role.DEFAULT.ledger-privileges=REGISTER_USER, REGISTER_DATA_ACCOUNT + +# 赋予角色的交易权限清单;可选项; +# 可选的权限如下; +# DIRECT_OPERATION, CONTRACT_OPERATION +# 多项权限之间用逗点“,”分隔; +# +security.role.DEFAULT.tx-privileges=DIRECT_OPERATION, CONTRACT_OPERATION + +# 其它角色的配置示例; +# 系统管理员角色:只能操作全局性的参数配置和用户注册,只能执行直接操作指令; +security.role.ADMIN.ledger-privileges=CONFIGURE_ROLES, AUTHORIZE_USER_ROLES, SET_CONSENSUS, SET_CRYPTO, REGISTER_PARTICIPANT, REGISTER_USER +security.role.ADMIN.tx-privileges=DIRECT_OPERATION + +# 业务主管角色:只能够执行账本数据相关的操作,包括注册用户、注册数据账户、注册合约、升级合约、写入数据等;能够执行直接操作指令和调用合约; +security.role.MANAGER.ledger-privileges=CONFIGURE_ROLES, AUTHORIZE_USER_ROLES, REGISTER_USER, REGISTER_DATA_ACCOUNT, REGISTER_CONTRACT, UPGRADE_CONTRACT, SET_USER_ATTRIBUTES, WRITE_DATA_ACCOUNT, +security.role.MANAGER.tx-privileges=DIRECT_OPERATION, CONTRACT_OPERATION + +# 访客角色:不具备任何的账本权限,只有数据读取的操作;也只能够通过调用合约来读取数据; +security.role.GUEST.ledger-privileges= +security.role.GUEST.tx-privileges=CONTRACT_OPERATION + + + +#----------------------------------------------- #共识服务提供者;必须; consensus.service-provider=com.jd.blockchain.consensus.bftsmart.BftsmartConsensusProvider @@ -28,6 +71,10 @@ cons_parti.0.name=jd.com cons_parti.0.pubkey-path=keys/jd-com.pub #第0个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; cons_parti.0.pubkey=3snPdw7i7PjVKiTH2VnXZu5H8QmNaSXpnk4ei533jFpuifyjS5zzH9 +#第0个参与方的角色清单;可选项; +cons_parti.0.roles=ADMIN, MANAGER +#第0个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; +cons_parti.0.roles-policy=UNION #第0个参与方的共识服务的主机地址; cons_parti.0.consensus.host=127.0.0.1 #第0个参与方的共识服务的端口; @@ -47,6 +94,10 @@ cons_parti.1.name=at.com cons_parti.1.pubkey-path=keys/at-com.pub #第1个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; cons_parti.1.pubkey=3snPdw7i7PajLB35tEau1kmixc6ZrjLXgxwKbkv5bHhP7nT5dhD9eX +#第1个参与方的角色清单;可选项; +cons_parti.1.roles=MANAGER +#第1个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; +cons_parti.1.roles-policy=UNION #第1个参与方的共识服务的主机地址; cons_parti.1.consensus.host=127.0.0.1 #第1个参与方的共识服务的端口; @@ -66,6 +117,10 @@ cons_parti.2.name=bt.com cons_parti.2.pubkey-path=classpath:keys/parti2.pub #第2个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; cons_parti.2.pubkey= +#第2个参与方的角色清单;可选项; +cons_parti.2.roles=MANAGER +#第2个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; +cons_parti.2.roles-policy=UNION #第2个参与方的共识服务的主机地址; cons_parti.2.consensus.host=127.0.0.1 #第2个参与方的共识服务的端口; @@ -85,6 +140,10 @@ cons_parti.3.name=xt.com cons_parti.3.pubkey-path=keys/xt-com.pub #第3个参与方的公钥内容(由keygen工具生成);此参数优先于 pubkey-path 参数; cons_parti.3.pubkey=3snPdw7i7PifPuRX7fu3jBjsb3rJRfDe9GtbDfvFJaJ4V4hHXQfhwk +#第3个参与方的角色清单;可选项; +cons_parti.3.roles=GUEST +#第3个参与方的角色权限策略,可选值有:UNION(并集),INTERSECT(交集);可选项; +cons_parti.3.roles-policy=INTERSECT #第3个参与方的共识服务的主机地址; cons_parti.3.consensus.host=127.0.0.1 #第3个参与方的共识服务的端口; diff --git a/source/tools/tools-keygen/src/main/java/com/jd/blockchain/tools/keygen/KeyGenCommand.java b/source/tools/tools-keygen/src/main/java/com/jd/blockchain/tools/keygen/KeyGenCommand.java index e0c63a0b..cd2df93c 100644 --- a/source/tools/tools-keygen/src/main/java/com/jd/blockchain/tools/keygen/KeyGenCommand.java +++ b/source/tools/tools-keygen/src/main/java/com/jd/blockchain/tools/keygen/KeyGenCommand.java @@ -1,15 +1,19 @@ package com.jd.blockchain.tools.keygen; +import static com.jd.blockchain.crypto.KeyGenUtils.decodePubKey; +import static com.jd.blockchain.crypto.KeyGenUtils.decryptedPrivKeyBytes; +import static com.jd.blockchain.crypto.KeyGenUtils.encodePrivKey; +import static com.jd.blockchain.crypto.KeyGenUtils.encodePubKey; +import static com.jd.blockchain.crypto.KeyGenUtils.readPassword; + import java.io.File; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; -import javax.crypto.SecretKey; - import com.jd.blockchain.crypto.AsymmetricKeypair; import com.jd.blockchain.crypto.Crypto; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.utils.ArgumentSet; @@ -17,18 +21,11 @@ import com.jd.blockchain.utils.ArgumentSet.ArgEntry; import com.jd.blockchain.utils.ArgumentSet.Setting; import com.jd.blockchain.utils.ConsoleUtils; import com.jd.blockchain.utils.codec.Base58Utils; -import com.jd.blockchain.utils.io.BytesUtils; import com.jd.blockchain.utils.io.FileUtils; -import com.jd.blockchain.utils.security.AESUtils; import com.jd.blockchain.utils.security.DecryptionException; -import com.jd.blockchain.utils.security.ShaUtils; public class KeyGenCommand { - public static final byte[] PUB_KEY_FILE_MAGICNUM = { (byte) 0xFF, 112, 117, 98 }; - - public static final byte[] PRIV_KEY_FILE_MAGICNUM = { (byte) 0x00, 112, 114, 118 }; - // 指定 -r 参数时为“读取模式”,显示密钥文件; -r 参数之后紧跟着指定要读取的公钥或者私钥文件的路径; private static final String READ_ARG = "-r"; @@ -172,34 +169,6 @@ public class KeyGenCommand { } } - public static String encodePubKey(PubKey pubKey) { - byte[] pubKeyBytes = BytesUtils.concat(PUB_KEY_FILE_MAGICNUM, pubKey.toBytes()); - String base58PubKey = Base58Utils.encode(pubKeyBytes); - return base58PubKey; - } - - public static PubKey decodePubKey(String base58PubKey) { - byte[] keyBytes = Base58Utils.decode(base58PubKey); - return decodePubKey(keyBytes); - } - - public static String encodePrivKey(PrivKey privKey, String base58Pwd) { - byte[] pwdBytes = Base58Utils.decode(base58Pwd); - return encodePrivKey(privKey, pwdBytes); - } - - public static String encodePrivKey(PrivKey privKey, byte[] pwdBytes) { - byte[] encodedPrivKeyBytes = encryptPrivKey(privKey, pwdBytes); - String base58PrivKey = Base58Utils.encode(encodedPrivKeyBytes); - return base58PrivKey; - } - - public static byte[] encryptPrivKey(PrivKey privKey, byte[] pwdBytes) { - SecretKey userKey = AESUtils.generateKey128(pwdBytes); - byte[] encryptedPrivKeyBytes = AESUtils.encrypt(privKey.toBytes(), userKey); - return BytesUtils.concat(PRIV_KEY_FILE_MAGICNUM, encryptedPrivKeyBytes); - } - /** * 读取密钥;
* 如果是私钥,则需要输入密码; @@ -209,10 +178,10 @@ public class KeyGenCommand { public static void readKey(String keyFile, boolean decrypting) { String base58KeyString = FileUtils.readText(keyFile); byte[] keyBytes = Base58Utils.decode(base58KeyString); - if (BytesUtils.startsWith(keyBytes, PUB_KEY_FILE_MAGICNUM)) { + if (KeyGenUtils.isPubKeyBytes(keyBytes)) { if (decrypting) { // Try reading pubKey; - PubKey pubKey = doDecodePubKeyBytes(keyBytes); + PubKey pubKey = decodePubKey(keyBytes); ConsoleUtils.info( "======================== pub key ========================\r\n" + "[%s]\r\n" + "Raw:[%s][%s]\r\n", @@ -222,7 +191,7 @@ public class KeyGenCommand { base58KeyString); } return; - } else if (BytesUtils.startsWith(keyBytes, PRIV_KEY_FILE_MAGICNUM)) { + } else if (KeyGenUtils.isPrivKeyBytes(keyBytes)) { // Try reading privKye; try { if (decrypting) { @@ -246,119 +215,4 @@ public class KeyGenCommand { } } - private static PubKey doDecodePubKeyBytes(byte[] encodedPubKeyBytes) { - byte[] pubKeyBytes = Arrays.copyOfRange(encodedPubKeyBytes, PUB_KEY_FILE_MAGICNUM.length, - encodedPubKeyBytes.length); - return new PubKey(pubKeyBytes); - } - - public static PrivKey decryptedPrivKeyBytes(byte[] encodedPrivKeyBytes, byte[] pwdBytes) { - // Read privKye; - SecretKey userKey = AESUtils.generateKey128(pwdBytes); - byte[] encryptedKeyBytes = Arrays.copyOfRange(encodedPrivKeyBytes, PRIV_KEY_FILE_MAGICNUM.length, - encodedPrivKeyBytes.length); - try { - byte[] plainKeyBytes = AESUtils.decrypt(encryptedKeyBytes, userKey); - return new PrivKey(plainKeyBytes); - } catch (DecryptionException e) { - throw new DecryptionException("Invalid password!", e); - } - } - - public static PubKey readPubKey(String keyFile) { - String base58KeyString = FileUtils.readText(keyFile); - return decodePubKey(base58KeyString); - } - - public static PubKey decodePubKey(byte[] encodedPubKeyBytes) { - if (BytesUtils.startsWith(encodedPubKeyBytes, PUB_KEY_FILE_MAGICNUM)) { - // Read pubKey; - return doDecodePubKeyBytes(encodedPubKeyBytes); - } - - throw new IllegalArgumentException("The specified bytes is not valid PubKey generated by the KeyGen tool!"); - } - - /** - * 从控制台读取加密口令,以二进制数组形式返回原始口令的一次SHA256的结果; - * - * @return - */ - public static byte[] readPassword() { - byte[] pwdBytes = ConsoleUtils.readPassword(); - return ShaUtils.hash_256(pwdBytes); - } - - /** - * 对指定的原始密码进行编码生成用于加解密的密码; - * - * @param rawPassword - * @return - */ - public static byte[] encodePassword(String rawPassword) { - byte[] pwdBytes = BytesUtils.toBytes(rawPassword, "UTF-8"); - return ShaUtils.hash_256(pwdBytes); - } - - /** - * 对指定的原始密码进行编码生成用于加解密的密码; - * - * @param rawPassword - * @return - */ - public static String encodePasswordAsBase58(String rawPassword) { - return Base58Utils.encode(encodePassword(rawPassword)); - } - - /** - * 从控制台读取加密口令,以Base58字符串形式返回口令的一次SHA256的结果; - * - * @return - */ - public static String readPasswordString() { - return Base58Utils.encode(readPassword()); - } - - public static PrivKey readPrivKey(String keyFile, String base58Pwd) { - return readPrivKey(keyFile, Base58Utils.decode(base58Pwd)); - } - - /** - * 从文件读取私钥; - * - * @param keyFile - * @param pwdBytes - * @return - */ - public static PrivKey readPrivKey(String keyFile, byte[] pwdBytes) { - String base58KeyString = FileUtils.readText(keyFile); - byte[] keyBytes = Base58Utils.decode(base58KeyString); - if (!BytesUtils.startsWith(keyBytes, PRIV_KEY_FILE_MAGICNUM)) { - throw new IllegalArgumentException("The specified file is not a private key file!"); - } - return decryptedPrivKeyBytes(keyBytes, pwdBytes); - } - - public static PrivKey decodePrivKey(String base58Key, String base58Pwd) { - byte[] decryptedKey = Base58Utils.decode(base58Pwd); - return decodePrivKey(base58Key, decryptedKey); - } - - public static PrivKey decodePrivKey(String base58Key, byte[] pwdBytes) { - byte[] keyBytes = Base58Utils.decode(base58Key); - if (!BytesUtils.startsWith(keyBytes, PRIV_KEY_FILE_MAGICNUM)) { - throw new IllegalArgumentException("The specified file is not a private key file!"); - } - return decryptedPrivKeyBytes(keyBytes, pwdBytes); - } - - public static PrivKey decodePrivKeyWithRawPassword(String base58Key, String rawPassword) { - byte[] pwdBytes = encodePassword(rawPassword); - byte[] keyBytes = Base58Utils.decode(base58Key); - if (!BytesUtils.startsWith(keyBytes, PRIV_KEY_FILE_MAGICNUM)) { - throw new IllegalArgumentException("The specified file is not a private key file!"); - } - return decryptedPrivKeyBytes(keyBytes, pwdBytes); - } - } diff --git a/source/tools/tools-mocker/pom.xml b/source/tools/tools-mocker/pom.xml index 3b79b5b9..c78dcd31 100644 --- a/source/tools/tools-mocker/pom.xml +++ b/source/tools/tools-mocker/pom.xml @@ -39,7 +39,11 @@ crypto-classic ${project.version} - + + org.mockito + mockito-core + provided + diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/MockerLedgerInitializer.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/MockerLedgerInitializer.java index 0c2361fa..938e12bd 100644 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/MockerLedgerInitializer.java +++ b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/MockerLedgerInitializer.java @@ -1,29 +1,54 @@ package com.jd.blockchain.mocker; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.Random; + +import org.springframework.web.bind.annotation.RequestBody; + import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.consensus.ConsensusProvider; import com.jd.blockchain.consensus.ConsensusProviders; import com.jd.blockchain.consensus.ConsensusSettings; -import com.jd.blockchain.crypto.*; +import com.jd.blockchain.crypto.Crypto; +import com.jd.blockchain.crypto.CryptoProvider; +import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.crypto.PubKey; +import com.jd.blockchain.crypto.SignatureDigest; +import com.jd.blockchain.crypto.SignatureFunction; import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; import com.jd.blockchain.crypto.service.sm.SMCryptoService; -import com.jd.blockchain.ledger.*; -import com.jd.blockchain.ledger.core.*; -import com.jd.blockchain.ledger.core.impl.LedgerManager; +import com.jd.blockchain.ledger.CryptoSetting; +import com.jd.blockchain.ledger.DigitalSignature; +import com.jd.blockchain.ledger.LedgerInitException; +import com.jd.blockchain.ledger.LedgerInitProperties; +import com.jd.blockchain.ledger.LedgerInitProperties.ParticipantProperties; +import com.jd.blockchain.ledger.LedgerInitSetting; +import com.jd.blockchain.ledger.ParticipantNode; +import com.jd.blockchain.ledger.TransactionContent; +import com.jd.blockchain.ledger.TransactionRequest; +import com.jd.blockchain.ledger.core.CryptoConfig; +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.ledger.core.LedgerInitializer; +import com.jd.blockchain.ledger.core.LedgerManager; import com.jd.blockchain.storage.service.DbConnection; import com.jd.blockchain.storage.service.DbConnectionFactory; -import com.jd.blockchain.tools.initializer.*; -import com.jd.blockchain.tools.initializer.LedgerInitProperties.ConsensusParticipantConfig; +import com.jd.blockchain.tools.initializer.DBConnectionConfig; +import com.jd.blockchain.tools.initializer.LedgerInitProcess; +import com.jd.blockchain.tools.initializer.Prompter; +import com.jd.blockchain.tools.initializer.web.LedgerInitConfiguration; import com.jd.blockchain.tools.initializer.web.LedgerInitConsensusService; import com.jd.blockchain.tools.initializer.web.LedgerInitDecisionData; -import com.jd.blockchain.transaction.*; +import com.jd.blockchain.transaction.DigitalSignatureBlob; +import com.jd.blockchain.transaction.LedgerInitData; +import com.jd.blockchain.transaction.SignatureUtils; import com.jd.blockchain.utils.Bytes; import com.jd.blockchain.utils.concurrent.InvocationResult; import com.jd.blockchain.utils.io.BytesUtils; -import org.springframework.web.bind.annotation.*; - -import java.io.IOException; -import java.util.*; /** * 账本初始化控制器; @@ -37,21 +62,20 @@ public class MockerLedgerInitializer implements LedgerInitProcess, LedgerInitCon DataContractRegistry.register(TransactionRequest.class); } - private static final String[] SUPPORTED_PROVIDERS = { - ClassicCryptoService.class.getName(), + private static final String[] SUPPORTED_PROVIDERS = { ClassicCryptoService.class.getName(), SMCryptoService.class.getName() }; private static final String DEFAULT_SIGN_ALGORITHM = "ED25519"; private final SignatureFunction SIGN_FUNC; - private volatile LedgerInitPermission localPermission; + private volatile LedgerInitProposal localPermission; - private TransactionContent initTxContent; + private volatile LedgerInitializer initializer; private volatile int currentId = -1; - private volatile LedgerInitSetting ledgerInitSetting; + private volatile LedgerInitConfiguration ledgerInitConfig; // private volatile LedgerInitPermission[] permissions; // private volatile LedgerInitPermission permission; @@ -60,16 +84,12 @@ public class MockerLedgerInitializer implements LedgerInitProcess, LedgerInitCon private volatile ConsensusProvider consensusProvider; - private volatile LedgerBlock genesisBlock; - private volatile LedgerInitDecision localDecision; private volatile DecisionResultHandle[] decisions; private volatile DbConnection dbConn; - private volatile LedgerEditor ledgerEditor; - private LedgerManager ledgerManager; private DbConnectionFactory dbConnFactory; @@ -89,10 +109,10 @@ public class MockerLedgerInitializer implements LedgerInitProcess, LedgerInitCon } public TransactionContent getInitTxContent() { - return initTxContent; + return initializer.getTransactionContent(); } - public LedgerInitPermission getLocalPermission() { + public LedgerInitProposal getLocalPermission() { return localPermission; } @@ -111,25 +131,22 @@ public class MockerLedgerInitializer implements LedgerInitProcess, LedgerInitCon @Override public HashDigest initialize(int currentId, PrivKey privKey, LedgerInitProperties ledgerInitProps, DBConnectionConfig dbConnConfig, Prompter prompter) { - return initialize(currentId, privKey, ledgerInitProps, dbConnConfig, prompter, createDefaultCryptoSetting()); + LedgerInitConfiguration ledgerInitConfig = LedgerInitConfiguration.create(ledgerInitProps); + return initialize(currentId, privKey, ledgerInitConfig, dbConnConfig, prompter); } @Override - public synchronized HashDigest initialize(int currentId, PrivKey privKey, LedgerInitProperties ledgerInitProps, - DBConnectionConfig dbConnConfig, Prompter prompter, CryptoSetting cryptoSetting) { - - if (this.ledgerInitSetting != null) { + public synchronized HashDigest initialize(int currentId, PrivKey privKey, LedgerInitConfiguration ledgerInitProps, + DBConnectionConfig dbConnConfig, Prompter prompter) { + if (this.ledgerInitConfig != null) { throw new IllegalStateException("ledger init process has already started."); } setPrompter(prompter); - ConsensusProvider csProvider = ConsensusProviders.getProvider(ledgerInitProps.getConsensusProvider()); - setConsensusProvider(csProvider); - prompter.info("Init settings and sign permision..."); - prepareLocalPermission(currentId, privKey, ledgerInitProps, null, cryptoSetting); + prepareLocalProposal(currentId, privKey, ledgerInitProps); try { // 连接数据库; @@ -155,12 +172,13 @@ public class MockerLedgerInitializer implements LedgerInitProcess, LedgerInitCon public LedgerInitDecision makeLocalDecision(PrivKey privKey) { // 生成账本; - this.ledgerEditor = ledgerManager.newLedger(this.ledgerInitSetting, dbConn.getStorageService()); - this.genesisBlock = initLedgerDataset(ledgerEditor); +// this.ledgerEditor = ledgerManager.newLedger(this.ledgerInitSetting, dbConn.getStorageService()); +// this.genesisBlock = initLedgerDataset(ledgerEditor); + initializer.prepareLedger(dbConn.getStorageService(), getNodeSignatures()); // 生成签名决定; - this.localDecision = makeDecision(currentId, genesisBlock.getHash(), privKey); - this.decisions = new DecisionResultHandle[this.ledgerInitSetting.getConsensusParticipants().length]; + this.localDecision = makeDecision(currentId, initializer.getLedgerHash(), privKey); + this.decisions = new DecisionResultHandle[this.ledgerInitConfig.getParticipantCount()]; for (int i = 0; i < decisions.length; i++) { // 参与者的 id 是依次递增的; this.decisions[i] = new DecisionResultHandle(i); @@ -170,10 +188,19 @@ public class MockerLedgerInitializer implements LedgerInitProcess, LedgerInitCon return localDecision; } + private DigitalSignature getNodeSignatures() { + ParticipantNode parti = this.ledgerInitConfig.getParticipant(currentId); + PubKey pubKey = parti.getPubKey(); + SignatureDigest signDigest = this.localPermission.getTransactionSignature(); + DigitalSignatureBlob digitalSignature = new DigitalSignatureBlob(pubKey, signDigest); + + return digitalSignature; + } + public HashDigest consensusDecisions() { // 执行提交提交; - ledgerEditor.commit(); - return genesisBlock.getHash(); + initializer.commit(); + return initializer.getLedgerHash(); } public void closeDb() { @@ -201,55 +228,28 @@ public class MockerLedgerInitializer implements LedgerInitProcess, LedgerInitCon return defCryptoSetting; } - public LedgerInitPermission prepareLocalPermission(int currentId, PrivKey privKey, LedgerInitProperties ledgerProps, - ConsensusSettings csSettings, CryptoSetting cryptoSetting) { - // 创建初始化配置; - LedgerInitSettingData initSetting = new LedgerInitSettingData(); - initSetting.setLedgerSeed(ledgerProps.getLedgerSeed()); - initSetting.setCryptoSetting(cryptoSetting); + public LedgerInitProposal prepareLocalProposal(int currentId, PrivKey privKey, + LedgerInitConfiguration ledgerInitConfig) { - List partiList = ledgerProps.getConsensusParticipants(); - ConsensusParticipantConfig[] parties = partiList.toArray(new ConsensusParticipantConfig[partiList.size()]); - ConsensusParticipantConfig[] orderedParties = sortAndVerify(parties); - initSetting.setConsensusParticipants(orderedParties); - - // 创建默认的共识配置; - try { - byte[] csSettingBytes = new byte[1024]; - new Random().nextBytes(csSettingBytes); - - initSetting.setConsensusProvider(consensusProvider.getName()); - initSetting.setConsensusSettings(new Bytes(csSettingBytes)); - } catch (Exception e) { - throw new LedgerInitException("Create default consensus config failed! --" + e.getMessage(), e); - } - - if (currentId < 0 || currentId >= orderedParties.length) { + if (currentId < 0 || currentId >= ledgerInitConfig.getParticipantCount()) { throw new LedgerInitException("Your id is out of bound of participant list!"); } this.currentId = currentId; - this.ledgerInitSetting = initSetting; // 校验当前的公钥、私钥是否匹配; byte[] testBytes = BytesUtils.toBytes(currentId); SignatureDigest testSign = SIGN_FUNC.sign(privKey, testBytes); - PubKey myPubKey = orderedParties[currentId].getPubKey(); + PubKey myPubKey = ledgerInitConfig.getParticipant(currentId).getPubKey(); if (!SIGN_FUNC.verify(testSign, myPubKey, testBytes)) { throw new LedgerInitException("Your pub-key specified in the init-settings isn't match your priv-key!"); } - // 生成初始化交易,并签署许可; - TransactionBuilder initTxBuilder = new TxBuilder(null);// 账本初始化交易的账本 hash 为 null; - initTxBuilder.ledgers().create(initSetting); - for (ParticipantNode p : initSetting.getConsensusParticipants()) { - // TODO:暂时只支持注册用户的初始化操作; - BlockchainIdentity superUserId = new BlockchainIdentityData(p.getPubKey()); - initTxBuilder.users().register(superUserId); - } - this.initTxContent = initTxBuilder.prepareContent(); + // 初始化; + this.initializer = LedgerInitializer.create(ledgerInitConfig.getLedgerSettings(), + ledgerInitConfig.getSecuritySettings()); // 对初始交易签名,生成当前参与者的账本初始化许可; - SignatureDigest permissionSign = SignatureUtils.sign(initTxContent, privKey); - localPermission = new LedgerInitPermissionData(currentId, permissionSign); + SignatureDigest permissionSign = SignatureUtils.sign(initializer.getTransactionContent(), privKey); + localPermission = new LedgerInitProposalData(currentId, permissionSign); this.currentId = currentId; return localPermission; @@ -267,40 +267,40 @@ public class MockerLedgerInitializer implements LedgerInitProcess, LedgerInitCon return decision; } - private LedgerBlock initLedgerDataset(LedgerEditor ledgerEditor) { - // 初始化时,自动将参与方注册为账本的用户; - TxRequestBuilder txReqBuilder = new TxRequestBuilder(this.initTxContent); -// ParticipantNode[] parties = this.ledgerInitSetting.getConsensusParticipants(); - ParticipantNode parti = this.ledgerInitSetting.getConsensusParticipants()[currentId]; - - PubKey pubKey = parti.getPubKey(); - SignatureDigest signDigest = this.localPermission.getTransactionSignature(); - DigitalSignatureBlob digitalSignature = new DigitalSignatureBlob(pubKey, signDigest); - txReqBuilder.addNodeSignature(digitalSignature); - - TransactionRequest txRequest = txReqBuilder.buildRequest(); - - LedgerTransactionContext txCtx = ledgerEditor.newTransaction(txRequest); - Operation[] ops = txRequest.getTransactionContent().getOperations(); - // 注册用户; 注:第一个操作是 LedgerInitOperation; - // TODO:暂时只支持注册用户的初始化操作; - for (int i = 1; i < ops.length; i++) { - UserRegisterOperation userRegOP = (UserRegisterOperation) ops[i]; - txCtx.getDataSet().getUserAccountSet().register(userRegOP.getUserID().getAddress(), - userRegOP.getUserID().getPubKey()); - } - - txCtx.commit(TransactionState.SUCCESS, null); - - return ledgerEditor.prepare(); - } +// private LedgerBlock initLedgerDataset(LedgerEditor ledgerEditor) { +// // 初始化时,自动将参与方注册为账本的用户; +// TxRequestBuilder txReqBuilder = new TxRequestBuilder(this.initTxContent); +//// ParticipantNode[] parties = this.ledgerInitSetting.getConsensusParticipants(); +// ParticipantNode parti = this.ledgerInitSetting.getConsensusParticipants()[currentId]; +// +// PubKey pubKey = parti.getPubKey(); +// SignatureDigest signDigest = this.localPermission.getTransactionSignature(); +// DigitalSignatureBlob digitalSignature = new DigitalSignatureBlob(pubKey, signDigest); +// txReqBuilder.addNodeSignature(digitalSignature); +// +// TransactionRequest txRequest = txReqBuilder.buildRequest(); +// +// LedgerTransactionContext txCtx = ledgerEditor.newTransaction(txRequest); +// Operation[] ops = txRequest.getTransactionContent().getOperations(); +// // 注册用户; 注:第一个操作是 LedgerInitOperation; +// // TODO:暂时只支持注册用户的初始化操作; +// for (int i = 1; i < ops.length; i++) { +// UserRegisterOperation userRegOP = (UserRegisterOperation) ops[i]; +// txCtx.getDataset().getUserAccountSet().register(userRegOP.getUserID().getAddress(), +// userRegOP.getUserID().getPubKey()); +// } +// +// txCtx.commit(TransactionState.SUCCESS, null); +// +// return ledgerEditor.prepare(); +// } private byte[] getDecisionBytes(int participantId, HashDigest ledgerHash) { return BytesUtils.concat(BytesUtils.toBytes(participantId), ledgerHash.toBytes()); } @Override - public LedgerInitPermission requestPermission(int requesterId, SignatureDigest signature) { + public LedgerInitProposal requestPermission(int requesterId, SignatureDigest signature) { return localPermission; } @@ -315,7 +315,7 @@ public class MockerLedgerInitializer implements LedgerInitProcess, LedgerInitCon * @param parties * @return */ - private ConsensusParticipantConfig[] sortAndVerify(ConsensusParticipantConfig[] parties) { + private ParticipantProperties[] sortAndVerify(ParticipantProperties[] parties) { Arrays.sort(parties, (o1, o2) -> o1.getId() - o2.getId()); for (int i = 0; i < parties.length; i++) { if (parties[i].getId() != i) { diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/MockerNodeContext.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/MockerNodeContext.java index 312bcc45..7e916d16 100644 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/MockerNodeContext.java +++ b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/MockerNodeContext.java @@ -1,6 +1,8 @@ package com.jd.blockchain.mocker; import static java.lang.reflect.Proxy.newProxyInstance; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.when; import java.text.SimpleDateFormat; import java.util.Date; @@ -8,6 +10,8 @@ import java.util.HashMap; import java.util.Map; import java.util.Properties; +import org.mockito.Mockito; + import com.jd.blockchain.binaryproto.DataContract; import com.jd.blockchain.binaryproto.DataContractRegistry; import com.jd.blockchain.consensus.ClientIdentification; @@ -17,30 +21,63 @@ import com.jd.blockchain.consensus.action.ActionResponse; import com.jd.blockchain.crypto.Crypto; import com.jd.blockchain.crypto.CryptoProvider; import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.crypto.service.classic.ClassicAlgorithm; import com.jd.blockchain.crypto.service.classic.ClassicCryptoService; import com.jd.blockchain.crypto.service.sm.SMCryptoService; -import com.jd.blockchain.ledger.*; +import com.jd.blockchain.ledger.AccountHeader; +import com.jd.blockchain.ledger.BlockchainIdentity; +import com.jd.blockchain.ledger.BlockchainKeyGenerator; +import com.jd.blockchain.ledger.BlockchainKeypair; +import com.jd.blockchain.ledger.ContractCodeDeployOperation; +import com.jd.blockchain.ledger.ContractEventSendOperation; +import com.jd.blockchain.ledger.ContractInfo; +import com.jd.blockchain.ledger.DataAccountKVSetOperation; +import com.jd.blockchain.ledger.DataAccountRegisterOperation; +import com.jd.blockchain.ledger.EndpointRequest; +import com.jd.blockchain.ledger.KVDataEntry; +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.LedgerInitProperties; +import com.jd.blockchain.ledger.LedgerMetadata; +import com.jd.blockchain.ledger.LedgerPermission; +import com.jd.blockchain.ledger.LedgerTransaction; +import com.jd.blockchain.ledger.NodeRequest; +import com.jd.blockchain.ledger.Operation; +import com.jd.blockchain.ledger.OperationResult; +import com.jd.blockchain.ledger.ParticipantNode; +import com.jd.blockchain.ledger.TransactionContent; +import com.jd.blockchain.ledger.TransactionContentBody; +import com.jd.blockchain.ledger.TransactionPermission; +import com.jd.blockchain.ledger.TransactionRequest; +import com.jd.blockchain.ledger.TransactionRequestBuilder; +import com.jd.blockchain.ledger.TransactionResponse; +import com.jd.blockchain.ledger.TransactionState; +import com.jd.blockchain.ledger.UserInfo; +import com.jd.blockchain.ledger.UserRegisterOperation; import com.jd.blockchain.ledger.core.CryptoConfig; -import com.jd.blockchain.ledger.core.LedgerDataSet; +import com.jd.blockchain.ledger.core.DefaultOperationHandleRegisteration; +import com.jd.blockchain.ledger.core.LedgerDataQuery; import com.jd.blockchain.ledger.core.LedgerEditor; +import com.jd.blockchain.ledger.core.LedgerManager; +import com.jd.blockchain.ledger.core.LedgerQueryService; import com.jd.blockchain.ledger.core.LedgerRepository; -import com.jd.blockchain.ledger.core.impl.LedgerManager; -import com.jd.blockchain.ledger.core.impl.LedgerQueryService; -import com.jd.blockchain.ledger.core.impl.TransactionBatchProcessor; +import com.jd.blockchain.ledger.core.LedgerSecurityManager; +import com.jd.blockchain.ledger.core.SecurityPolicy; +import com.jd.blockchain.ledger.core.TransactionBatchProcessor; import com.jd.blockchain.mocker.config.MockerConstant; import com.jd.blockchain.mocker.config.PresetAnswerPrompter; import com.jd.blockchain.mocker.handler.MockerContractExeHandle; -import com.jd.blockchain.mocker.handler.MockerOperationHandleRegister; import com.jd.blockchain.mocker.proxy.ContractProxy; import com.jd.blockchain.service.TransactionBatchResultHandle; import com.jd.blockchain.storage.service.DbConnectionFactory; import com.jd.blockchain.storage.service.utils.MemoryDBConnFactory; import com.jd.blockchain.tools.initializer.DBConnectionConfig; -import com.jd.blockchain.tools.initializer.LedgerInitProperties; -import com.jd.blockchain.tools.keygen.KeyGenCommand; +import com.jd.blockchain.tools.initializer.web.LedgerInitConfiguration; import com.jd.blockchain.transaction.BlockchainQueryService; import com.jd.blockchain.transaction.TxBuilder; import com.jd.blockchain.utils.Bytes; @@ -56,7 +93,7 @@ public class MockerNodeContext implements BlockchainQueryService { private DbConnectionFactory dbConnFactory = new MemoryDBConnFactory(); - private MockerOperationHandleRegister opHandler = new MockerOperationHandleRegister(); + private DefaultOperationHandleRegisteration opHandler = new DefaultOperationHandleRegisteration(); private MockerContractExeHandle contractExeHandle = new MockerContractExeHandle(); @@ -97,6 +134,8 @@ public class MockerNodeContext implements BlockchainQueryService { DataContractRegistry.register(ClientIdentifications.class); DataContractRegistry.register(ClientIdentification.class); +// DataContractRegistry.register(LedgerAdminInfo.class); + ByteArrayObjectUtil.init(); } @@ -128,16 +167,16 @@ public class MockerNodeContext implements BlockchainQueryService { boolean isExist = false; // 通过公钥进行判断 for (Map.Entry entry : participants.entrySet()) { - String existPubKey = KeyGenCommand.encodePubKey(entry.getValue().getPubKey()); + String existPubKey = KeyGenUtils.encodePubKey(entry.getValue().getPubKey()); if (pubKeyString.equals(existPubKey)) { isExist = true; } } if (!isExist) { // 加入系统中 - PrivKey privKey = KeyGenCommand.decodePrivKeyWithRawPassword(MockerConstant.PRIVATE_KEYS[i], + PrivKey privKey = KeyGenUtils.decodePrivKeyWithRawPassword(MockerConstant.PRIVATE_KEYS[i], MockerConstant.PASSWORD); - PubKey pubKey = KeyGenCommand.decodePubKey(MockerConstant.PUBLIC_KEYS[i]); + PubKey pubKey = KeyGenUtils.decodePubKey(MockerConstant.PUBLIC_KEYS[i]); participants(new BlockchainKeypair(pubKey, privKey)); } if (participants.size() >= 4) { @@ -150,8 +189,11 @@ public class MockerNodeContext implements BlockchainQueryService { MockerLedgerInitializer mockLedgerInitializer = new MockerLedgerInitializer(dbConnFactory, ledgerManager); - ledgerHash = mockLedgerInitializer.initialize(0, defaultKeypair.getPrivKey(), ledgerInitProperties, - dbConnectionConfig, new PresetAnswerPrompter("N"), cryptoConfig()); + LedgerInitConfiguration initConfig = LedgerInitConfiguration.create(ledgerInitProperties); + initConfig.getLedgerSettings().setCryptoSetting(cryptoConfig()); + + ledgerHash = mockLedgerInitializer.initialize(0, defaultKeypair.getPrivKey(), initConfig, dbConnectionConfig, + new PresetAnswerPrompter("N")); ledgerRepository = registerLedger(ledgerHash, dbConnectionConfig); @@ -159,7 +201,7 @@ public class MockerNodeContext implements BlockchainQueryService { contractExeHandle.initLedger(ledgerManager, ledgerHash); - opHandler.registerHandler(contractExeHandle); + opHandler.registerHandle(contractExeHandle); return this; } @@ -247,6 +289,11 @@ public class MockerNodeContext implements BlockchainQueryService { return queryService.getLedger(ledgerHash); } + @Override + public LedgerAdminInfo getLedgerAdminInfo(HashDigest ledgerHash) { + return queryService.getLedgerAdminInfo(ledgerHash); + } + @Override public ParticipantNode[] getConsensusParticipants(HashDigest ledgerHash) { return queryService.getConsensusParticipants(ledgerHash); @@ -378,7 +425,7 @@ public class MockerNodeContext implements BlockchainQueryService { } @Override - public ContractInfo getContract(HashDigest ledgerHash, String address) { + public ContractInfo getContract(HashDigest ledgerHash, String address) { return queryService.getContract(ledgerHash, address); } @@ -407,12 +454,26 @@ public class MockerNodeContext implements BlockchainQueryService { return reqBuilder.buildRequest(); } + private static LedgerSecurityManager getSecurityManager() { + LedgerSecurityManager securityManager = Mockito.mock(LedgerSecurityManager.class); + + SecurityPolicy securityPolicy = Mockito.mock(SecurityPolicy.class); + when(securityPolicy.isEndpointEnable(any(LedgerPermission.class), any())).thenReturn(true); + when(securityPolicy.isEndpointEnable(any(TransactionPermission.class), any())).thenReturn(true); + when(securityPolicy.isNodeEnable(any(LedgerPermission.class), any())).thenReturn(true); + when(securityPolicy.isNodeEnable(any(TransactionPermission.class), any())).thenReturn(true); + + when(securityManager.createSecurityPolicy(any(), any())).thenReturn(securityPolicy); + + return securityManager; + } + public OperationResult[] txProcess(TransactionRequest txRequest) { LedgerEditor newEditor = ledgerRepository.createNextBlock(); LedgerBlock latestBlock = ledgerRepository.getLatestBlock(); - LedgerDataSet previousDataSet = ledgerRepository.getDataSet(latestBlock); - TransactionBatchProcessor txProc = new TransactionBatchProcessor(newEditor, previousDataSet, opHandler, - ledgerManager); + LedgerDataQuery previousDataSet = ledgerRepository.getDataSet(latestBlock); + TransactionBatchProcessor txProc = new TransactionBatchProcessor(getSecurityManager(), newEditor, + previousDataSet, opHandler, ledgerManager); TransactionResponse txResp = txProc.schedule(txRequest); TransactionBatchResultHandle handle = txProc.prepare(); handle.commit(); @@ -469,7 +530,7 @@ public class MockerNodeContext implements BlockchainQueryService { ledgerProp.put(partiPrefix + LedgerInitProperties.PART_NAME, name); ledgerProp.put(partiPrefix + LedgerInitProperties.PART_PUBKEY_PATH, ""); ledgerProp.put(partiPrefix + LedgerInitProperties.PART_PUBKEY, - KeyGenCommand.encodePubKey(keypair.getPubKey())); + KeyGenUtils.encodePubKey(keypair.getPubKey())); ledgerProp.put(partiPrefix + LedgerInitProperties.PART_INITIALIZER_HOST, MockerConstant.LOCAL_ADDRESS); ledgerProp.put(partiPrefix + LedgerInitProperties.PART_INITIALIZER_PORT, String.valueOf(MockerConstant.LEDGER_INIT_PORT_START + partiIndex * 10)); diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerContractExeHandle.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerContractExeHandle.java index cb26ac92..d278de13 100644 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerContractExeHandle.java +++ b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerContractExeHandle.java @@ -9,15 +9,22 @@ import com.jd.blockchain.contract.ContractException; import com.jd.blockchain.contract.EventProcessingAware; import com.jd.blockchain.contract.LedgerContext; import com.jd.blockchain.crypto.HashDigest; -import com.jd.blockchain.ledger.*; -import com.jd.blockchain.ledger.core.LedgerDataSet; +import com.jd.blockchain.ledger.BlockchainIdentity; +import com.jd.blockchain.ledger.BytesValue; +import com.jd.blockchain.ledger.BytesValueEncoding; +import com.jd.blockchain.ledger.BytesValueList; +import com.jd.blockchain.ledger.ContractEventSendOperation; +import com.jd.blockchain.ledger.Operation; +import com.jd.blockchain.ledger.TransactionRequest; +import com.jd.blockchain.ledger.core.LedgerDataQuery; +import com.jd.blockchain.ledger.core.LedgerDataset; +import com.jd.blockchain.ledger.core.LedgerManager; +import com.jd.blockchain.ledger.core.LedgerQueryService; import com.jd.blockchain.ledger.core.LedgerService; import com.jd.blockchain.ledger.core.OperationHandle; -import com.jd.blockchain.ledger.core.TransactionRequestContext; -import com.jd.blockchain.ledger.core.impl.LedgerManager; -import com.jd.blockchain.ledger.core.impl.LedgerQueryService; -import com.jd.blockchain.ledger.core.impl.OperationHandleContext; -import com.jd.blockchain.ledger.core.impl.handles.ContractLedgerContext; +import com.jd.blockchain.ledger.core.OperationHandleContext; +import com.jd.blockchain.ledger.core.TransactionRequestExtension; +import com.jd.blockchain.ledger.core.handles.ContractLedgerContext; import com.jd.blockchain.mocker.proxy.ExecutorProxy; public class MockerContractExeHandle implements OperationHandle { @@ -29,11 +36,11 @@ public class MockerContractExeHandle implements OperationHandle { private HashDigest ledgerHash; @Override - public BytesValue process(Operation op, LedgerDataSet dataset, TransactionRequestContext requestContext, - LedgerDataSet previousBlockDataset, OperationHandleContext opHandleContext, LedgerService ledgerService) { + public BytesValue process(Operation op, LedgerDataset dataset, TransactionRequestExtension request, + LedgerDataQuery previousBlockDataset, OperationHandleContext opHandleContext, LedgerService ledgerService) { ContractEventSendOperation contractOP = (ContractEventSendOperation) op; - HashDigest txHash = requestContext.getRequest().getTransactionContent().getHash(); + HashDigest txHash = request.getTransactionContent().getHash(); ExecutorProxy executorProxy = executorProxyMap.get(txHash); @@ -43,7 +50,7 @@ public class MockerContractExeHandle implements OperationHandle { ContractLedgerContext ledgerContext = new ContractLedgerContext(queryService, opHandleContext); MockerContractEventContext contractEventContext = new MockerContractEventContext(ledgerHash, - contractOP.getEvent(), requestContext.getRequest(), ledgerContext); + contractOP.getEvent(), request, ledgerContext); Object instance = executorProxy.getInstance(); EventProcessingAware awire = null; @@ -73,8 +80,8 @@ public class MockerContractExeHandle implements OperationHandle { } @Override - public boolean support(Class operationType) { - return ContractEventSendOperation.class.isAssignableFrom(operationType); + public Class getOperationType() { + return ContractEventSendOperation.class; } public void initLedger(LedgerManager ledgerManager, HashDigest ledgerHash) { diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerNodeHandler.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerNodeHandler.java index bd1bea24..b4d355fc 100644 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerNodeHandler.java +++ b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerNodeHandler.java @@ -1,8 +1,10 @@ package com.jd.blockchain.mocker.handler; import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.gateway.GatewayConfigProperties; +import com.jd.blockchain.ledger.LedgerInitProperties; import com.jd.blockchain.mocker.config.MockerConstant; import com.jd.blockchain.mocker.config.PresetAnswerPrompter; import com.jd.blockchain.mocker.node.GatewayNodeRunner; @@ -10,9 +12,7 @@ import com.jd.blockchain.mocker.node.NodeWebContext; import com.jd.blockchain.mocker.node.PeerNodeRunner; import com.jd.blockchain.tools.initializer.DBConnectionConfig; import com.jd.blockchain.tools.initializer.LedgerBindingConfig; -import com.jd.blockchain.tools.initializer.LedgerInitProperties; import com.jd.blockchain.tools.initializer.Prompter; -import com.jd.blockchain.tools.keygen.KeyGenCommand; import com.jd.blockchain.utils.concurrent.ThreadInvoker; import com.jd.blockchain.utils.net.NetworkAddress; import org.springframework.util.ResourceUtils; @@ -93,7 +93,7 @@ public class MockerNodeHandler { // 启动服务器; NetworkAddress initAddr = initSetting.getConsensusParticipant(nodeIndex).getInitializerAddress(); NodeWebContext node = new NodeWebContext(nodeIndex, initAddr); - PrivKey privkey = KeyGenCommand.decodePrivKeyWithRawPassword(PRIVATE_KEYS[nodeIndex], PASSWORD); + PrivKey privkey = KeyGenUtils.decodePrivKeyWithRawPassword(PRIVATE_KEYS[nodeIndex], PASSWORD); DBConnectionConfig dbConn = new DBConnectionConfig(); dbConn.setConnectionUri(MockerConstant.DB_MEMS[nodeIndex]); ThreadInvoker.AsyncCallback nodeCallback = node.startInit(privkey, initSetting, dbConn, consolePrompter, diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerOperationHandleRegister.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerOperationHandleRegister.java index f0819d72..d22c6174 100644 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerOperationHandleRegister.java +++ b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerOperationHandleRegister.java @@ -1,54 +1,54 @@ -package com.jd.blockchain.mocker.handler; - -import java.util.ArrayList; -import java.util.List; - -import com.jd.blockchain.ledger.LedgerException; -import com.jd.blockchain.ledger.core.OperationHandle; -import com.jd.blockchain.ledger.core.impl.OperationHandleRegisteration; -import com.jd.blockchain.ledger.core.impl.handles.ContractCodeDeployOperationHandle; -import com.jd.blockchain.ledger.core.impl.handles.DataAccountKVSetOperationHandle; -import com.jd.blockchain.ledger.core.impl.handles.DataAccountRegisterOperationHandle; -import com.jd.blockchain.ledger.core.impl.handles.UserRegisterOperationHandle; - -public class MockerOperationHandleRegister implements OperationHandleRegisteration { - - private List opHandles = new ArrayList<>(); - - public MockerOperationHandleRegister() { - initDefaultHandles(); - } - - /** - * 针对不采用bean依赖注入的方式来处理; - */ - private void initDefaultHandles(){ - opHandles.add(new DataAccountKVSetOperationHandle()); - opHandles.add(new DataAccountRegisterOperationHandle()); - opHandles.add(new UserRegisterOperationHandle()); - opHandles.add(new ContractCodeDeployOperationHandle()); -// opHandles.add(new ContractEventSendOperationHandle()); - } - - public List getOpHandles() { - return opHandles; - } - - public void registerHandler(OperationHandle operationHandle) { - opHandles.add(operationHandle); - } - - public void removeHandler(OperationHandle operationHandle) { - opHandles.remove(operationHandle); - } - - @Override - public OperationHandle getHandle(Class operationType) { - for (OperationHandle handle : opHandles) { - if (handle.support(operationType)) { - return handle; - } - } - throw new LedgerException("Unsupported operation type[" + operationType.getName() + "]!"); - } -} +//package com.jd.blockchain.mocker.handler; +// +//import java.util.ArrayList; +//import java.util.List; +// +//import com.jd.blockchain.ledger.LedgerException; +//import com.jd.blockchain.ledger.core.OperationHandle; +//import com.jd.blockchain.ledger.core.OperationHandleRegisteration; +//import com.jd.blockchain.ledger.core.handles.ContractCodeDeployOperationHandle; +//import com.jd.blockchain.ledger.core.handles.DataAccountKVSetOperationHandle; +//import com.jd.blockchain.ledger.core.handles.DataAccountRegisterOperationHandle; +//import com.jd.blockchain.ledger.core.handles.UserRegisterOperationHandle; +// +//public class MockerOperationHandleRegister implements OperationHandleRegisteration { +// +// private List opHandles = new ArrayList<>(); +// +// public MockerOperationHandleRegister() { +// initDefaultHandles(); +// } +// +// /** +// * 针对不采用bean依赖注入的方式来处理; +// */ +// private void initDefaultHandles(){ +// opHandles.add(new DataAccountKVSetOperationHandle()); +// opHandles.add(new DataAccountRegisterOperationHandle()); +// opHandles.add(new UserRegisterOperationHandle()); +// opHandles.add(new ContractCodeDeployOperationHandle()); +//// opHandles.add(new ContractEventSendOperationHandle()); +// } +// +// public List getOpHandles() { +// return opHandles; +// } +// +// public void registerHandler(OperationHandle operationHandle) { +// opHandles.add(operationHandle); +// } +// +// public void removeHandler(OperationHandle operationHandle) { +// opHandles.remove(operationHandle); +// } +// +// @Override +// public OperationHandle getHandle(Class operationType) { +// for (OperationHandle handle : opHandles) { +// if (handle.support(operationType)) { +// return handle; +// } +// } +// throw new LedgerException("Unsupported operation type[" + operationType.getName() + "]!"); +// } +//} diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerServiceHandler.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerServiceHandler.java index 36308c0c..d7f1f43b 100644 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerServiceHandler.java +++ b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/handler/MockerServiceHandler.java @@ -1,6 +1,7 @@ package com.jd.blockchain.mocker.handler; import com.jd.blockchain.crypto.HashDigest; +import com.jd.blockchain.crypto.KeyGenUtils; import com.jd.blockchain.crypto.PrivKey; import com.jd.blockchain.crypto.PubKey; import com.jd.blockchain.ledger.*; @@ -9,7 +10,6 @@ import com.jd.blockchain.mocker.data.KvData; import com.jd.blockchain.mocker.data.ResponseData; import com.jd.blockchain.sdk.BlockchainService; import com.jd.blockchain.sdk.client.GatewayServiceFactory; -import com.jd.blockchain.tools.keygen.KeyGenCommand; public class MockerServiceHandler { @@ -115,8 +115,8 @@ public class MockerServiceHandler { } private BlockchainKeypair defaultParticipant() { - PrivKey privKey = KeyGenCommand.decodePrivKeyWithRawPassword(MockerConstant.PRIVATE_KEYS[0], MockerConstant.PASSWORD); - PubKey pubKey = KeyGenCommand.decodePubKey(MockerConstant.PUBLIC_KEYS[0]); + PrivKey privKey = KeyGenUtils.decodePrivKeyWithRawPassword(MockerConstant.PRIVATE_KEYS[0], MockerConstant.PASSWORD); + PubKey pubKey = KeyGenUtils.decodePubKey(MockerConstant.PUBLIC_KEYS[0]); return new BlockchainKeypair(pubKey, privKey); } diff --git a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/node/NodeWebContext.java b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/node/NodeWebContext.java index 93096613..30cb4866 100644 --- a/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/node/NodeWebContext.java +++ b/source/tools/tools-mocker/src/main/java/com/jd/blockchain/mocker/node/NodeWebContext.java @@ -2,17 +2,17 @@ package com.jd.blockchain.mocker.node; import com.jd.blockchain.crypto.HashDigest; import com.jd.blockchain.crypto.PrivKey; +import com.jd.blockchain.ledger.LedgerInitProperties; import com.jd.blockchain.ledger.TransactionContent; import com.jd.blockchain.ledger.core.LedgerInitDecision; -import com.jd.blockchain.ledger.core.LedgerInitPermission; +import com.jd.blockchain.ledger.core.LedgerInitProposal; +import com.jd.blockchain.ledger.core.LedgerManager; import com.jd.blockchain.ledger.core.LedgerRepository; -import com.jd.blockchain.ledger.core.impl.LedgerManager; import com.jd.blockchain.mocker.config.LedgerInitWebConfiguration; import com.jd.blockchain.storage.service.DbConnection; import com.jd.blockchain.storage.service.impl.composite.CompositeConnectionFactory; import com.jd.blockchain.tools.initializer.DBConnectionConfig; import com.jd.blockchain.tools.initializer.LedgerInitProcess; -import com.jd.blockchain.tools.initializer.LedgerInitProperties; import com.jd.blockchain.tools.initializer.Prompter; import com.jd.blockchain.tools.initializer.web.LedgerInitializeWebController; import com.jd.blockchain.utils.concurrent.ThreadInvoker; @@ -48,7 +48,7 @@ public class NodeWebContext { return controller.getInitTxContent(); } - public LedgerInitPermission getLocalPermission() { + public LedgerInitProposal getLocalPermission() { return controller.getLocalPermission(); } 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 c787a014..79773915 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 @@ -9,6 +9,7 @@ import java.util.*; */ public abstract class ArrayUtils { private ArrayUtils() { + } public static T[] singleton(T obj, Class clazz) { @@ -30,6 +31,13 @@ public abstract class ArrayUtils { 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 List asList(T[] array){ return asList(array, 0, array.length); } diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/PropertiesUtils.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/PropertiesUtils.java index 994272b0..aaaed113 100644 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/PropertiesUtils.java +++ b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/PropertiesUtils.java @@ -251,6 +251,14 @@ public abstract class PropertiesUtils { String value = getRequiredProperty(props, key); return Boolean.parseBoolean(value); } + + public static boolean getBooleanOptional(Properties props, String key, boolean defaultValue) { + String value = getProperty(props, key, false); + if (value == null) { + return defaultValue; + } + return Boolean.parseBoolean(value); + } /** * 返回指定的属性;
@@ -263,6 +271,18 @@ public abstract class PropertiesUtils { public static String getRequiredProperty(Properties props, String key) { return getProperty(props, key, true); } + + public static String getOptionalProperty(Properties props, String key) { + return getProperty(props, key, false); + } + + public static String getOptionalProperty(Properties props, String key, String defaultValue) { + String value = getProperty(props, key, false); + if (value == null) { + return defaultValue; + } + return value; + } /** * 返回指定的属性;
diff --git a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/StringUtils.java b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/StringUtils.java index 5ae1a856..480d1335 100644 --- a/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/StringUtils.java +++ b/source/utils/utils-common/src/main/java/com/jd/blockchain/utils/StringUtils.java @@ -1,24 +1,79 @@ package com.jd.blockchain.utils; +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; import java.util.regex.Pattern; /** - * @Author zhaogw - * date 2018/11/26 20:46 + * @Author zhaogw date 2018/11/26 20:46 */ public class StringUtils { - public static boolean isEmpty(Object str) { - return str == null || "".equals(str); - } - - /* - * 判断是否为整数 - * @param str 传入的字符串 - * @return 是整数返回true,否则返回false - */ - - public static boolean isNumber(String str) { - Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$"); - return pattern.matcher(str).matches(); - } + + public static final String[] EMPTY_ARRAY = {}; + + public static boolean isEmpty(Object str) { + return str == null || "".equals(str); + } + + /* + * 判断是否为整数 + * + * @param str 传入的字符串 + * + * @return 是整数返回true,否则返回false + */ + + public static boolean isNumber(String str) { + Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$"); + return pattern.matcher(str).matches(); + } + + /** + * 按照指定的分隔符把字符串分解为字符数组,同时截掉每一个元素两端的空白字符,并忽略掉空字符元素; + * + * @param str 要被截断的字符串; + * @param delimiter 分隔符; + * @return + */ + public static String[] splitToArray(String str, String delimiter) { + return splitToArray(str, delimiter, true, true); + } + + /** + * 按照指定的分隔符把字符串分解为字符数组 + * + * @param str 要被截断的字符串; + * @param delimiter 分隔符; + * @param trimElement 是否截断元素两端的空白字符; + * @param ignoreEmptyElement 是否忽略空字符元素; + * @return + */ + public static String[] splitToArray(String str, String delimiter, boolean trimElement, boolean ignoreEmptyElement) { + if (str == null) { + return EMPTY_ARRAY; + } + if (trimElement) { + str = str.trim(); + } + if (str.length() == 0) { + return EMPTY_ARRAY; + } + StringTokenizer tokenizer = new StringTokenizer(str, delimiter); + List tokens = new ArrayList<>(); + while (tokenizer.hasMoreTokens()) { + String token = tokenizer.nextToken(); + if (trimElement) { + token = token.trim(); + } + if ((!ignoreEmptyElement) || token.length() > 0) { + tokens.add(token); + } + } + return tokens.toArray(new String[tokens.size()]); + } + + public static String trim(String str) { + return str == null ? "" : str.trim(); + } } \ No newline at end of file