public ClientWorker(ECDSAPublicKey peerPublicKey, IMessageFactory messageFactory, HubConnector hubConnector) { _messageFactory = messageFactory; _hubConnector = hubConnector; PeerPublicKey = peerPublicKey.EncodeCompressed(); _worker = new Thread(Worker); }
public void VerifyTransaction(TransactionReceipt acceptedTransaction, ECDSAPublicKey publicKey, bool useNewChainId) { var address = _crypto.ComputeAddress(publicKey.EncodeCompressed()).ToUInt160(); _publicKeyCache.Add(address, publicKey); VerifyTransaction(acceptedTransaction, useNewChainId); }
/// <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 ); }
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()); }
public static byte[] EncodeCompressed(this ECDSAPublicKey key) { if (key.Buffer.Length != PublicKeyLength) { throw new InvalidOperationException("Corrupted public key"); } return(key.Buffer.ToByteArray()); }
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()); }
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)); }
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); }
public int GetSenderByPublicKey(ECDSAPublicKey publicKey) { try { return(_publicKeys.FirstIndexOf(publicKey)); } catch (Exception) { return(-1); } }
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); }
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); } }
/* 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); } }
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); }
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); }
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); } }
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); } }
public Task <bool> Validate(ECDSAPublicKey key) { return(key.Verify(content.Serialize(), Signature)); }
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); }
public EcdsaKeyPair(ECDSAPrivateKey privateKey, ECDSAPublicKey publicKey) { PrivateKey = privateKey; PublicKey = publicKey; }
public async Task <bool> Verify(ECDSAPublicKey publicKey) { return(await publicKey.Verify(Serialize(), Signature)); }
public void SendTo(ECDSAPublicKey publicKey, NetworkMessage message) { CreateMsgChannel(publicKey)?.AddMsgToQueue(message); }
public bool IsValidatorForBlock(ECDSAPublicKey key, long block) { return(GetValidatorsPublicKeys(block - 1).Contains(key)); }
public ValidatorCredentials(ECDSAPublicKey publicKey, byte[] thresholdSignaturePublicKey) { PublicKey = publicKey; ThresholdSignaturePublicKey = thresholdSignaturePublicKey; }
private static byte[] EncryptRow(IEnumerable <Fr> row, ECDSAPublicKey publicKey) { var serializedRow = row.Select(x => x.ToBytes()).Flatten().ToArray(); return(Crypto.Secp256K1Encrypt(publicKey.EncodeCompressed(), serializedRow)); }
public static string ToHex(this ECDSAPublicKey key, bool prefix = true) { return(key.Buffer.ToHex(prefix)); }
public EcdsaKeyPair(ECDSAPrivateKey privateKey) { PrivateKey = privateKey; PublicKey = privateKey.GetPublicKey(); }
public int GetIdByPublicKey(ECDSAPublicKey publicKey) { return(_validators.GetValidatorIndex(publicKey)); }
public MessageEnvelope(ECDSAPublicKey publicKey, ClientWorker remotePeer) { PublicKey = publicKey; RemotePeer = remotePeer; }
public override void Read(DataDeserializer reader) { base.Read(reader); TargetId = reader.ReadShortString(); PublicKey = reader.ReadContent <ECDSAPublicKey>(); }
public static UInt160 GetAddress(this ECDSAPublicKey key) { return(Crypto.ComputeAddress(key.EncodeCompressed()).ToUInt160()); }