/// <summary>
        ///      Gets config of network at height.
        /// </summary>
        /// <param name="height"></param>
        /// <returns></returns>
        public IObservable <BlockchainConfig> GetBlockConfiguration(ulong height)
        {
            var route = $"{BasePath}/config/{height}";

            return(Observable.FromAsync(async ar => await route.GetJsonAsync <NetworkConfigDTO>())
                   .Select(i => BlockchainConfig.FromDto(i)));
        }
        private void GetBlockCount(BlockchainNode node)
        {
            if (node.NodeState.NodeOperationState.State != ProcessState.Running)
            {
                return;
            }

            BlockchainNodeConfig config = BlockchainConfig.GetNodeConfig(node.NodeConfig.NodeConfigFullName);
            int apiPort = config.GetApiPort();

            node.NodeState.NodeOperationState.BlockHeight = BufferedRequestCaller.GetRpcResult <int>(RequestType.RpcGetBlockCount, node.NodeEndpoint.FullNodeName, apiPort);
        }
Пример #3
0
 public Config(NetworkConfig network, GenesisConfig genesis, RpcConfig rpc, VaultConfig vault,
               StorageConfig storage, BlockchainConfig blockchain, HardforkConfig hardfork, VersionConfig version,
               CacheConfig cache)
 {
     Network       = network;
     Genesis       = genesis;
     Rpc           = rpc;
     Vault         = vault;
     Storage       = storage;
     Blockchain    = blockchain;
     Hardfork      = hardfork;
     ConfigVersion = version;
     Cache         = cache;
 }
        private void StopNode()
        {
            BlockchainNode node = Client.Session.ManagedNodes.GetNode(ClientAction.FullNodeName);

            if (node == null)
            {
                logger.Error($"Cannot find node {ClientAction.FullNodeName}");
                return;
            }

            BlockchainNodeConfig config = BlockchainConfig.GetNodeConfig(node.NodeConfig.NodeConfigFullName);
            int apiPort = config.GetApiPort();

            BufferedRequestCaller.GetApiResult <string>(RequestType.ApiNodeShutdown, ClientAction.FullNodeName, apiPort);
        }
        private void GetNodeStatus(BlockchainNode node)
        {
            BlockchainNodeConfig config = BlockchainConfig.GetNodeConfig(node.NodeConfig.NodeConfigFullName);
            int apiPort = config.GetApiPort();

            NodeStatus nodeStatus = BufferedRequestCaller.GetApiResult <NodeStatus>(RequestType.ApiNodeStatus, node.NodeEndpoint.FullNodeName, apiPort);

            if (nodeStatus == null)
            {
                node.NodeState.NodeOperationState.State = ProcessState.Stopped;
                return;
            }

            node.NodeState.NodeOperationState.State = ProcessState.Running;

            node.NodeState.NodeOperationState.AgentName       = nodeStatus.Agent;
            node.NodeState.NodeOperationState.Version         = nodeStatus.Version;
            node.NodeState.NodeOperationState.Network         = nodeStatus.Network;
            node.NodeState.NodeOperationState.ConsensusHeight = nodeStatus.ConsensusHeight;

            node.NodeState.NodeOperationState.Peers.Clear();
            foreach (Peer inboundPeer in nodeStatus.InboundPeers)
            {
                ConnectionPeer peer = new ConnectionPeer();
                peer.PeerType             = PeerType.Inbound;
                peer.RemoteSocketEndpoint = inboundPeer.RemoteSocketEndpoint;
                peer.TipHeight            = inboundPeer.TipHeight;
                peer.Version = inboundPeer.Version;
                node.NodeState.NodeOperationState.Peers.Add(peer);
            }
            foreach (Peer outboundPeer in nodeStatus.OutboundPeers)
            {
                ConnectionPeer peer = new ConnectionPeer();
                peer.PeerType             = PeerType.Inbound;
                peer.RemoteSocketEndpoint = outboundPeer.RemoteSocketEndpoint;
                peer.TipHeight            = outboundPeer.TipHeight;
                peer.Version = outboundPeer.Version;
                node.NodeState.NodeOperationState.Peers.Add(peer);
            }

            node.NodeState.NodeOperationState.DataDirectory = nodeStatus.DataDirectoryPath;
            node.NodeState.NodeOperationState.Uptime        = nodeStatus.RunningTime;

            int maxInboundTipHeight  = nodeStatus.InboundPeers.Any() ? nodeStatus.InboundPeers.Max(p => p.TipHeight) : 0;
            int maxOutboundTipHeight = nodeStatus.OutboundPeers.Any() ? nodeStatus.OutboundPeers.Max(p => p.TipHeight) : 0;

            node.NodeState.NodeOperationState.NetworkHeight = Math.Max(maxInboundTipHeight, maxOutboundTipHeight);
        }
        private static T LoadJson <T>(string filename)
        {
            try
            {
                var fullfilename = $"{AssemblyDirectory}/{filename}";
                if (File.Exists(fullfilename))
                {
                    return(JsonConvert.DeserializeObject <T>(File.ReadAllText(fullfilename)));
                }

                if (typeof(T) == typeof(Config))
                {
                    var config = new Config
                    {
                        LoggingType   = LoggingType.File,
                        LoggingServer = "http://195.48.9.135:5341",
                        BuildMode     = BuildMode.Prod,
                        Hostname      = "195.48.9.208",
                        DaemonPort    = 8095,
                        WalletPort    = 8096,
                        Api           = "/rpc",
                        Version       = "2.0"
                    };
                    File.WriteAllText(fullfilename, JsonConvert.SerializeObject(config));
                }
                else if (typeof(T) == typeof(BlockchainConfig))
                {
                    var blockchainconfig = new BlockchainConfig
                    {
                        Account      = AccountOwner.Sender,
                        Index        = 0,
                        IsoTimeStamp = DateTime.UtcNow,
                        SearchType   = SearchType.BySender,
                        Start        = StartBy.Index
                    };
                    File.WriteAllText(fullfilename, JsonConvert.SerializeObject(blockchainconfig));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            return(default(T));
        }
Пример #7
0
        public void Setup()
        {
            _genesisBlock   = Build.A.Block.WithNumber(0).TestObject;
            _blockTree      = Build.A.BlockTree(_genesisBlock).OfChainLength(1).TestObject;
            _stateDb        = new MemDb();
            _receiptsDb     = new MemDb();
            _receiptStorage = Substitute.For <IReceiptStorage>();
            BlockchainConfig quickConfig = new BlockchainConfig();

            quickConfig.SyncTimerInterval = 100;

            IHeaderValidator      headerValidator      = Build.A.HeaderValidator.ThatAlwaysReturnsTrue.TestObject;
            IBlockValidator       blockValidator       = Build.A.BlockValidator.ThatAlwaysReturnsTrue.TestObject;
            ITransactionValidator transactionValidator = Build.A.TransactionValidator.ThatAlwaysReturnsTrue.TestObject;

            _manager = new QueueBasedSyncManager(_stateDb, _blockTree, blockValidator, headerValidator, transactionValidator, NullLogManager.Instance, quickConfig, new PerfService(NullLogManager.Instance), _receiptStorage);
        }
        private void GetMemoryPoolTransactions(BlockchainNode node)
        {
            if (node.NodeState.NodeOperationState.State != ProcessState.Running)
            {
                return;
            }

            BlockchainNodeConfig config = BlockchainConfig.GetNodeConfig(node.NodeConfig.NodeConfigFullName);
            int apiPort = config.GetApiPort();

            string[] mempoolTransactions = BufferedRequestCaller.GetRpcResult <string[]>(RequestType.RpcGetRawMempool, node.NodeEndpoint.FullNodeName, apiPort);
            if (mempoolTransactions == null)
            {
                node.NodeState.NodeOperationState.MempoolTransactionCount = 0;
                return;
            }

            node.NodeState.NodeOperationState.MempoolTransactionCount = mempoolTransactions != null ? mempoolTransactions.Length : 0;
        }
Пример #9
0
        public static void CloudKeygen(int n, int f, IEnumerable <string> ips, ushort basePort, ushort target, ulong chainId, ulong cycleDuration, ulong validatorsCount, string networkName,
                                       string feedAddress, string feedBalance, string stakeAmount, IEnumerable <ulong> hardforks)
        {
            if (n <= 3 * f)
            {
                throw new Exception("N must be >= 3 * F + 1");
            }
            var tpkeKeyGen = new Crypto.TPKE.TrustedKeyGen(n, f);
            var tpkePubKey = tpkeKeyGen.GetPubKey();

            var sigKeyGen  = new Crypto.ThresholdSignature.TrustedKeyGen(n, f);
            var privShares = sigKeyGen.GetPrivateShares().ToArray();
            var pubShares  = sigKeyGen.GetPrivateShares()
                             .Select(s => s.GetPublicKeyShare())
                             .Select(s => s.ToHex())
                             .ToArray();

            var ecdsaPrivateKeys = new string[n];
            var ecdsaPublicKeys  = new string[n];
            var addresses        = new string[n];
            var crypto           = CryptoProvider.GetCrypto();

            for (var i = 0; i < n; ++i)
            {
                ecdsaPrivateKeys[i] = crypto.GenerateRandomBytes(32).ToHex(false);
                ecdsaPublicKeys[i]  = crypto.ComputePublicKey(ecdsaPrivateKeys[i].HexToBytes(), true).ToHex(false);
                addresses[i]        = ecdsaPrivateKeys[i].HexToBytes().ToPrivateKey().GetPublicKey().GetAddress().ToHex();
            }

            var hubPublicKeys            = new string[n];
            var serializedHubPrivateKeys = new string[n];

            for (var i = 0; i < n; ++i)
            {
                (serializedHubPrivateKeys[i], hubPublicKeys[i]) = PrivateWallet.GenerateHubKey();
            }

            var bootstraps = ips
                             .Zip(hubPublicKeys, (ip, id) => $"{id}@{ip}")
                             .Select((x, i) => $"{x}:{41011 + i}")
                             .ToArray();

            var peers = ecdsaPublicKeys.ToArray();

            for (var i = 0; i < n; ++i)
            {
                var net = new NetworkConfig
                {
                    Peers              = peers,
                    MaxPeers           = 100,
                    ForceIPv6          = false,
                    BootstrapAddresses = bootstraps,
                    HubLogLevel        = "Trace",
                    HubMetricsPort     = basePort + 2,
                    NetworkName        = networkName,
                    ChainId            = (int)chainId,
                    CycleDuration      = cycleDuration,
                    ValidatorsCount    = validatorsCount,
                };
                var genesis = new GenesisConfig(tpkePubKey.ToHex(), "5.000000000000000000", "0.000000100000000000")
                {
                    Balances = new Dictionary <string, string>
                    {
                        {
                            feedAddress, feedBalance
                        }
                    },
                    Validators = Enumerable.Range(0, n).Select(j => new ValidatorInfo(
                                                                   ecdsaPublicKeys[j], pubShares[j], feedAddress, stakeAmount
                                                                   )).ToList()
                };
                for (var j = 0; j < n; ++j)
                {
                    genesis.Balances[addresses[j]] = "100";
                }

                var secp256K1  = new Secp256k1();
                var privateKey = new byte[32];
                var rnd        = System.Security.Cryptography.RandomNumberGenerator.Create();
                do
                {
                    rnd.GetBytes(privateKey);
                }while (!secp256K1.SecretKeyVerify(privateKey));

                var privateKeyHex = privateKey.ToHex();
                var publicKey     = new byte[64];
                Debug.Assert(secp256K1.PublicKeyCreate(publicKey, privateKey));
                var publicKeyHex = publicKey.ToHex();

                System.Console.WriteLine($"Loop {i + 1:D2}: private key [{privateKeyHex}] associated with public key [{publicKeyHex}]");

                var rpc = new RpcConfig
                {
                    Hosts       = new[] { "+" },
                    Port        = basePort,
                    MetricsPort = (ushort)(basePort + 1),
                    // ApiKey = "0x2e917846fe7487a4ea3a765473a3fc9b2d9227a4d312bc77fb9de357cf73d7e52b771d537394336e9eb2cb4838138f668f4bd7d8cf7e04d9242a42c71b99f166",
                    ApiKey = publicKeyHex
                };
                var walletPath = "wallet.json";
                var vault      = new VaultConfig
                {
                    Path     = walletPath,
                    Password = getRandomPassword()
                };
                var storage = new StorageConfig
                {
                    Path     = "ChainLachain",
                    Provider = "RocksDB",
                };
                var blockchain = new BlockchainConfig
                {
                    TargetBlockTime = target,
                };
                List <ulong> hardforkHeights = hardforks.ToList();
                var          hardfork        = new HardforkConfig
                {
                    Hardfork_1 = hardforkHeights[0],
                    Hardfork_2 = hardforkHeights[1],
                    Hardfork_3 = hardforkHeights[2],
                    Hardfork_4 = hardforkHeights[3],
                };
                var version = new VersionConfig
                {
                    Version = 2
                };

                var blockHeight = new CacheOptions
                {
                    SizeLimit = 100
                };

                var cache = new CacheConfig
                {
                    BlockHeight = blockHeight
                };

                var config = new Config(net, genesis, rpc, vault, storage, blockchain, hardfork, version, cache);
                File.WriteAllText($"config{i + 1:D2}.json", JsonConvert.SerializeObject(config, Formatting.Indented));
                GenWallet(
                    $"wallet{i + 1:D2}.json",
                    ecdsaPrivateKeys[i],
                    serializedHubPrivateKeys[i],
                    tpkeKeyGen.GetPrivKey(i).ToHex(),
                    privShares[i].ToHex(),
                    vault.Password
                    );
            }

            var tpkePrivKeys = string.Join(
                ", ",
                Enumerable.Range(0, n)
                .Select(idx => tpkeKeyGen.GetPrivKey(idx))
                .Select(x => $"\"{x.ToHex()}\""));
            var tsKeys = string.Join(
                ", ",
                sigKeyGen.GetPrivateShares()
                .Select(x => $"(\"{x.GetPublicKeyShare().ToHex()}\", \"{x.ToHex()}\")")
                );

            System.Console.WriteLine(
                $"{n}: " + "{" +
                "  \"tpke\": (" +
                $"    \"{tpkePubKey.ToHex()}\"," +
                $"    [{tpkePrivKeys}]" +
                "  )," +
                $"  \"ts\": [{tsKeys}]," +
                "}");
            System.Console.WriteLine(
                string.Join(", ", ecdsaPrivateKeys.Zip(ecdsaPublicKeys).Zip(addresses)
                            .Select(t => $"(\"{t.First.Second}\", \"{t.First.First}\", \"{t.Second}\")"))
                );
        }