Example #1
0
File: Peer.cs Project: wyk125/AElf
        /// <summary>
        /// This method sends authentification information to the distant peer and
        /// start the authentification timer.
        /// </summary>
        /// <returns></returns>
        private void StartAuthentification()
        {
            var nodeInfo = new NodeData {
                Port = _port
            };

            ECSigner    signer = new ECSigner();
            ECSignature sig    = signer.Sign(_nodeKey, nodeInfo.ToByteArray());

            var nd = new Handshake
            {
                NodeInfo  = nodeInfo,
                PublicKey = ByteString.CopyFrom(_nodeKey.GetEncodedPublicKey()),
                Height    = CurrentHeight,
                Version   = GlobalConfig.ProtocolVersion,
                R         = ByteString.CopyFrom(sig.R),
                S         = ByteString.CopyFrom(sig.S)
            };

            byte[] packet = nd.ToByteArray();

            _logger?.Trace($"Sending authentification : {{ port: {nd.NodeInfo.Port}, addr: {nd.PublicKey.ToByteArray().ToHex()} }}");

            _messageWriter.EnqueueMessage(new Message {
                Type = (int)MessageType.Auth, HasId = false, Length = packet.Length, Payload = packet
            });

            StartAuthTimer();
        }
Example #2
0
        private bool WriteKeyPair(ECKeyPair keyPair, string password)
        {
            if (keyPair?.PrivateKey == null || keyPair.PublicKey == null)
            {
                throw new InvalidKeyPairException("Invalid keypair (null reference).", null);
            }

            if (string.IsNullOrEmpty(password))
            {
                // Why here we can just invoke Console.WriteLine? should we use Logger?
                Console.WriteLine("Invalid password.");
                return(false);
            }

            // Ensure path exists
            GetOrCreateKeystoreDir();

            string fullPath = null;

            try
            {
                Address.FromRawBytes(keyPair.GetEncodedPublicKey());
                var address = Address.FromRawBytes(keyPair.GetEncodedPublicKey()).Value.ToByteArray().ToHex();
//                var address = keyPair.GetAddressHex();
                fullPath = GetKeyFileFullPath(address);
            }
            catch (Exception e)
            {
                Console.WriteLine("Could not calculate the address from the keypair.", e);
                return(false);
            }

            var akp = new AsymmetricCipherKeyPair(keyPair.PublicKey, keyPair.PrivateKey);

            using (var writer = File.CreateText(fullPath))
            {
                var pw = new PemWriter(writer);
                pw.WriteObject(akp, _algo, password.ToCharArray(), _random);
                pw.Writer.Close();
            }

            return(true);
        }
Example #3
0
        public void SignatureDecoding_Decode_ShouldBeEqualToOriginal()
        {
            // GenerareceivedKeyte the key pair
            ECKeyPair keyPair = new KeyPairGenerator().Generate();

            // Get its byte array representation
            byte[] initialPublicKey = keyPair.GetEncodedPublicKey(compressed: true);

            // Reconstruct it and check if the key is the same
            ECKeyPair recipientKeyPair = ECKeyPair.FromPublicKey(initialPublicKey);

            byte[] receivedKey = recipientKeyPair.GetEncodedPublicKey(true);

            Assert.True(receivedKey.SequenceEqual(initialPublicKey));
        }
Example #4
0
File: Miner.cs Project: wyk125/AElf
        /// <summary>
        /// Generate a system tx for parent chain block info and broadcast it.
        /// </summary>
        /// <returns></returns>
        private async Task GenerateTransactionWithParentChainBlockInfo()
        {
            var parentChainBlockInfo = GetParentChainBlockInfo();

            if (parentChainBlockInfo == null)
            {
                return;
            }
            try
            {
                var bn = await _blockChain.GetCurrentBlockHeightAsync();

                bn = bn > 4 ? bn - 4 : 0;
                var bh     = bn == 0 ? Hash.Genesis : (await _blockChain.GetHeaderByHeightAsync(bn)).GetHash();
                var bhPref = bh.Value.Where((x, i) => i < 4).ToArray();
                var tx     = new Transaction
                {
                    From = _keyPair.GetAddress(),
                    To   = AddressHelpers.GetSystemContractAddress(Config.ChainId,
                                                                   SmartContractType.SideChainContract.ToString()),
                    RefBlockNumber = bn,
                    RefBlockPrefix = ByteString.CopyFrom(bhPref),
                    MethodName     = "WriteParentChainBlockInfo",
                    Sig            = new Signature
                    {
                        P = ByteString.CopyFrom(_keyPair.GetEncodedPublicKey())
                    },
                    Type   = TransactionType.CrossChainBlockInfoTransaction,
                    Params = ByteString.CopyFrom(ParamsPacker.Pack(parentChainBlockInfo)),
                    Time   = Timestamp.FromDateTime(DateTime.UtcNow)
                };
                // sign tx
                var signature = new ECSigner().Sign(_keyPair, tx.GetHash().DumpByteArray());
                tx.Sig.R = ByteString.CopyFrom(signature.R);
                tx.Sig.S = ByteString.CopyFrom(signature.S);

                await InsertTransactionToPool(tx);

                _logger?.Trace($"Generated Cross chain info transaction {tx.GetHash()}");
            }
            catch (Exception e)
            {
                _logger?.Error(e, "PCB transaction generation failed.");
            }
        }
Example #5
0
File: Miner.cs Project: wyk125/AElf
 /// <summary>
 /// Start mining
 /// init clients to side chain node
 /// </summary>
 public void Init()
 {
     _keyPair         = NodeConfig.Instance.ECKeyPair;
     _producerAddress = Address.FromRawBytes(_keyPair.GetEncodedPublicKey());
     _blockChain      = _chainService.GetBlockChain(Config.ChainId);
 }