Search in sources :

Example 1 with BlockchainKeypair

use of com.jd.blockchain.ledger.BlockchainKeypair in project jdchain-core by blockchain-jd-com.

the class LedgerSecurityManagerTest method testGetSecurityPolicy.

@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 };
    UserRoleDatasetEditor 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();
    ParticipantCollection partisQuery = Mockito.mock(ParticipantCollection.class);
    UserAccountSet usersQuery = Mockito.mock(UserAccountSet.class);
    // 创建安全管理器;
    LedgerSecurityManager securityManager = new LedgerSecurityManagerImpl(rolePrivilegeDataset, userRolesDataset, partisQuery, usersQuery);
    // 定义终端用户列表;终端用户一起共同具有 ADMIN、OPERATOR 角色;
    final Map<Bytes, BlockchainKeypair> endpoints = new HashMap<>();
    endpoints.put(kpManager.getAddress(), kpManager);
    endpoints.put(kpEmployee.getAddress(), kpEmployee);
    // 定义节点参与方列表;
    final Map<Bytes, BlockchainKeypair> nodes = new HashMap<>();
    nodes.put(kpPlatform.getAddress(), kpPlatform);
    // 创建一项与指定的终端用户和节点参与方相关的安全策略;
    SecurityPolicy policy = securityManager.getSecurityPolicy(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));
    }
}
Also used : RolePrivilegeDataset(com.jd.blockchain.ledger.core.RolePrivilegeDataset) LedgerSecurityManager(com.jd.blockchain.ledger.core.LedgerSecurityManager) TransactionPermission(com.jd.blockchain.ledger.TransactionPermission) HashMap(java.util.HashMap) ParticipantCollection(com.jd.blockchain.ledger.core.ParticipantCollection) LedgerPermission(com.jd.blockchain.ledger.LedgerPermission) BlockchainKeypair(com.jd.blockchain.ledger.BlockchainKeypair) Bytes(utils.Bytes) UserRoleDatasetEditor(com.jd.blockchain.ledger.core.UserRoleDatasetEditor) LedgerSecurityManagerImpl(com.jd.blockchain.ledger.core.LedgerSecurityManagerImpl) MemoryKVStorage(com.jd.blockchain.storage.service.utils.MemoryKVStorage) Privileges(com.jd.blockchain.ledger.Privileges) SecurityPolicy(com.jd.blockchain.ledger.SecurityPolicy) UserAccountSet(com.jd.blockchain.ledger.core.UserAccountSet) Test(org.junit.Test)

Example 2 with BlockchainKeypair

use of com.jd.blockchain.ledger.BlockchainKeypair in project jdchain-core by blockchain-jd-com.

the class LedgerAdminDatasetTest method verifyReadonlyState.

/**
 * 验证指定账户是否只读;
 *
 * @param readonlyAccount
 */
private void verifyReadonlyState(LedgerAdminDataSetEditor 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());
    newParti.setParticipantState(ParticipantNodeState.CONSENSUS);
    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);
}
Also used : ConsensusParticipantData(com.jd.blockchain.transaction.ConsensusParticipantData) NetworkAddress(utils.net.NetworkAddress) BlockchainKeypair(com.jd.blockchain.ledger.BlockchainKeypair) LedgerConfiguration(com.jd.blockchain.ledger.core.LedgerConfiguration)

Example 3 with BlockchainKeypair

use of com.jd.blockchain.ledger.BlockchainKeypair in project jdchain-core by blockchain-jd-com.

the class LedgerEditorTest method testGennesisBlockCreation.

/**
 * 测试创建账本;
 */
@Test
public void testGennesisBlockCreation() {
    LedgerEditor ldgEdt = createLedgerInitEditor();
    LedgerTransactionContext genisisTxCtx = createGenisisTx(ldgEdt, participants);
    LedgerDataSetEditor ldgDS = (LedgerDataSetEditor) genisisTxCtx.getDataset();
    AsymmetricKeypair cryptoKeyPair = signatureFunction.generateKeypair();
    BlockchainKeypair userKP = new BlockchainKeypair(cryptoKeyPair.getPubKey(), cryptoKeyPair.getPrivKey());
    UserAccount userAccount = ldgDS.getUserAccountSet().register(userKP.getAddress(), userKP.getPubKey());
    userAccount.setProperty("Name", "孙悟空", -1);
    userAccount.setProperty("Age", "10000", -1);
    TransactionResult tx = genisisTxCtx.commit(TransactionState.SUCCESS);
    TransactionRequest genesisTxReq = genisisTxCtx.getTransactionRequest();
    assertEquals(genesisTxReq.getTransactionHash(), tx.getTransactionHash());
    assertEquals(0, tx.getBlockHeight());
    LedgerBlock block = ldgEdt.prepare();
    assertEquals(0, block.getHeight());
    assertNotNull(block.getHash());
    assertNull(block.getLedgerHash());
    assertNull(block.getPreviousHash());
    // 提交数据,写入存储;
    ldgEdt.commit();
}
Also used : LedgerBlock(com.jd.blockchain.ledger.LedgerBlock) AsymmetricKeypair(com.jd.blockchain.crypto.AsymmetricKeypair) TransactionResult(com.jd.blockchain.ledger.TransactionResult) LedgerDataSetEditor(com.jd.blockchain.ledger.core.LedgerDataSetEditor) LedgerEditor(com.jd.blockchain.ledger.core.LedgerEditor) BlockchainKeypair(com.jd.blockchain.ledger.BlockchainKeypair) LedgerTransactionContext(com.jd.blockchain.ledger.core.LedgerTransactionContext) UserAccount(com.jd.blockchain.ledger.core.UserAccount) TransactionRequest(com.jd.blockchain.ledger.TransactionRequest) Test(org.junit.Test)

Example 4 with BlockchainKeypair

use of com.jd.blockchain.ledger.BlockchainKeypair in project jdchain-core by blockchain-jd-com.

the class LedgerEditorTest method testWriteDataAccoutKvOp.

@SuppressWarnings("unused")
@Test
public void testWriteDataAccoutKvOp() {
    MemoryKVStorage storage = new MemoryKVStorage();
    LedgerEditor ldgEdt = createLedgerInitEditor(storage);
    LedgerTransactionContext genisisTxCtx = createGenisisTx(ldgEdt, participants);
    LedgerDataSetEditor ldgDS = (LedgerDataSetEditor) genisisTxCtx.getDataset();
    AsymmetricKeypair cryptoKeyPair = signatureFunction.generateKeypair();
    BlockchainKeypair dataKP = new BlockchainKeypair(cryptoKeyPair.getPubKey(), cryptoKeyPair.getPrivKey());
    DataAccount dataAccount = ldgDS.getDataAccountSet().register(dataKP.getAddress(), dataKP.getPubKey(), null);
    dataAccount.getDataset().setValue("A", TypedValue.fromText("abc"), -1);
    TransactionResult tx = genisisTxCtx.commit(TransactionState.SUCCESS);
    LedgerBlock block = ldgEdt.prepare();
    // 提交数据,写入存储;
    ldgEdt.commit();
    // 预期这是第1个区块;
    assertNotNull(block);
    assertNotNull(block.getHash());
    assertEquals(0, block.getHeight());
    // 验证数据读写的一致性;
    BytesValue bytes = dataAccount.getDataset().getValue("A");
    assertEquals(DataType.TEXT, bytes.getType());
    String textValue = bytes.getBytes().toUTF8String();
    assertEquals("abc", textValue);
    // 验证重新加载的正确性;
    LedgerManager manager = new LedgerManager();
    HashDigest ledgerHash = block.getHash();
    LedgerRepository repo = manager.register(ledgerHash, storage, LedgerDataStructure.MERKLE_TREE);
    dataAccount = repo.getDataAccountSet().getAccount(dataKP.getAddress());
    assertNotNull(dataAccount);
    bytes = dataAccount.getDataset().getValue("A");
    assertEquals(DataType.TEXT, bytes.getType());
    textValue = bytes.getBytes().toUTF8String();
    assertEquals("abc", textValue);
    LedgerTransaction tx_init = repo.getTransactionSet().getTransaction(tx.getTransactionHash());
    assertNotNull(tx_init);
}
Also used : LedgerBlock(com.jd.blockchain.ledger.LedgerBlock) LedgerManager(com.jd.blockchain.ledger.core.LedgerManager) TransactionResult(com.jd.blockchain.ledger.TransactionResult) LedgerDataSetEditor(com.jd.blockchain.ledger.core.LedgerDataSetEditor) LedgerEditor(com.jd.blockchain.ledger.core.LedgerEditor) BlockchainKeypair(com.jd.blockchain.ledger.BlockchainKeypair) LedgerTransactionContext(com.jd.blockchain.ledger.core.LedgerTransactionContext) BytesValue(com.jd.blockchain.ledger.BytesValue) LedgerRepository(com.jd.blockchain.ledger.core.LedgerRepository) DataAccount(com.jd.blockchain.ledger.core.DataAccount) AsymmetricKeypair(com.jd.blockchain.crypto.AsymmetricKeypair) HashDigest(com.jd.blockchain.crypto.HashDigest) LedgerTransaction(com.jd.blockchain.ledger.LedgerTransaction) MemoryKVStorage(com.jd.blockchain.storage.service.utils.MemoryKVStorage) Test(org.junit.Test)

Example 5 with BlockchainKeypair

use of com.jd.blockchain.ledger.BlockchainKeypair in project jdchain-core by blockchain-jd-com.

the class LedgerInitSettingSerializeTest method test_ledgerinitsetting_ParticipantCertData.

// @Test
// public void test_ledgerinitsetting_ConsensusParticipantConfig() {
// }
@Test
public void test_ledgerinitsetting_ParticipantCertData() {
    ParticipantCertData[] parties = new ParticipantCertData[4];
    BlockchainKeypair[] keys = new BlockchainKeypair[parties.length];
    for (int i = 0; i < parties.length; i++) {
        keys[i] = BlockchainKeyGenerator.getInstance().generate();
        parties[i] = new ParticipantCertData(AddressEncoding.generateAddress(keys[i].getPubKey()), "Participant[" + i + "]", keys[i].getPubKey(), ParticipantNodeState.CONSENSUS);
    }
    ParticipantCertData[] parties1 = Arrays.copyOf(parties, 4);
    ledgerInitSettingData.setConsensusParticipants(parties1);
    ledgerInitSettingData.setLedgerDataStructure(LedgerDataStructure.MERKLE_TREE);
    ledgerInitSettingData.setIdentityMode(IdentityMode.KEYPAIR);
    byte[] encode = BinaryProtocol.encode(ledgerInitSettingData, LedgerInitSetting.class);
    LedgerInitSetting decode = BinaryProtocol.decode(encode);
    for (int i = 0; i < ledgerInitSettingData.getConsensusParticipants().length; i++) {
        assertEquals(ledgerInitSettingData.getConsensusParticipants()[i].getAddress(), decode.getConsensusParticipants()[i].getAddress());
        assertEquals(ledgerInitSettingData.getConsensusParticipants()[i].getName(), decode.getConsensusParticipants()[i].getName());
        assertEquals(ledgerInitSettingData.getConsensusParticipants()[i].getPubKey(), decode.getConsensusParticipants()[i].getPubKey());
    }
    assertArrayEquals(ledgerInitSettingData.getLedgerSeed(), decode.getLedgerSeed());
    assertArrayEquals(ledgerInitSettingData.getConsensusSettings().toBytes(), decode.getConsensusSettings().toBytes());
    assertEquals(ledgerInitSettingData.getCryptoSetting().getHashAlgorithm(), decode.getCryptoSetting().getHashAlgorithm());
    assertEquals(ledgerInitSettingData.getCryptoSetting().getAutoVerifyHash(), decode.getCryptoSetting().getAutoVerifyHash());
    assertEquals(ledgerInitSettingData.getConsensusProvider(), decode.getConsensusProvider());
}
Also used : ParticipantCertData(com.jd.blockchain.ledger.core.ParticipantCertData) LedgerInitSetting(com.jd.blockchain.ledger.LedgerInitSetting) BlockchainKeypair(com.jd.blockchain.ledger.BlockchainKeypair) Test(org.junit.Test)

Aggregations

BlockchainKeypair (com.jd.blockchain.ledger.BlockchainKeypair)23 Test (org.junit.Test)16 MemoryKVStorage (com.jd.blockchain.storage.service.utils.MemoryKVStorage)14 HashDigest (com.jd.blockchain.crypto.HashDigest)11 TransactionRequest (com.jd.blockchain.ledger.TransactionRequest)9 LedgerBlock (com.jd.blockchain.ledger.LedgerBlock)8 LedgerEditor (com.jd.blockchain.ledger.core.LedgerEditor)8 LedgerManager (com.jd.blockchain.ledger.core.LedgerManager)7 LedgerRepository (com.jd.blockchain.ledger.core.LedgerRepository)7 LedgerSecurityManager (com.jd.blockchain.ledger.core.LedgerSecurityManager)6 TransactionResponse (com.jd.blockchain.ledger.TransactionResponse)5 CryptoConfig (com.jd.blockchain.ledger.core.CryptoConfig)5 DefaultOperationHandleRegisteration (com.jd.blockchain.ledger.core.DefaultOperationHandleRegisteration)5 LedgerDataSet (com.jd.blockchain.ledger.core.LedgerDataSet)5 OperationHandleRegisteration (com.jd.blockchain.ledger.core.OperationHandleRegisteration)5 TransactionBatchProcessor (com.jd.blockchain.ledger.core.TransactionBatchProcessor)5 UserAccount (com.jd.blockchain.ledger.core.UserAccount)5 LedgerTransaction (com.jd.blockchain.ledger.LedgerTransaction)4 TransactionResult (com.jd.blockchain.ledger.TransactionResult)4 NetworkAddress (utils.net.NetworkAddress)4