Search in sources :

Example 1 with LedgerAdminDataSetEditor

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

the class LedgerAdminDatasetTest method testSerialization.

@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());
        parties[i].setParticipantState(ParticipantNodeState.CONSENSUS);
    }
    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);
    initSetting.setIdentityMode(IdentityMode.KEYPAIR);
    byte[] ledgerSeed = new byte[16];
    rand.nextBytes(ledgerSeed);
    initSetting.setLedgerSeed(ledgerSeed);
    MemoryKVStorage testStorage = new MemoryKVStorage();
    // Create intance with init setting;
    LedgerAdminDataSetEditor ledgerAdminDataset = new LedgerAdminDataSetEditor(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.getAuthorizations().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();
    LedgerAdminDataSetEditor reloadAdminAccount1 = new LedgerAdminDataSetEditor(-1, adminAccHash, keyPrefix, testStorage, testStorage, LedgerDataStructure.MERKLE_TREE, 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.getAuthorizations());
    // --------------
    // 重新加载,并进行修改;
    LedgerAdminDataSetEditor reloadAdminAccount2 = new LedgerAdminDataSetEditor(-1, adminAccHash, keyPrefix, testStorage, testStorage, LedgerDataStructure.MERKLE_TREE, 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.getAuthorizations().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;
    LedgerAdminDataSetEditor previousAdminAccount = new LedgerAdminDataSetEditor(-1, adminAccHash, keyPrefix, testStorage, testStorage, LedgerDataStructure.MERKLE_TREE, true);
    verifyRealoadingSettings(previousAdminAccount, adminAccHash, ledgerAdminDataset.getMetadata(), ledgerAdminDataset.getSettings());
    verifyRealoadingParities(previousAdminAccount, parties1);
    verifyReadonlyState(previousAdminAccount);
    // load the hash of new committing;
    LedgerAdminDataSetEditor newlyAdminAccount = new LedgerAdminDataSetEditor(-1, newAccHash, keyPrefix, testStorage, testStorage, LedgerDataStructure.MERKLE_TREE, true);
    verifyRealoadingSettings(newlyAdminAccount, newAccHash, newMeta, newlyLedgerSettings);
    verifyRealoadingParities(newlyAdminAccount, parties);
    verifyReadonlyState(newlyAdminAccount);
// System.out.println("========= [LedgerAdminAccount Test] Show generated storage keys... =======");
// testStorage.printStoragedKeys();
}
Also used : ConsensusParticipantData(com.jd.blockchain.transaction.ConsensusParticipantData) BlockchainKeypair(com.jd.blockchain.ledger.BlockchainKeypair) CryptoProvider(com.jd.blockchain.crypto.CryptoProvider) LedgerAdminDataSetEditor(com.jd.blockchain.ledger.core.LedgerAdminDataSetEditor) LedgerSettings(com.jd.blockchain.ledger.LedgerSettings) Bytes(utils.Bytes) NetworkAddress(utils.net.NetworkAddress) HashDigest(com.jd.blockchain.crypto.HashDigest) LedgerMetadata_V2(com.jd.blockchain.ledger.LedgerMetadata_V2) MemoryKVStorage(com.jd.blockchain.storage.service.utils.MemoryKVStorage) LedgerConfiguration(com.jd.blockchain.ledger.core.LedgerConfiguration) LedgerInitData(com.jd.blockchain.transaction.LedgerInitData) CryptoConfig(com.jd.blockchain.ledger.core.CryptoConfig) Test(org.junit.Test)

Example 2 with LedgerAdminDataSetEditor

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

the class ParticipantStateUpdateOperationHandle method doProcess.

@Override
protected void doProcess(ParticipantStateUpdateOperation op, LedgerTransactionContext transactionContext, TransactionRequestExtension requestContext, LedgerQuery previousBlockDataset, OperationHandleContext handleContext, EventManager manager) {
    // 权限校验;
    SecurityPolicy securityPolicy = SecurityContext.getContextUsersPolicy();
    securityPolicy.checkEndpointPermission(LedgerPermission.REGISTER_PARTICIPANT, MultiIDsPolicy.AT_LEAST_ONE);
    LedgerAdminDataSet adminAccountDataSet = transactionContext.getDataset().getAdminDataset();
    ParticipantNode[] participants = null;
    participants = ((LedgerAdminDataSetEditor) adminAccountDataSet).getParticipants();
    ParticipantNode participantNode = null;
    for (int i = 0; i < participants.length; i++) {
        if (op.getParticipantID().getPubKey().equals(participants[i].getPubKey())) {
            participantNode = new PartNode(participants[i].getId(), participants[i].getName(), participants[i].getPubKey(), op.getState());
            break;
        }
    }
    if (null == participantNode) {
        throw new ParticipantDoesNotExistException(String.format("Participant doesn't exist! --[Address=%s]", op.getParticipantID().getAddress()));
    }
    // 激活新参与方的共识状态
    ((LedgerAdminDataSetEditor) adminAccountDataSet).updateParticipant(participantNode);
}
Also used : LedgerAdminDataSet(com.jd.blockchain.ledger.core.LedgerAdminDataSet) SecurityPolicy(com.jd.blockchain.ledger.SecurityPolicy) LedgerAdminDataSetEditor(com.jd.blockchain.ledger.core.LedgerAdminDataSetEditor)

Example 3 with LedgerAdminDataSetEditor

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

the class RootCAUpdateOperationHandle method doProcess.

@Override
protected void doProcess(RootCAUpdateOperation op, LedgerTransactionContext transactionContext, TransactionRequestExtension requestContext, LedgerQuery ledger, OperationHandleContext handleContext, EventManager manager) {
    // 权限校验;
    SecurityPolicy securityPolicy = SecurityContext.getContextUsersPolicy();
    securityPolicy.checkEndpointPermission(LedgerPermission.UPDATE_ROOT_CA, MultiIDsPolicy.AT_LEAST_ONE);
    LedgerAdminDataSet adminDataset = transactionContext.getDataset().getAdminDataset();
    if (adminDataset.getAdminSettings().getMetadata().getIdentityMode() == IdentityMode.CA) {
        String[] ledgerCAs = adminDataset.getAdminSettings().getMetadata().getLedgerCertificates();
        Map<PublicKey, String> ledgerCAMap = new HashMap<>();
        for (int i = 0; i < ledgerCAs.length; i++) {
            X509Certificate cert = CertificateUtils.parseCertificate(ledgerCAs[i]);
            PublicKey publicKey = cert.getPublicKey();
            ledgerCAMap.put(publicKey, ledgerCAs[i]);
        }
        String[] certificatesAdd = op.getCertificatesAdd();
        for (String cert : certificatesAdd) {
            X509Certificate certificate = CertificateUtils.parseCertificate(cert);
            CertificateUtils.checkCACertificate(certificate);
            CertificateUtils.checkValidity(certificate);
            if (!ledgerCAMap.containsKey(certificate.getPublicKey())) {
                ledgerCAMap.put(certificate.getPublicKey(), cert);
            } else {
                throw new LedgerException("Certificate [" + CertificateUtils.toPEMString(certificate) + "] already exists in the ledger!");
            }
        }
        String[] certificatesUpdate = op.getCertificatesUpdate();
        for (String cert : certificatesUpdate) {
            X509Certificate certificate = CertificateUtils.parseCertificate(cert);
            CertificateUtils.checkCACertificate(certificate);
            CertificateUtils.checkValidity(certificate);
            if (ledgerCAMap.containsKey(certificate.getPublicKey())) {
                ledgerCAMap.put(certificate.getPublicKey(), cert);
            } else {
                throw new LedgerException("Certificate [" + CertificateUtils.toPEMString(certificate) + "] not exists in the ledger!");
            }
        }
        String[] certificatesRemove = op.getCertificatesRemove();
        for (String cert : certificatesRemove) {
            X509Certificate certificate = CertificateUtils.parseCertificate(cert);
            CertificateUtils.checkCACertificate(certificate);
            if (ledgerCAMap.containsKey(certificate.getPublicKey())) {
                ledgerCAMap.remove(certificate.getPublicKey(), cert);
            } else {
                throw new LedgerException("Certificate [" + CertificateUtils.toPEMString(certificate) + "] not exists in the ledger!");
            }
        }
        if (ledgerCAMap.size() == 0) {
            throw new LedgerException("At least one root certificate is required!");
        }
        ((LedgerAdminDataSetEditor) adminDataset).updateLedgerCA(ledgerCAMap.values().toArray(new String[0]));
    } else {
        throw new LedgerException("Not in CA identity mode!");
    }
}
Also used : LedgerAdminDataSet(com.jd.blockchain.ledger.core.LedgerAdminDataSet) HashMap(java.util.HashMap) PublicKey(java.security.PublicKey) SecurityPolicy(com.jd.blockchain.ledger.SecurityPolicy) LedgerException(com.jd.blockchain.ledger.LedgerException) X509Certificate(java.security.cert.X509Certificate) LedgerAdminDataSetEditor(com.jd.blockchain.ledger.core.LedgerAdminDataSetEditor)

Aggregations

LedgerAdminDataSetEditor (com.jd.blockchain.ledger.core.LedgerAdminDataSetEditor)3 SecurityPolicy (com.jd.blockchain.ledger.SecurityPolicy)2 LedgerAdminDataSet (com.jd.blockchain.ledger.core.LedgerAdminDataSet)2 CryptoProvider (com.jd.blockchain.crypto.CryptoProvider)1 HashDigest (com.jd.blockchain.crypto.HashDigest)1 BlockchainKeypair (com.jd.blockchain.ledger.BlockchainKeypair)1 LedgerException (com.jd.blockchain.ledger.LedgerException)1 LedgerMetadata_V2 (com.jd.blockchain.ledger.LedgerMetadata_V2)1 LedgerSettings (com.jd.blockchain.ledger.LedgerSettings)1 CryptoConfig (com.jd.blockchain.ledger.core.CryptoConfig)1 LedgerConfiguration (com.jd.blockchain.ledger.core.LedgerConfiguration)1 MemoryKVStorage (com.jd.blockchain.storage.service.utils.MemoryKVStorage)1 ConsensusParticipantData (com.jd.blockchain.transaction.ConsensusParticipantData)1 LedgerInitData (com.jd.blockchain.transaction.LedgerInitData)1 PublicKey (java.security.PublicKey)1 X509Certificate (java.security.cert.X509Certificate)1 HashMap (java.util.HashMap)1 Test (org.junit.Test)1 Bytes (utils.Bytes)1 NetworkAddress (utils.net.NetworkAddress)1