示例#1
0
        public (PrivateKey PrivateKey, Result Result) GenerateKey(SecureString password)
        {
            var privateKey = _privateKeyGenerator.Generate();
            var result     = StoreKey(privateKey, password);

            return(result.ResultType == ResultType.Success ? (privateKey, result) : (null, result));
        }
示例#2
0
        public byte[] Encrypt(PublicKey recipientPublicKey, byte[] plaintext, byte[] macData)
        {
            byte[]     iv = _cryptoRandom.GenerateRandomBytes(KeySize / 8);
            PrivateKey ephemeralPrivateKey = _keyGenerator.Generate();

            IIesEngine iesEngine = MakeIesEngine(true, recipientPublicKey, ephemeralPrivateKey, iv);

            try
            {
                byte[]       cipher       = iesEngine.ProcessBlock(plaintext, 0, plaintext.Length, macData);
                MemoryStream memoryStream = new MemoryStream();
                memoryStream.Write(ephemeralPrivateKey.PublicKey.PrefixedBytes, 0, ephemeralPrivateKey.PublicKey.PrefixedBytes.Length);
                memoryStream.Write(iv, 0, iv.Length);
                memoryStream.Write(cipher, 0, cipher.Length);
                return(memoryStream.ToArray());
            }
            catch (InvalidCipherTextException)
            {
                throw;
            }
            catch (IOException)
            {
                throw;
            }
        }
示例#3
0
            public string GenerateEnode(PrivateKeyGenerator generator = null)
            {
                generator ??= new PrivateKeyGenerator();
                string enode = $"enode://{generator.Generate().PublicKey.ToString(false)}@52.141.78.53:30303";

                return(enode);
            }
示例#4
0
        public Address NewAccount(SecureString passphrase)
        {
            using var privateKeyGenerator = new PrivateKeyGenerator();
            PrivateKey key = privateKeyGenerator.Generate();

            _keys.Add(key.Address, key);
            _isUnlocked.Add(key.Address, true);
            _passwords.Add(key.Address, passphrase.Unsecure());
            return(key.Address);
        }
示例#5
0
            public NodeBuilder WithNode(int id)
            {
                var peer = Substitute.For <INdmProviderPeer>();

                peer.NodeId.Returns(PrivateKeyGenerator.Generate().PublicKey);
                var node = new TestConsumerNode(id, new ConsumerNode(peer));

                _consumer._nodes.Add(node);

                return(new NodeBuilder(this, _depositId, node));
            }
示例#6
0
        public (PrivateKey PrivateKey, Result Result) GenerateKey(SecureString password)
        {
            if (!password.IsReadOnly())
            {
                throw new InvalidOperationException("Cannot work with password that is not readonly");
            }

            var privateKey = _privateKeyGenerator.Generate();
            var result     = StoreKey(privateKey, password);

            return(result.ResultType == ResultType.Success ? (privateKey, result) : (null, result));
        }
示例#7
0
        public void Initialize()
        {
            NetworkNodeDecoder.Init();
            _timestamp             = new Timestamp();
            _logManager            = new OneLoggerLogManager(new SimpleConsoleLogger());
            _configurationProvider = new ConfigProvider();
            INetworkConfig networkConfig = _configurationProvider.GetConfig <INetworkConfig>();

            networkConfig.DbBasePath = Path.Combine(Path.GetTempPath(), "PeerManagerTests");
            networkConfig.IsActivePeerTimerEnabled      = false;
            networkConfig.IsDiscoveryNodesPersistenceOn = false;
            networkConfig.IsPeersPersistenceOn          = false;

            if (!Directory.Exists(networkConfig.DbBasePath))
            {
                Directory.CreateDirectory(networkConfig.DbBasePath);
            }

            var   syncManager  = Substitute.For <ISynchronizationManager>();
            Block genesisBlock = Build.A.Block.Genesis.TestObject;

            syncManager.Head.Returns(genesisBlock.Header);
            syncManager.Genesis.Returns(genesisBlock.Header);

            _nodeFactory = new NodeFactory(LimboLogs.Instance);
            _localPeer   = new TestRlpxPeer();
            var keyProvider = new PrivateKeyGenerator(new CryptoRandom());
            var key         = keyProvider.Generate().PublicKey;

            _synchronizationManager = Substitute.For <ISynchronizationManager>();

            IStatsConfig statsConfig = _configurationProvider.GetConfig <IStatsConfig>();
            var          nodeTable   = new NodeTable(_nodeFactory, Substitute.For <IKeyStore>(), new NodeDistanceCalculator(networkConfig), networkConfig, _logManager);

            nodeTable.Initialize(new NodeId(key));

            _discoveryManager = new DiscoveryManager(new NodeLifecycleManagerFactory(_nodeFactory, nodeTable, new DiscoveryMessageFactory(networkConfig, _timestamp), Substitute.For <IEvictionManager>(), new NodeStatsProvider(_configurationProvider.GetConfig <IStatsConfig>(), _nodeFactory, _logManager, true), networkConfig, _logManager), _nodeFactory, nodeTable, new NetworkStorage("test", networkConfig, _logManager, new PerfService(_logManager)), networkConfig, _logManager);
            _discoveryManager.MessageSender = Substitute.For <IMessageSender>();
            _transactionPool = NullTransactionPool.Instance;
            _blockTree       = Substitute.For <IBlockTree>();
            var app = new DiscoveryApp(new NodesLocator(nodeTable, _discoveryManager, _configurationProvider, _logManager), _discoveryManager, _nodeFactory, nodeTable, Substitute.For <IMessageSerializationService>(), new CryptoRandom(), Substitute.For <INetworkStorage>(), networkConfig, _logManager, new PerfService(_logManager));

            app.Initialize(key);

            var sessionLogger = new PeerSessionLogger(_logManager, _configurationProvider, new PerfService(_logManager));

            sessionLogger.Init(Path.GetTempPath());
            var networkStorage = new NetworkStorage("test", networkConfig, _logManager, new PerfService(_logManager));

            _peerManager = new PeerManager(_localPeer, app, _synchronizationManager, new NodeStatsProvider(statsConfig, _nodeFactory, _logManager, true), networkStorage, _nodeFactory, _configurationProvider, new PerfService(_logManager), _transactionPool, _logManager, sessionLogger);
            _peerManager.Init(true);
        }
示例#8
0
        private List <NetworkNode> CreateNodes(int count)
        {
            var nodes = new List <NetworkNode>();

            for (int i = 0; i < count; i++)
            {
                var         generator = new PrivateKeyGenerator();
                string      enode     = $"enode://{generator.Generate().PublicKey.ToString(false)}@52.141.78.53:30303";
                NetworkNode node      = new NetworkNode(enode);
                nodes.Add(node);
            }

            return(nodes);
        }
示例#9
0
        private void SetupPersistedPeers(int count)
        {
            List <NetworkNode> nodes = new List <NetworkNode>();

            for (int i = 0; i < count; i++)
            {
                var         generator = new PrivateKeyGenerator();
                string      enode     = $"enode://{generator.Generate().PublicKey.ToString(false)}@52.141.78.53:30303";
                NetworkNode node      = new NetworkNode(enode);
                nodes.Add(node);
            }

            _storage.UpdateNodes(nodes);
        }
示例#10
0
        private void SetupPersistedPeers(int count)
        {
            List <NetworkNode> nodes = new List <NetworkNode>();

            for (int i = 0; i < count; i++)
            {
                var         generator = new PrivateKeyGenerator();
                string      enode     = $"enode://{generator.Generate().PublicKey.ToString(false)}@52.141.78.53:30303";
                NetworkNode node      = new NetworkNode(enode);
                nodes.Add(node);
            }

//            foreach (NetworkNode networkNode in nodes.OrderBy(n => n.NodeId.ToString()).ToArray())
//            {
//                Console.WriteLine(networkNode.NodeId);
//            }

            _storage.UpdateNodes(nodes.ToArray());
        }
示例#11
0
        public ProtectedPrivateKey LoadNodeKey()
        {
            ProtectedPrivateKey LoadKeyFromFile()
            {
                string oldPath = UnsecuredNodeKeyFilePath.GetApplicationResourcePath();
                string newPath = (_config.EnodeKeyFile ?? UnsecuredNodeKeyFilePath).GetApplicationResourcePath(_config.KeyStoreDirectory);

                GenerateKeyIfNeeded(newPath, oldPath);
                using var privateKey = new PrivateKey(_fileSystem.File.ReadAllBytes(newPath));
                return(new ProtectedPrivateKey(privateKey, _cryptoRandom));
            }

            void GenerateKeyIfNeeded(string newFile, string oldFile)
            {
                if (!_fileSystem.File.Exists(newFile))
                {
                    if (_logger.IsInfo)
                    {
                        _logger.Info("Generating private key for the node (no node key in configuration) - stored in plain + key store for JSON RPC unlocking");
                    }
                    using var privateKeyGenerator = new PrivateKeyGenerator(_cryptoRandom);
                    PrivateKey nodeKey           = _fileSystem.File.Exists(oldFile) ? new PrivateKey(_fileSystem.File.ReadAllBytes(oldFile)) : privateKeyGenerator.Generate();
                    var        keyStoreDirectory = _config.KeyStoreDirectory.GetApplicationResourcePath();
                    _fileSystem.Directory.CreateDirectory(keyStoreDirectory);
                    _fileSystem.File.WriteAllBytes(newFile, nodeKey.KeyBytes);
                    SecureString nodeKeyPassword = CreateNodeKeyPassword(8);
                    _keyStore.StoreKey(nodeKey, nodeKeyPassword);
                    if (_logger.IsInfo)
                    {
                        _logger.Info("Store this password for unlocking the node key for JSON RPC - this is not secure - this log message will be in your log files. Use only in DEV contexts.");
                    }
                }
            }

            if (_config.TestNodeKey != null)
            {
                return(new ProtectedPrivateKey(new PrivateKey(_config.TestNodeKey), _cryptoRandom));
            }
            var key = LoadKeyForAccount(_config.EnodeAccount);

            return(key ?? LoadKeyFromFile());
        }
示例#12
0
 public PrivateKeyBuilder()
 {
     TestObject = _generator.Generate();
 }
示例#13
0
        public ProtectedPrivateKey LoadNodeKey()
        {
            // this is not secure at all but this is just the node key, nothing critical so far, will use the key store here later and allow to manage by password when launching the node
            if (_config.TestNodeKey == null)
            {
                string oldPath = UnsecuredNodeKeyFilePath.GetApplicationResourcePath();
                string newPath = UnsecuredNodeKeyFilePath.GetApplicationResourcePath(_config.KeyStoreDirectory);

                if (!File.Exists(newPath))
                {
                    if (_logger.IsInfo)
                    {
                        _logger.Info("Generating private key for the node (no node key in configuration) - stored in plain + key store for JSON RPC unlocking");
                    }
                    using var privateKeyGenerator = new PrivateKeyGenerator(_cryptoRandom);
                    PrivateKey nodeKey           = File.Exists(oldPath) ? new PrivateKey(File.ReadAllBytes(oldPath)) : privateKeyGenerator.Generate();
                    var        keyStoreDirectory = _config.KeyStoreDirectory.GetApplicationResourcePath();
                    Directory.CreateDirectory(keyStoreDirectory);
                    File.WriteAllBytes(newPath, nodeKey.KeyBytes);
                    SecureString nodeKeyPassword = CreateNodeKeyPassword(8);
                    _keyStore.StoreKey(nodeKey, nodeKeyPassword);
                    if (_logger.IsInfo)
                    {
                        _logger.Info("Store this password for unlocking the node key for JSON RPC - this is not secure - this log message will be in your log files. Use only in DEV contexts.");
                    }
                    if (_logger.IsInfo)
                    {
                        _logger.Info(nodeKeyPassword.Unsecure());
                    }
                }

                using var privateKey = new PrivateKey(File.ReadAllBytes(newPath));
                return(new ProtectedPrivateKey(privateKey, _cryptoRandom));
            }

            return(new ProtectedPrivateKey(new PrivateKey(_config.TestNodeKey), _cryptoRandom));
        }
示例#14
0
        public PrivateKey LoadNodeKey()
        {
            if (_config.BlockAuthorAccount != null)
            {
                SecureString password;
                if (_config.BlockAuthorPassword != null)
                {
                    password = new SecureString();
                    foreach (var character in _config.BlockAuthorPassword)
                    {
                        password.AppendChar(character);
                    }

                    password.MakeReadOnly();
                }
                else
                {
                    password = ConsoleUtils.ReadSecret($"Provide password for validator account {_config.BlockAuthorAccount}");
                }

                try
                {
                    (PrivateKey privateKey, Result result) = _keyStore.GetKey(new Address(_config.BlockAuthorAccount), password);
                    if (result == Result.Success)
                    {
                        return(privateKey);
                    }
                    else
                    {
                        if (_logger.IsError)
                        {
                            _logger.Error($"Not able to unlock the key for {_config.BlockAuthorAccount}");
                        }
                        // continue to the other methods
                    }
                }
                catch (Exception e)
                {
                    if (_logger.IsError)
                    {
                        _logger.Error($"Not able to unlock the key for {_config.BlockAuthorAccount}", e);
                    }
                }
            }

            // this is not secure at all but this is just the node key, nothing critical so far, will use the key store here later and allow to manage by password when launching the node
            if (_config.TestNodeKey == null)
            {
                string oldPath = UnsecuredNodeKeyFilePath.GetApplicationResourcePath();
                string newPath = UnsecuredNodeKeyFilePath.GetApplicationResourcePath(_config.KeyStoreDirectory);

                if (!File.Exists(newPath))
                {
                    if (_logger.IsInfo)
                    {
                        _logger.Info("Generating private key for the node (no node key in configuration) - stored in plain + key store for JSON RPC unlocking");
                    }
                    using var privateKeyGenerator = new PrivateKeyGenerator(_cryptoRandom);
                    PrivateKey nodeKey           = File.Exists(oldPath) ? new PrivateKey(File.ReadAllBytes(oldPath)) : privateKeyGenerator.Generate();
                    var        keyStoreDirectory = _config.KeyStoreDirectory.GetApplicationResourcePath();
                    Directory.CreateDirectory(keyStoreDirectory);
                    File.WriteAllBytes(newPath, nodeKey.KeyBytes);
                    SecureString nodeKeyPassword = CreateNodeKeyPassword(8);
                    _keyStore.StoreKey(nodeKey, nodeKeyPassword);
                    if (_logger.IsInfo)
                    {
                        _logger.Info("Store this password for unlocking the node key for JSON RPC - this is not secure - this log message will be in your log files. Use only in DEV contexts.");
                    }
                    if (_logger.IsInfo)
                    {
                        _logger.Info(nodeKeyPassword.Unsecure());
                    }
                }


                return(new PrivateKey(File.ReadAllBytes(newPath)));
            }

            return(new PrivateKey(_config.TestNodeKey));
        }