Example #1
0
 public ClientWorker(ECDSAPublicKey peerPublicKey, IMessageFactory messageFactory, HubConnector hubConnector)
 {
     _messageFactory = messageFactory;
     _hubConnector   = hubConnector;
     PeerPublicKey   = peerPublicKey.EncodeCompressed();
     _worker         = new Thread(Worker);
 }
Example #2
0
        public void VerifyTransaction(TransactionReceipt acceptedTransaction, ECDSAPublicKey publicKey, bool useNewChainId)
        {
            var address = _crypto.ComputeAddress(publicKey.EncodeCompressed()).ToUInt160();

            _publicKeyCache.Add(address, publicKey);
            VerifyTransaction(acceptedTransaction, useNewChainId);
        }
Example #3
0
            /// <summary>
            /// Constructor
            /// </summary>
            /// <param name="hostName">host name</param>
            /// <param name="portNumber">port number</param>
            /// <param name="hostKey">host key</param>
            public SSH2HostKeyInformationProvider(string hostName, int portNumber, PublicKey hostKey)
            {
                HostName   = hostName;
                PortNumber = portNumber;

                _hostKey = hostKey;

                _knownHostsString =
                    new Lazy <string>(
                        () => {
                    // Poderosa known_hosts format
                    return(new StringBuilder()
                           .Append(_hostKey.Algorithm.GetAlgorithmName())
                           .Append(' ')
                           .Append(Encoding.ASCII.GetString(Base64.Encode(_encodedHostKey.Value)))
                           .ToString());
                },
                        false
                        );

                _encodedHostKey =
                    new Lazy <byte[]>(
                        () => {
                    SSH2PayloadImageBuilder image = new SSH2PayloadImageBuilder(0x10000);
                    image.WriteString(_hostKey.Algorithm.GetAlgorithmName());
                    if (_hostKey is RSAPublicKey)
                    {
                        RSAPublicKey rsa = (RSAPublicKey)_hostKey;
                        image.WriteBigInteger(rsa.Exponent);
                        image.WriteBigInteger(rsa.Modulus);
                    }
                    else if (_hostKey is DSAPublicKey)
                    {
                        DSAPublicKey dsa = (DSAPublicKey)_hostKey;
                        image.WriteBigInteger(dsa.P);
                        image.WriteBigInteger(dsa.Q);
                        image.WriteBigInteger(dsa.G);
                        image.WriteBigInteger(dsa.Y);
                    }
                    else if (_hostKey is ECDSAPublicKey)
                    {
                        ECDSAPublicKey ec = (ECDSAPublicKey)_hostKey;
                        image.WriteString(ec.CurveName);
                        image.WriteAsString(ec.ToOctetString());
                    }
                    else if (_hostKey is EDDSAPublicKey)
                    {
                        EDDSAPublicKey ed = (EDDSAPublicKey)_hostKey;
                        image.WriteAsString(ed.Bytes);
                    }
                    else
                    {
                        throw new SSHException("Host key algorithm is unsupported");
                    }
                    return(image.GetBytes());
                },
                        false
                        );
            }
Example #4
0
 public int GetValidatorIndex(ECDSAPublicKey publicKey, long afterBlock)
 {
     return(GetValidatorsPublicKeys(afterBlock)
            .Select((key, index) => new { key, index })
            .Where(arg => publicKey.Equals(arg.key))
            .Select(arg => arg.index)
            .First());
 }
Example #5
0
 public static byte[] EncodeCompressed(this ECDSAPublicKey key)
 {
     if (key.Buffer.Length != PublicKeyLength)
     {
         throw new InvalidOperationException("Corrupted public key");
     }
     return(key.Buffer.ToByteArray());
 }
Example #6
0
 public int GetValidatorIndex(ECDSAPublicKey publicKey)
 {
     return(EcdsaPublicKeySet
            .Select((key, index) => new { key, index })
            .Where(arg => publicKey.Equals(arg.key))
            .Select(arg => arg.index)
            .DefaultIfEmpty(-1)
            .First());
 }
Example #7
0
        public static ValidatorCredentials FromBytes(ReadOnlySpan <byte> bytes)
        {
            var decoded   = (RLPCollection)RLP.Decode(bytes.ToArray());
            var publicKey = new ECDSAPublicKey {
                Buffer = ByteString.CopyFrom(decoded[0].RLPData)
            };
            var tsKey = decoded[1].RLPData;

            return(new ValidatorCredentials(publicKey, tsKey));
        }
Example #8
0
 public OperatingError VerifySignature(TransactionReceipt transaction, ECDSAPublicKey publicKey, bool useNewChainId)
 {
     if (!_verifiedTransactions.ContainsKey(transaction.Hash))
     {
         return(_transactionVerifier.VerifyTransactionImmediately(transaction, publicKey, useNewChainId)
             ? OperatingError.Ok
             : OperatingError.InvalidSignature);
     }
     _verifiedTransactions.TryRemove(transaction.Hash, out _);
     return(OperatingError.Ok);
 }
Example #9
0
 public int GetSenderByPublicKey(ECDSAPublicKey publicKey)
 {
     try
     {
         return(_publicKeys.FirstIndexOf(publicKey));
     }
     catch (Exception)
     {
         return(-1);
     }
 }
Example #10
0
        public void VerifyPublicKey(ECDSAPublicKey pubkey)
        {
            var pk        = new byte[64];
            var publicKey = pubkey.Buffer.ToByteArray();

            Assert.IsTrue(Secp256K1.PublicKeyParse(pk, publicKey));
            var publicKeySerialized = new byte[33];

            Assert.IsTrue(Secp256K1.PublicKeySerialize(publicKeySerialized, pk, Flags.SECP256K1_EC_COMPRESSED));
            Assert.AreEqual(publicKey, publicKeySerialized);
        }
Example #11
0
 public void HandlePeerHasBlocks(ulong blockHeight, ECDSAPublicKey publicKey)
 {
     Logger.Log(_logLevelForSync, $"Peer {publicKey.ToHex()} has height {blockHeight}");
     lock (_peerHasBlocks)
     {
         if (_peerHeights.TryGetValue(publicKey, out var peerHeight) && blockHeight <= peerHeight)
         {
             return;
         }
         _peerHeights[publicKey] = blockHeight;
         Monitor.PulseAll(_peerHasBlocks);
     }
 }
Example #12
0
 /* Sync Verification, verifies the transaction immediately */
 public bool VerifyTransactionImmediately(TransactionReceipt receipt, ECDSAPublicKey publicKey, bool useNewChainId)
 {
     try
     {
         return(_crypto.VerifySignatureHashed(
                    receipt.Transaction.RawHash(useNewChainId).ToBytes(),
                    receipt.Signature.Encode(), publicKey.EncodeCompressed(), useNewChainId
                    ));
     }
     catch (Exception)
     {
         return(false);
     }
 }
Example #13
0
 public BlockBuilder WithSignature(ECDSAPublicKey publicKey, Signature signature)
 {
     if (_multiSig is null)
     {
         _multiSig = new MultiSig();
     }
     _multiSig.Signatures.Add(new MultiSig.Types.SignatureByValidator
     {
         Key   = publicKey,
         Value = signature
     });
     if (!_multiSig.Validators.Contains(publicKey))
     {
         _multiSig.Validators.Add(publicKey);
     }
     return(this);
 }
Example #14
0
        private ClientWorker?CreateMsgChannel(ECDSAPublicKey publicKey)
        {
            if (_messageFactory.GetPublicKey().Equals(publicKey))
            {
                return(null);
            }
            if (_clientWorkers.TryGetValue(publicKey, out var existingWorker))
            {
                return(existingWorker);
            }

            Logger.LogTrace($"Connecting to peer {publicKey.ToHex()}");
            var worker = new ClientWorker(publicKey, _messageFactory, _hubConnector);

            _clientWorkers.Add(publicKey, worker);
            worker.Start();
            return(worker);
        }
Example #15
0
        public uint HandleTransactionsFromPeer(IEnumerable <TransactionReceipt> transactions, ECDSAPublicKey publicKey)
        {
            lock (_txLock)
            {
                var txs = transactions.ToArray();
                Logger.LogTrace($"Received {txs.Length} transactions from peer {publicKey.ToHex()}");
                var persisted = 0u;
                foreach (var tx in txs)
                {
                    if (tx.Signature.IsZero())
                    {
                        Logger.LogTrace($"Received zero-signature transaction: {tx.Hash.ToHex()}");
                        if (_transactionPool.Add(tx, false) == OperatingError.Ok)
                        {
                            persisted++;
                        }
                        continue;
                    }

                    var error = _transactionManager.Verify(tx, HardforkHeights.IsHardfork_9Active(_blockManager.GetHeight() + 1));
                    if (error != OperatingError.Ok)
                    {
                        Logger.LogTrace($"Unable to verify transaction: {tx.Hash.ToHex()} ({error})");
                        continue;
                    }

                    error = _transactionPool.Add(tx, false);
                    if (error == OperatingError.Ok)
                    {
                        persisted++;
                    }
                    else
                    {
                        Logger.LogTrace($"Transaction {tx.Hash.ToHex()} not persisted: {error}");
                    }
                }

                lock (_peerHasTransactions)
                    Monitor.PulseAll(_peerHasTransactions);
                Logger.LogTrace($"Persisted {persisted} transactions from peer {publicKey.ToHex()}");
                return(persisted);
            }
        }
Example #16
0
        public bool HandleBlockFromPeer(BlockInfo blockWithTransactions, ECDSAPublicKey publicKey)
        {
            Logger.LogTrace("HandleBlockFromPeer");
            lock (_blocksLock)
            {
                var block    = blockWithTransactions.Block;
                var receipts = blockWithTransactions.Transactions;
                Logger.LogDebug(
                    $"Got block {block.Header.Index} with hash {block.Hash.ToHex()} from peer {publicKey.ToHex()}");
                var myHeight = _blockManager.GetHeight();
                if (block.Header.Index != myHeight + 1)
                {
                    Logger.LogTrace(
                        $"Skipped block {block.Header.Index} from peer {publicKey.ToHex()}: our height is {myHeight}");
                    return(false);
                }

                if (!block.TransactionHashes.ToHashSet().SetEquals(receipts.Select(r => r.Hash)))
                {
                    try
                    {
                        var needHashes = string.Join(", ", block.TransactionHashes.Select(x => x.ToHex()));
                        var gotHashes  = string.Join(", ", receipts.Select(x => x.Hash.ToHex()));

                        Logger.LogTrace(
                            $"Skipped block {block.Header.Index} from peer {publicKey.ToHex()}: expected hashes [{needHashes}] got hashes [{gotHashes}]");
                    }
                    catch (Exception e)
                    {
                        Logger.LogWarning($"Failed to get transaction receipts for tx hash: {e}");
                    }

                    return(false);
                }

                var error = _blockManager.VerifySignatures(block, true);
                if (error != OperatingError.Ok)
                {
                    Logger.LogTrace($"Skipped block {block.Header.Index} from peer {publicKey.ToHex()}: invalid multisig with error: {error}");
                    return(false);
                }
                // This is to tell consensus manager to terminate current era, since we trust given multisig
                OnSignedBlockReceived?.Invoke(this, block.Header.Index);

                error = _stateManager.SafeContext(() =>
                {
                    if (_blockManager.GetHeight() + 1 == block.Header.Index)
                    {
                        return(_blockManager.Execute(block, receipts, commit: true, checkStateHash: true));
                    }
                    Logger.LogTrace(
                        $"We have blockchain with height {_blockManager.GetHeight()} but got block {block.Header.Index}");
                    return(OperatingError.BlockAlreadyExists);
                });
                if (error == OperatingError.BlockAlreadyExists)
                {
                    Logger.LogTrace(
                        $"Skipped block {block.Header.Index} from peer {publicKey.ToHex()}: block already exists");
                    return(true);
                }

                if (error != OperatingError.Ok)
                {
                    Logger.LogWarning(
                        $"Unable to persist block {block.Header.Index} (current height {_blockManager.GetHeight()}), got error {error}, dropping peer");
                    return(false);
                }

                lock (_peerHasBlocks)
                    Monitor.PulseAll(_peerHasBlocks);
                return(true);
            }
        }
Example #17
0
 public Task <bool> Validate(ECDSAPublicKey key)
 {
     return(key.Verify(content.Serialize(), Signature));
 }
Example #18
0
        public OperatingError VerifySignature(BlockHeader blockHeader, Signature signature, ECDSAPublicKey publicKey)
        {
            var result = Crypto.VerifySignatureHashed(
                blockHeader.Keccak().ToBytes(), signature.Encode(), publicKey.EncodeCompressed(),
                HardforkHeights.IsHardfork_9Active(blockHeader.Index)
                );

            return(result ? OperatingError.Ok : OperatingError.InvalidSignature);
        }
Example #19
0
 public EcdsaKeyPair(ECDSAPrivateKey privateKey, ECDSAPublicKey publicKey)
 {
     PrivateKey = privateKey;
     PublicKey  = publicKey;
 }
Example #20
0
 public async Task <bool> Verify(ECDSAPublicKey publicKey)
 {
     return(await publicKey.Verify(Serialize(), Signature));
 }
Example #21
0
 public void SendTo(ECDSAPublicKey publicKey, NetworkMessage message)
 {
     CreateMsgChannel(publicKey)?.AddMsgToQueue(message);
 }
Example #22
0
 public bool IsValidatorForBlock(ECDSAPublicKey key, long block)
 {
     return(GetValidatorsPublicKeys(block - 1).Contains(key));
 }
Example #23
0
 public ValidatorCredentials(ECDSAPublicKey publicKey, byte[] thresholdSignaturePublicKey)
 {
     PublicKey = publicKey;
     ThresholdSignaturePublicKey = thresholdSignaturePublicKey;
 }
Example #24
0
        private static byte[] EncryptRow(IEnumerable <Fr> row, ECDSAPublicKey publicKey)
        {
            var serializedRow = row.Select(x => x.ToBytes()).Flatten().ToArray();

            return(Crypto.Secp256K1Encrypt(publicKey.EncodeCompressed(), serializedRow));
        }
Example #25
0
 public static string ToHex(this ECDSAPublicKey key, bool prefix = true)
 {
     return(key.Buffer.ToHex(prefix));
 }
Example #26
0
 public EcdsaKeyPair(ECDSAPrivateKey privateKey)
 {
     PrivateKey = privateKey;
     PublicKey  = privateKey.GetPublicKey();
 }
Example #27
0
 public int GetIdByPublicKey(ECDSAPublicKey publicKey)
 {
     return(_validators.GetValidatorIndex(publicKey));
 }
Example #28
0
 public MessageEnvelope(ECDSAPublicKey publicKey, ClientWorker remotePeer)
 {
     PublicKey  = publicKey;
     RemotePeer = remotePeer;
 }
Example #29
0
 public override void Read(DataDeserializer reader)
 {
     base.Read(reader);
     TargetId  = reader.ReadShortString();
     PublicKey = reader.ReadContent <ECDSAPublicKey>();
 }
Example #30
0
 public static UInt160 GetAddress(this ECDSAPublicKey key)
 {
     return(Crypto.ComputeAddress(key.EncodeCompressed()).ToUInt160());
 }