Search in sources :

Example 1 with LedgerBindingConfig

use of com.jd.blockchain.tools.initializer.LedgerBindingConfig in project jdchain-core by blockchain-jd-com.

the class LedgerBindingConfigTest method assertLedgerBindingConfig.

// @Test
// public void testLedgerBindingRegister() throws IOException {
// LedgerManager ledgerManager = new LedgerManager();
// ClassPathResource ledgerBindingConfigFile = new ClassPathResource("ledger-binding-1.conf");
// InputStream in = ledgerBindingConfigFile.getInputStream();
// Exception ex = null;
// try {
// LedgerBindingConfig conf = LedgerBindingConfig.resolve(in);
// //			assertLedgerBindingConfig(conf);
// 
// HashDigest[] existingLedgerHashs = ledgerManager.getLedgerHashs();
// for (HashDigest lh : existingLedgerHashs) {
// ledgerManager.unregister(lh);
// }
// HashDigest[] ledgerHashs = conf.getLedgerHashs();
// for (HashDigest ledgerHash : ledgerHashs) {
// //				setConfig(conf,ledgerHash);
// LedgerBindingConfig.BindingConfig bindingConfig = conf.getLedger(ledgerHash);
// }
// } catch (Exception e) {
// ex =e;
// } finally {
// in.close();
// }
// 
// assertNull(ex);
// }
/**
 * 判断指定的对象跟测试模板是否一致;
 *
 * @param conf
 */
private void assertLedgerBindingConfig(LedgerBindingConfig conf) {
    String[] expectedHashs = { "j5ptBmn67B2p3yki3ji1j2ZMjnJhrUvP4kFpGmcXgvrhmk", "j5kLUENMvcUooZjKfz2bEYU6zoK9DAqbdDDU8aZEZFR4qf" };
    HashDigest[] hashs = conf.getLedgerHashs();
    for (int i = 0; i < hashs.length; i++) {
        assertEquals(expectedHashs[i], hashs[i].toBase58());
    }
    BindingConfig bindingConf_0 = conf.getLedger(hashs[0]);
    assertEquals("1", bindingConf_0.getParticipant().getAddress());
    assertEquals("keys/jd-com.priv", bindingConf_0.getParticipant().getPkPath());
    assertEquals("AdSXsf5QJpy", bindingConf_0.getParticipant().getPk());
    assertNull(bindingConf_0.getParticipant().getPassword());
    assertEquals("redis://ip:port/1", bindingConf_0.getDbConnection().getUri());
    assertEquals("kksfweffj", bindingConf_0.getDbConnection().getPassword());
    BindingConfig bindingConf_1 = conf.getLedger(hashs[1]);
    assertEquals("2", bindingConf_1.getParticipant().getAddress());
    assertEquals("keys/jd-com-1.priv", bindingConf_1.getParticipant().getPkPath());
    assertNull(bindingConf_1.getParticipant().getPk());
    assertEquals("kksafe", bindingConf_1.getParticipant().getPassword());
    assertEquals("redis://ip:port/2", bindingConf_1.getDbConnection().getUri());
    assertNull(bindingConf_1.getDbConnection().getPassword());
}
Also used : HashDigest(com.jd.blockchain.crypto.HashDigest) BindingConfig(com.jd.blockchain.tools.initializer.LedgerBindingConfig.BindingConfig) LedgerBindingConfig(com.jd.blockchain.tools.initializer.LedgerBindingConfig)

Example 2 with LedgerBindingConfig

use of com.jd.blockchain.tools.initializer.LedgerBindingConfig in project jdchain-core by blockchain-jd-com.

the class PeerServerBooter method startServer.

/**
 * 启动服务;
 *
 * @param ledgerBindingConfig 账本绑定配置;
 * @param hostAddress         服务地址;如果为空,则采用默认配置;
 * @param port                端口地址;如果小于等于 0 ,则采用默认配置;
 * @return
 */
private static ConfigurableApplicationContext startServer(LedgerBindingConfig ledgerBindingConfig, String hostAddress, int port, String springConfigLocation, Object... externalBeans) {
    List<String> argList = new ArrayList<String>();
    String logConfig = System.getProperty(LOG_CONFIG_FILE);
    if (!StringUtils.isEmpty(logConfig)) {
        argList.add(String.format("--logging.config=%s", logConfig));
    }
    String argServerAddress = String.format("--server.address=%s", "0.0.0.0");
    argList.add(argServerAddress);
    if (port > 0) {
        String argServerPort = String.format("--server.port=%s", port);
        argList.add(argServerPort);
    } else {
        port = 8080;
    }
    if (springConfigLocation != null) {
        argList.add(String.format("--spring.config.location=%s", springConfigLocation));
    }
    String[] args = argList.toArray(new String[argList.size()]);
    SpringApplication app = new SpringApplication(PeerConfiguration.class);
    if (externalBeans != null && externalBeans.length > 0) {
        app.addInitializers((ApplicationContextInitializer<ConfigurableApplicationContext>) applicationContext -> {
            ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory();
            for (Object bean : externalBeans) {
                if (bean != null) {
                    beanFactory.registerSingleton(bean.toString(), bean);
                }
            }
        });
    }
    // 启动 web 服务;
    ConfigurableApplicationContext ctx = app.run(args);
    RuntimeConstant.setMonitorProperties(port, Boolean.valueOf(ctx.getEnvironment().getProperty("server.ssl.enabled")));
    // 配置文件为空,则说明目前没有账本,不需要配置账本相关信息
    if (ledgerBindingConfig != null) {
        // 建立共识网络;
        Map<String, LedgerBindingConfigAware> bindingConfigAwares = ctx.getBeansOfType(LedgerBindingConfigAware.class);
        for (LedgerBindingConfigAware aware : bindingConfigAwares.values()) {
            aware.setConfig(ledgerBindingConfig);
        }
        ConsensusManage consensusManage = ctx.getBean(ConsensusManage.class);
        consensusManage.runAllRealms();
    }
    // 释放定时任务许可
    LedgerLoadTimer loadTimerBean = ctx.getBean(LedgerLoadTimer.class);
    loadTimerBean.release();
    return ctx;
}
Also used : ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) Arrays(java.util.Arrays) Global(com.jd.blockchain.consts.Global) NodeNetworkAddress(com.jd.blockchain.consensus.NodeNetworkAddress) ActionResponse(com.jd.blockchain.consensus.action.ActionResponse) TransactionResponse(com.jd.blockchain.ledger.TransactionResponse) URLClassLoader(java.net.URLClassLoader) MsgQueueNodeSettings(com.jd.blockchain.consensus.mq.settings.MsgQueueNodeSettings) BlockchainIdentity(com.jd.blockchain.ledger.BlockchainIdentity) MerkleIndex(com.jd.blockchain.ledger.merkletree.MerkleIndex) LedgerInitDecision(com.jd.blockchain.ledger.core.LedgerInitDecision) Map(java.util.Map) RoleSet(com.jd.blockchain.ledger.RoleSet) DigitalSignatureBody(com.jd.blockchain.ledger.DigitalSignatureBody) RuntimeConstant(com.jd.blockchain.runtime.RuntimeConstant) OperationResult(com.jd.blockchain.ledger.OperationResult) PrivilegeSet(com.jd.blockchain.ledger.PrivilegeSet) MsgQueueConsensusSettings(com.jd.blockchain.consensus.mq.settings.MsgQueueConsensusSettings) LedgerInitSetting(com.jd.blockchain.ledger.LedgerInitSetting) LedgerDataSnapshot(com.jd.blockchain.ledger.LedgerDataSnapshot) TransactionContent(com.jd.blockchain.ledger.TransactionContent) ContractCodeDeployOperation(com.jd.blockchain.ledger.ContractCodeDeployOperation) LedgerInitProposal(com.jd.blockchain.ledger.core.LedgerInitProposal) LedgerMetadata(com.jd.blockchain.ledger.LedgerMetadata) ClientIncomingSettings(com.jd.blockchain.consensus.ClientIncomingSettings) UserAuthInitSettings(com.jd.blockchain.ledger.UserAuthInitSettings) LedgerTransactions(com.jd.blockchain.ledger.LedgerTransactions) ContractEventSendOperation(com.jd.blockchain.ledger.ContractEventSendOperation) HashObject(com.jd.blockchain.ledger.HashObject) EventPublishOperation(com.jd.blockchain.ledger.EventPublishOperation) ArrayList(java.util.ArrayList) LedgerLoadTimer(com.jd.blockchain.peer.web.LedgerLoadTimer) UserAuthorizeOperation(com.jd.blockchain.ledger.UserAuthorizeOperation) LedgerAdminInfo(com.jd.blockchain.ledger.LedgerAdminInfo) ConsensusViewSettings(com.jd.blockchain.consensus.ConsensusViewSettings) DataAccountInfo(com.jd.blockchain.ledger.DataAccountInfo) ConsensusReconfigOperation(com.jd.blockchain.ledger.ConsensusReconfigOperation) TransactionResult(com.jd.blockchain.ledger.TransactionResult) ArgumentSet(utils.ArgumentSet) ParticipantStateUpdateOperation(com.jd.blockchain.ledger.ParticipantStateUpdateOperation) RolesConfigureOperation(com.jd.blockchain.ledger.RolesConfigureOperation) LedgerBlock(com.jd.blockchain.ledger.LedgerBlock) MerkleKey(com.jd.blockchain.ledger.proof.MerkleKey) LedgerSettings(com.jd.blockchain.ledger.LedgerSettings) File(java.io.File) Operation(com.jd.blockchain.ledger.Operation) DataContractRegistry(com.jd.binaryproto.DataContractRegistry) EventAccountRegisterOperation(com.jd.blockchain.ledger.EventAccountRegisterOperation) BaseConstant(utils.BaseConstant) NodeNetworkAddresses(com.jd.blockchain.consensus.NodeNetworkAddresses) DbConnectionFactory(com.jd.blockchain.storage.service.DbConnectionFactory) NodeSettings(com.jd.blockchain.consensus.NodeSettings) LoggerFactory(org.slf4j.LoggerFactory) LedgerBindingConfigException(com.jd.blockchain.tools.initializer.web.LedgerBindingConfigException) UserInfo(com.jd.blockchain.ledger.UserInfo) BytesValue(com.jd.blockchain.ledger.BytesValue) ConfigurableListableBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory) SpringApplication(org.springframework.boot.SpringApplication) BftsmartClientIncomingSettings(com.jd.blockchain.consensus.bftsmart.BftsmartClientIncomingSettings) LedgerInitOperation(com.jd.blockchain.ledger.LedgerInitOperation) ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) BftsmartNodeSettings(com.jd.blockchain.consensus.bftsmart.BftsmartNodeSettings) Event(com.jd.blockchain.ledger.Event) MsgQueueNetworkSettings(com.jd.blockchain.consensus.mq.settings.MsgQueueNetworkSettings) CryptoAlgorithm(com.jd.blockchain.crypto.CryptoAlgorithm) ParticipantRegisterOperation(com.jd.blockchain.ledger.ParticipantRegisterOperation) BlockBody(com.jd.blockchain.ledger.BlockBody) DataAccountKVSetOperation(com.jd.blockchain.ledger.DataAccountKVSetOperation) DigitalSignature(com.jd.blockchain.ledger.DigitalSignature) StringUtils(utils.StringUtils) UserRegisterOperation(com.jd.blockchain.ledger.UserRegisterOperation) MerklePath(com.jd.blockchain.ledger.proof.MerklePath) DataAccountRegisterOperation(com.jd.blockchain.ledger.DataAccountRegisterOperation) KeyIndex(com.jd.blockchain.ledger.merkletree.KeyIndex) List(java.util.List) LedgerBindingConfig(com.jd.blockchain.tools.initializer.LedgerBindingConfig) ParticipantNode(com.jd.blockchain.ledger.ParticipantNode) BytesValueList(com.jd.blockchain.ledger.BytesValueList) MsgQueueClientIncomingSettings(com.jd.blockchain.consensus.mq.settings.MsgQueueClientIncomingSettings) MerkleTrieData(com.jd.blockchain.ledger.proof.MerkleTrieData) RoleInitSettings(com.jd.blockchain.ledger.RoleInitSettings) ClassPathResource(org.springframework.core.io.ClassPathResource) CryptoSetting(com.jd.blockchain.ledger.CryptoSetting) ActionRequest(com.jd.blockchain.consensus.action.ActionRequest) CryptoProvider(com.jd.blockchain.crypto.CryptoProvider) UserInfoSetOperation(com.jd.blockchain.ledger.UserInfoSetOperation) LedgerMetadata_V2(com.jd.blockchain.ledger.LedgerMetadata_V2) TransactionRequest(com.jd.blockchain.ledger.TransactionRequest) HashAlgorithmUpdateOperation(com.jd.blockchain.ledger.HashAlgorithmUpdateOperation) ClientCredential(com.jd.blockchain.consensus.ClientCredential) MerkleLeaf(com.jd.blockchain.ledger.proof.MerkleLeaf) Logger(org.slf4j.Logger) HashBucketEntry(com.jd.blockchain.ledger.merkletree.HashBucketEntry) ContractInfo(com.jd.blockchain.ledger.ContractInfo) TypeUtils(utils.reflection.TypeUtils) LedgerTransaction(com.jd.blockchain.ledger.LedgerTransaction) ConsensusSettingsUpdateOperation(com.jd.blockchain.ledger.ConsensusSettingsUpdateOperation) MsgQueueBlockSettings(com.jd.blockchain.consensus.mq.settings.MsgQueueBlockSettings) MerkleSnapshot(com.jd.blockchain.ledger.MerkleSnapshot) UserAccountHeader(com.jd.blockchain.ledger.UserAccountHeader) SecurityInitSettings(com.jd.blockchain.ledger.SecurityInitSettings) ApplicationContextInitializer(org.springframework.context.ApplicationContextInitializer) InputStream(java.io.InputStream) BftsmartConsensusViewSettings(com.jd.blockchain.consensus.bftsmart.BftsmartConsensusViewSettings) ParticipantStateUpdateInfo(com.jd.blockchain.ledger.ParticipantStateUpdateInfo) SpringApplication(org.springframework.boot.SpringApplication) ArrayList(java.util.ArrayList) LedgerLoadTimer(com.jd.blockchain.peer.web.LedgerLoadTimer) HashObject(com.jd.blockchain.ledger.HashObject) ConfigurableListableBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory)

Example 3 with LedgerBindingConfig

use of com.jd.blockchain.tools.initializer.LedgerBindingConfig in project jdchain-core by blockchain-jd-com.

the class LedgerBindingConfigTest method testResolveAndStore.

@Test
public void testResolveAndStore() throws IOException {
    ClassPathResource ledgerBindingConfigFile = new ClassPathResource("ledger-binding.conf");
    InputStream in = ledgerBindingConfigFile.getInputStream();
    try {
        LedgerBindingConfig conf = LedgerBindingConfig.resolve(in);
        assertLedgerBindingConfig(conf);
        conf.store(System.out);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        conf.store(out);
        ByteArrayInputStream newIn = new ByteArrayInputStream(out.toByteArray());
        LedgerBindingConfig newConf = LedgerBindingConfig.resolve(newIn);
        assertLedgerBindingConfig(newConf);
    } finally {
        in.close();
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) LedgerBindingConfig(com.jd.blockchain.tools.initializer.LedgerBindingConfig) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ClassPathResource(org.springframework.core.io.ClassPathResource) Test(org.junit.Test)

Example 4 with LedgerBindingConfig

use of com.jd.blockchain.tools.initializer.LedgerBindingConfig in project jdchain-core by blockchain-jd-com.

the class PeerServerBooter method handle.

public static void handle(String[] args) {
    LedgerBindingConfig ledgerBindingConfig = null;
    ArgumentSet arguments = ArgumentSet.resolve(args, ArgumentSet.setting().prefix(LEDGERBIND_ARG, HOST_ARG, PORT_ARG, SPRING_CF_LOCATION));
    try {
        ArgumentSet.ArgEntry argLedgerBindConf = arguments.getArg(LEDGERBIND_ARG);
        ledgerBindConfigFile = argLedgerBindConf == null ? null : argLedgerBindConf.getValue();
        if (ledgerBindConfigFile == null) {
            LOGGER.info("Load build-in default configuration ...");
            ClassPathResource configResource = new ClassPathResource(LEDGER_BIND_CONFIG_NAME);
            if (configResource.exists()) {
                try (InputStream in = configResource.getInputStream()) {
                    ledgerBindingConfig = LedgerBindingConfig.resolve(in);
                }
            }
        } else {
            LOGGER.info("Load configuration,ledgerBindConfigFile position=" + ledgerBindConfigFile);
            File file = new File(ledgerBindConfigFile);
            if (file.exists()) {
                try {
                    ledgerBindingConfig = LedgerBindingConfig.resolve(file);
                } catch (LedgerBindingConfigException e) {
                    LOGGER.info("Load ledgerBindConfigFile content is empty !!!");
                }
            }
        }
        String host = null;
        ArgumentSet.ArgEntry hostArg = arguments.getArg(HOST_ARG);
        if (hostArg != null) {
            host = hostArg.getValue();
        }
        int port = 0;
        ArgumentSet.ArgEntry portArg = arguments.getArg(PORT_ARG);
        if (portArg != null) {
            try {
                port = Integer.parseInt(portArg.getValue());
            } catch (NumberFormatException e) {
            // ignore NumberFormatException of port argument;
            }
        }
        // spring config location;
        String springConfigLocation = null;
        ArgumentSet.ArgEntry spConfigLocation = arguments.getArg(SPRING_CF_LOCATION);
        if (spConfigLocation != null) {
            springConfigLocation = spConfigLocation.getValue();
        }
        PeerServerBooter booter = new PeerServerBooter(ledgerBindingConfig, host, port, springConfigLocation);
        LOGGER.debug("PeerServerBooter's urls=" + Arrays.toString(((URLClassLoader) booter.getClass().getClassLoader()).getURLs()));
        booter.start();
    } catch (Exception e) {
        LOGGER.error("Peer start error", e);
    }
}
Also used : InputStream(java.io.InputStream) ArgumentSet(utils.ArgumentSet) LedgerBindingConfigException(com.jd.blockchain.tools.initializer.web.LedgerBindingConfigException) LedgerBindingConfig(com.jd.blockchain.tools.initializer.LedgerBindingConfig) File(java.io.File) ClassPathResource(org.springframework.core.io.ClassPathResource) LedgerBindingConfigException(com.jd.blockchain.tools.initializer.web.LedgerBindingConfigException)

Example 5 with LedgerBindingConfig

use of com.jd.blockchain.tools.initializer.LedgerBindingConfig in project jdchain-core by blockchain-jd-com.

the class LedgerLoadTimer method ledgerLoad.

// 每5秒执行一次
@Scheduled(cron = "*/5 * * * * * ")
public void ledgerLoad() {
    lock.lock();
    try {
        LOGGER.debug("--- Ledger loader tasks start... ");
        boolean acquire = false;
        try {
            /**
             * 5秒内获取许可
             */
            acquire = loadSemaphore.tryAcquire(5, TimeUnit.SECONDS);
            if (acquire) {
                LedgerBindingConfig ledgerBindingConfig = loadLedgerBindingConfig();
                if (ledgerBindingConfig == null) {
                    // print debug
                    LOGGER.warn("Can not load any ledgerBindingConfigs !!!");
                    return;
                }
                HashDigest[] totalLedgerHashs = ledgerBindingConfig.getLedgerHashs();
                Set<HashDigest> existedHashSet = existedHashSet();
                Set<HashDigest> newAddHashs = new HashSet<>();
                for (HashDigest ledgerHash : totalLedgerHashs) {
                    if (!existedHashSet.contains(ledgerHash)) {
                        newAddHashs.add(ledgerHash);
                    }
                }
                if (!newAddHashs.isEmpty()) {
                    // 由线程单独执行
                    ledgerLoadExecutor.execute(new LedgerLoadRunnable(newAddHashs, ledgerBindingConfig));
                }
            } else {
                LOGGER.warn("--- Can not get semaphore of load ledger !!!");
            }
        } catch (Exception e) {
            LOGGER.error("--- Ledger loader execute error !!!", e);
        } finally {
            if (acquire) {
                // 获取到许可的情况下释放,以便于后续线程处理
                release();
            }
        }
    } finally {
        lock.unlock();
    }
}
Also used : HashDigest(com.jd.blockchain.crypto.HashDigest) LedgerBindingConfig(com.jd.blockchain.tools.initializer.LedgerBindingConfig) LedgerBindingConfigException(com.jd.blockchain.tools.initializer.web.LedgerBindingConfigException) BeansException(org.springframework.beans.BeansException) Scheduled(org.springframework.scheduling.annotation.Scheduled)

Aggregations

LedgerBindingConfig (com.jd.blockchain.tools.initializer.LedgerBindingConfig)6 LedgerBindingConfigException (com.jd.blockchain.tools.initializer.web.LedgerBindingConfigException)3 InputStream (java.io.InputStream)3 ClassPathResource (org.springframework.core.io.ClassPathResource)3 HashDigest (com.jd.blockchain.crypto.HashDigest)2 File (java.io.File)2 DataContractRegistry (com.jd.binaryproto.DataContractRegistry)1 ClientCredential (com.jd.blockchain.consensus.ClientCredential)1 ClientIncomingSettings (com.jd.blockchain.consensus.ClientIncomingSettings)1 ConsensusViewSettings (com.jd.blockchain.consensus.ConsensusViewSettings)1 NodeNetworkAddress (com.jd.blockchain.consensus.NodeNetworkAddress)1 NodeNetworkAddresses (com.jd.blockchain.consensus.NodeNetworkAddresses)1 NodeSettings (com.jd.blockchain.consensus.NodeSettings)1 ActionRequest (com.jd.blockchain.consensus.action.ActionRequest)1 ActionResponse (com.jd.blockchain.consensus.action.ActionResponse)1 BftsmartClientIncomingSettings (com.jd.blockchain.consensus.bftsmart.BftsmartClientIncomingSettings)1 BftsmartConsensusViewSettings (com.jd.blockchain.consensus.bftsmart.BftsmartConsensusViewSettings)1 BftsmartNodeSettings (com.jd.blockchain.consensus.bftsmart.BftsmartNodeSettings)1 MsgQueueBlockSettings (com.jd.blockchain.consensus.mq.settings.MsgQueueBlockSettings)1 MsgQueueClientIncomingSettings (com.jd.blockchain.consensus.mq.settings.MsgQueueClientIncomingSettings)1