Search in sources :

Example 1 with Keystore

use of org.aion.zero.impl.keystore.Keystore in project aion by aionnetwork.

the class Aion method main.

public static void main(String[] args) {
    // TODO: should we load native libraries first thing?
    NativeLibrary.checkNativeLibrariesLoaded();
    try {
        Compiler.getInstance().compileHelloAion();
    } catch (IOException e) {
        System.out.println("compiler load failed!");
        throw new ExceptionInInitializerError();
    }
    /*
         * @ATTENTION: ECKey have two layer: tx layer is KeyFac optional,
         *             network layer is hardcode to secp256.
         */
    ECKeyFac.setType(ED25519);
    HashUtil.setType(BLAKE2B_256);
    CfgAion cfg = CfgAion.inst();
    ReturnType ret = new Cli().callAndInitializeAvm(args, cfg);
    if (ret != ReturnType.RUN) {
        // We have to shutdown the avm if we exit early
        shutdownAvm();
        System.exit(ret.getValue());
    }
    Properties p = cfg.getFork().getProperties();
    p.forEach((k, v) -> {
        System.out.println("<Protocol name: " + k.toString() + (k.toString().contains("fork") ? " block#: " : ": ") + v.toString());
    });
    // can't find the keypair.
    if (cfg.getApi().getZmq().getActive() && cfg.getApi().getZmq().isSecureConnectEnabledEnabled()) {
        try {
            checkZmqKeyPair();
        } catch (Exception e) {
            System.out.println("Check zmq keypair fail! " + e.toString());
            // We have to shutdown the avm if we exit early
            shutdownAvm();
            System.exit(SystemExitCodes.INITIALIZATION_ERROR);
        }
    }
    // UUID check
    String UUID = cfg.getId();
    if (!UUID.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) {
        System.out.println("Invalid UUID; please check <id> setting in config.xml");
        // We have to shutdown the avm if we exit early
        shutdownAvm();
        System.exit(SystemExitCodes.INITIALIZATION_ERROR);
    }
    ServiceLoader.load(EventMgrModule.class);
    try {
        ServiceLoader.load(AionLoggerFactory.class);
    } catch (Exception e) {
        System.out.println("load AionLoggerFactory service fail!" + e.toString());
        throw e;
    }
    // get the ssl password synchronously from the console, only if required
    // do this here, before writes to logger because if we don't do this here, then
    // it gets presented to console out of order with the rest of the logging ...
    final char[] sslPass = getSslPassword(cfg);
    // from now on, all logging to console and file happens asynchronously
    String[] filePath = new String[7];
    // Log/Database path
    if (!cfg.getLog().getLogFile()) {
        System.out.println("Logger disabled; to enable please update log settings in config.xml and restart kernel.");
        filePath[0] = "« disabled »";
    } else {
        filePath[0] = cfg.getLogPath();
    }
    // Logger initialize with LOGFILE and LOGPATH (user config inputs)
    AionLoggerFactory.init(cfg.getLog().getModules(), cfg.getLog().getLogFile(), cfg.getLogPath());
    Logger genLog = AionLoggerFactory.getLogger(LogEnum.GEN.name());
    filePath[1] = cfg.getDatabasePath();
    filePath[2] = Keystore.getKeystorePath();
    filePath[3] = cfg.getExecConfigFile().getAbsolutePath();
    filePath[4] = cfg.getInitialConfigFile().getAbsolutePath();
    filePath[5] = cfg.getGenesisFile().getAbsolutePath();
    filePath[6] = cfg.getForkFile().getAbsolutePath();
    String path = "\n-------------------------------- USED PATHS --------------------------------" + "\n> Logger path:   " + filePath[0] + "\n> Database path: " + filePath[1] + "\n> Keystore path: " + filePath[2] + "\n> Config write:  " + filePath[3] + "\n----------------------------------------------------------------------------" + "\n> Config read:   " + filePath[4] + "\n> Genesis read:  " + filePath[5] + "\n> Fork read:     " + filePath[6] + "\n----------------------------------------------------------------------------\n\n";
    String logo = "\n\n" + " _|_|_|_| _|                     _|_|_|      _|     _|_|_|_|  \n" + "    _|    _|_|_|     _|_|      _|      _|   _|_|    _|     _| \n" + "    _|    _|    _| _|_|_|_|    _|      _|  _|  _|   _|      _|\n" + "    _|    _|    _| _|          _|      _| _|    _|  _|      _|\n" + "    _|    _|    _|   _|_|_|      _|_|_|  _|_|_|_|_| _|_|_|_|_|\n" + "\n";
    // always print the version string in the center of The OAN logo
    String peakName = "Denali";
    String versionStr = "v" + KERNEL_VERSION + " (" + peakName + ")";
    String networkStr = cfg.getNetwork();
    // if using old kernel configuration
    if (networkStr == null && cfg.getNet().getId() >= 0) {
        networkStr = Network.determineNetwork(cfg.getNet().getId()).toString();
    }
    logo = appendLogo(logo, versionStr);
    if (networkStr != null) {
        logo = appendLogo(logo, networkStr);
    }
    // show enabled VMs
    logo = appendLogo(logo, "using FVM & AVM");
    genLog.info(path);
    genLog.info(logo);
    IAionChain ac = AionFactory.create();
    EquihashMiner nm = null;
    if (cfg.getConsensus().getMining() && !cfg.getTx().isSeedMode()) {
        nm = ac.getBlockMiner();
    }
    if (nm != null) {
        nm.delayedStartMining(10);
    }
    /*
         * Create JMX server and register in-flight config receiver MBean.  Commenting out for now
         * because not using it yet.
         */
    // InFlightConfigReceiver inFlightConfigReceiver = new InFlightConfigReceiver(
    // cfg, new DynamicConfigKeyRegistry());
    // MBeanServer server = ManagementFactory.getPlatformMBeanServer();
    // ObjectName objectName = null;
    // try {
    // objectName = new ObjectName(InFlightConfigReceiver.DEFAULT_JMX_OBJECT_NAME);
    // server.registerMBean(inFlightConfigReceiver, objectName);
    // } catch (MalformedObjectNameException
    // | NotCompliantMBeanException
    // | InstanceAlreadyExistsException
    // | MBeanRegistrationException ex) {
    // genLog.error(
    // "Failed to initialize JMX server.  In-flight configuration changes
    // will not be available.",
    // ex);
    // }
    /*
         * Start Threads.
         */
    Thread zmqThread = null;
    ProtocolProcessor processor = null;
    AccountManager am = null;
    if (cfg.getApi().getZmq().getActive()) {
        am = new AccountManager(AionLoggerFactory.getLogger(LogEnum.API.name()));
        ApiAion0 javaAPI = new ApiAion0(ac, am);
        ac.setApiServiceCallback(new BlockchainCallbackForApiServer(javaAPI));
        IHdlr handler = new HdlrZmq(javaAPI);
        processor = new ProtocolProcessor(handler, cfg.getApi().getZmq());
        zmqThread = new Thread(processor, "zmq-api");
        zmqThread.start();
    }
    RpcServer rpcServer = null;
    if (cfg.getApi().getRpc().isActive()) {
        if (am == null) {
            am = new AccountManager(AionLoggerFactory.getLogger(LogEnum.API.name()));
        }
        CfgApiRpc rpcCfg = cfg.getApi().getRpc();
        AccountManager finalAm = am;
        Consumer<RpcServerBuilder<? extends RpcServerBuilder<?>>> commonRpcConfig = (rpcBuilder) -> {
            rpcBuilder.setUrl(rpcCfg.getIp(), rpcCfg.getPort());
            rpcBuilder.enableEndpoints(rpcCfg.getEnabled());
            rpcBuilder.enableMethods(rpcCfg.getEnabledMethods());
            rpcBuilder.disableMethods(rpcCfg.getDisabledMethods());
            rpcBuilder.setWorkerPoolSize(rpcCfg.getWorkerThreads());
            rpcBuilder.setIoPoolSize(rpcCfg.getIoThreads());
            rpcBuilder.setRequestQueueSize(rpcCfg.getRequestQueueSize());
            rpcBuilder.setStuckThreadDetectorEnabled(rpcCfg.isStuckThreadDetectorEnabled());
            rpcBuilder.setAccountManager(finalAm);
            if (rpcCfg.isCorsEnabled()) {
                rpcBuilder.enableCorsWithOrigin(rpcCfg.getCorsOrigin());
            }
            CfgSsl cfgSsl = rpcCfg.getSsl();
            if (cfgSsl.getEnabled()) {
                rpcBuilder.enableSsl(cfgSsl.getCert(), sslPass);
            }
        };
        RpcServerVendor rpcVendor = RpcServerVendor.fromString(rpcCfg.getVendor()).orElse(RpcServerVendor.UNDERTOW);
        try {
            switch(rpcVendor) {
                case NANO:
                    {
                        NanoRpcServer.Builder rpcBuilder = new NanoRpcServer.Builder();
                        commonRpcConfig.accept(rpcBuilder);
                        rpcServer = rpcBuilder.build();
                        break;
                    }
                case UNDERTOW:
                default:
                    {
                        UndertowRpcServer.Builder rpcBuilder = new UndertowRpcServer.Builder();
                        commonRpcConfig.accept(rpcBuilder);
                        rpcServer = rpcBuilder.build();
                        break;
                    }
            }
        } catch (Exception e) {
            genLog.error("Failed to instantiate RPC server.", e);
        }
        if (rpcServer == null) {
            throw new IllegalStateException("Issue with RPC settings caused server instantiation to fail. " + "Please check RPC settings in config file.");
        }
        rpcServer.start();
    }
    /*
         * This is a hack, but used to let us pass zmqThread into thread
         * Shutdown hook for Ctrl+C
         */
    class ShutdownThreadHolder {

        private final Thread zmqThread;

        private final EquihashMiner miner;

        private final ProtocolProcessor pp;

        private final RpcServer rpc;

        private ShutdownThreadHolder(Thread zmqThread, EquihashMiner nm, ProtocolProcessor pp, RpcServer rpc) {
            this.zmqThread = zmqThread;
            this.miner = nm;
            this.pp = pp;
            this.rpc = rpc;
        }
    }
    ShutdownThreadHolder holder = new ShutdownThreadHolder(zmqThread, nm, processor, rpcServer);
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        genLog.info("Starting shutdown process...");
        if (holder.rpc != null) {
            genLog.info("Shutting down RpcServer");
            holder.rpc.stop();
            genLog.info("Shutdown RpcServer ... Done!");
        }
        if (holder.pp != null) {
            genLog.info("Shutting down zmq ProtocolProcessor");
            try {
                holder.pp.shutdown();
                genLog.info("Shutdown zmq ProtocolProcessor... Done!");
            } catch (InterruptedException e) {
                genLog.info("Shutdown zmq ProtocolProcessor failed! {}", e.getMessage());
                Thread.currentThread().interrupt();
            }
        }
        if (holder.zmqThread != null) {
            genLog.info("Shutting down zmq thread");
            try {
                holder.zmqThread.interrupt();
                genLog.info("Shutdown zmq thread... Done!");
            } catch (Exception e) {
                genLog.info("Shutdown zmq thread failed! {}", e.getMessage());
                Thread.currentThread().interrupt();
            }
        }
        if (holder.miner != null) {
            genLog.info("Shutting down sealer");
            holder.miner.stopMining();
            holder.miner.shutdown();
            genLog.info("Shutdown sealer... Done!");
        }
        genLog.info("Shutting down the AionHub...");
        ac.getAionHub().close();
        genLog.info("Shutting down the Aion Virtual Machine...");
        shutdownAvm();
        genLog.info("---------------------------------------------");
        genLog.info("| Aion kernel graceful shutdown successful! |");
        genLog.info("---------------------------------------------");
    }, "shutdown"));
}
Also used : NanoRpcServer(org.aion.api.server.http.nano.NanoRpcServer) ReturnType(org.aion.zero.impl.cli.Cli.ReturnType) Date(java.util.Date) CfgApiZmq(org.aion.zero.impl.config.CfgApiZmq) RpcServer(org.aion.api.server.http.RpcServer) Cli(org.aion.zero.impl.cli.Cli) Path(java.nio.file.Path) DateFormat(java.text.DateFormat) Network(org.aion.zero.impl.config.Network) PosixFilePermission(java.nio.file.attribute.PosixFilePermission) ECKeyFac(org.aion.crypto.ECKeyFac) RpcServerVendor(org.aion.api.server.http.RpcServerVendor) TimeZone(java.util.TimeZone) ApiAion0(org.aion.api.server.pb.ApiAion0) Keystore(org.aion.zero.impl.keystore.Keystore) Set(java.util.Set) FileAttribute(java.nio.file.attribute.FileAttribute) ServiceLoader(java.util.ServiceLoader) HashUtil(org.aion.crypto.HashUtil) AionFactory(org.aion.zero.impl.blockchain.AionFactory) EquihashMiner(org.aion.equihash.EquihashMiner) List(java.util.List) AvmProvider(org.aion.zero.impl.vm.avm.AvmProvider) LogEnum(org.aion.log.LogEnum) BLAKE2B_256(org.aion.crypto.HashUtil.H256Type.BLAKE2B_256) AvmVersion(org.aion.avm.stub.AvmVersion) CfgAion(org.aion.zero.impl.config.CfgAion) CfgApiRpc(org.aion.zero.impl.config.CfgApiRpc) NativeLibrary(org.aion.utils.NativeLibrary) SystemExitCodes(org.aion.zero.impl.SystemExitCodes) SimpleDateFormat(java.text.SimpleDateFormat) ED25519(org.aion.crypto.ECKeyFac.ECKeyType.ED25519) AccountManager(org.aion.api.server.account.AccountManager) PosixFilePermissions(java.nio.file.attribute.PosixFilePermissions) HdlrZmq(org.aion.api.server.zmq.HdlrZmq) BlockchainCallbackForApiServer(org.aion.api.server.BlockchainCallbackForApiServer) IAionChain(org.aion.zero.impl.blockchain.IAionChain) CfgSsl(org.aion.zero.impl.config.CfgSsl) Console(java.io.Console) ZMQ(org.zeromq.ZMQ) EventMgrModule(org.aion.evtmgr.EventMgrModule) AionLoggerFactory(org.aion.log.AionLoggerFactory) Properties(java.util.Properties) IHdlr(org.aion.api.server.pb.IHdlr) Logger(org.slf4j.Logger) Compiler(org.aion.solidity.Compiler) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) KERNEL_VERSION(org.aion.zero.impl.Version.KERNEL_VERSION) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ProtocolProcessor(org.aion.api.server.zmq.ProtocolProcessor) Paths(java.nio.file.Paths) RpcServerBuilder(org.aion.api.server.http.RpcServerBuilder) UndertowRpcServer(org.aion.api.server.http.undertow.UndertowRpcServer) Cli(org.aion.zero.impl.cli.Cli) CfgApiRpc(org.aion.zero.impl.config.CfgApiRpc) RpcServerBuilder(org.aion.api.server.http.RpcServerBuilder) CfgSsl(org.aion.zero.impl.config.CfgSsl) UndertowRpcServer(org.aion.api.server.http.undertow.UndertowRpcServer) Properties(java.util.Properties) Logger(org.slf4j.Logger) IHdlr(org.aion.api.server.pb.IHdlr) HdlrZmq(org.aion.api.server.zmq.HdlrZmq) RpcServerBuilder(org.aion.api.server.http.RpcServerBuilder) EquihashMiner(org.aion.equihash.EquihashMiner) NanoRpcServer(org.aion.api.server.http.nano.NanoRpcServer) IAionChain(org.aion.zero.impl.blockchain.IAionChain) BlockchainCallbackForApiServer(org.aion.api.server.BlockchainCallbackForApiServer) IOException(java.io.IOException) ReturnType(org.aion.zero.impl.cli.Cli.ReturnType) IOException(java.io.IOException) CfgAion(org.aion.zero.impl.config.CfgAion) ApiAion0(org.aion.api.server.pb.ApiAion0) NanoRpcServer(org.aion.api.server.http.nano.NanoRpcServer) RpcServer(org.aion.api.server.http.RpcServer) UndertowRpcServer(org.aion.api.server.http.undertow.UndertowRpcServer) AccountManager(org.aion.api.server.account.AccountManager) ProtocolProcessor(org.aion.api.server.zmq.ProtocolProcessor) RpcServerVendor(org.aion.api.server.http.RpcServerVendor)

Aggregations

Console (java.io.Console)1 File (java.io.File)1 FileOutputStream (java.io.FileOutputStream)1 IOException (java.io.IOException)1 Path (java.nio.file.Path)1 Paths (java.nio.file.Paths)1 FileAttribute (java.nio.file.attribute.FileAttribute)1 PosixFilePermission (java.nio.file.attribute.PosixFilePermission)1 PosixFilePermissions (java.nio.file.attribute.PosixFilePermissions)1 DateFormat (java.text.DateFormat)1 SimpleDateFormat (java.text.SimpleDateFormat)1 Date (java.util.Date)1 List (java.util.List)1 Properties (java.util.Properties)1 ServiceLoader (java.util.ServiceLoader)1 Set (java.util.Set)1 TimeZone (java.util.TimeZone)1 TimeUnit (java.util.concurrent.TimeUnit)1 Consumer (java.util.function.Consumer)1 BlockchainCallbackForApiServer (org.aion.api.server.BlockchainCallbackForApiServer)1