Пример #1
0
        /// <summary>
        /// Verifies if signature of provided header was created using
        /// private key that corresponds to given public key.
        /// </summary>
        public bool VerifySignature(PubKey pubKey, PoABlockHeader header)
        {
            if ((header.BlockSignature == null) || header.BlockSignature.IsEmpty())
            {
                this.logger.LogTrace("(-)[NO_SIGNATURE]");
                return(false);
            }

            if (!ECDSASignature.IsValidDER(header.BlockSignature.Signature))
            {
                this.logger.LogTrace("(-)[INVALID_DER]");
                return(false);
            }

            ECDSASignature signature = ECDSASignature.FromDER(header.BlockSignature.Signature);

            if (!signature.IsLowS)
            {
                this.logger.LogTrace("(-)[NOT_CANONICAL]");
                return(false);
            }

            uint256 headerHash       = header.GetHash();
            bool    isValidSignature = pubKey.Verify(headerHash, signature);

            return(isValidSignature);
        }
Пример #2
0
        public bool Verify()
        {
            var messageBytes     = Sha256.ComputeHash(Encoding.ASCII.GetBytes(message));
            var messageSignature = ECDSASignature.FromDER(Encoders.Hex.DecodeData(signature));

            return(new PubKey(publicKey).Verify(new uint256(messageBytes), messageSignature));
        }
Пример #3
0
        public void can_always_recover_pubkey_from_signature_when_stopping_at_null()
        {
            var rand = new Random();

            for (int i = 0; i < 1000; i++)
            {
                var      key   = new Key();
                PosBlock block = new PosBlock(new BlockHeader()
                {
                    Time = (uint)rand.Next()
                });
                ECDSASignature signature = key.Sign(block.GetHash());
                block.BlockSignature = new BlockSignature {
                    Signature = signature.ToDER()
                };
                Assert.True(key.PubKey.Verify(block.GetHash(), new ECDSASignature(block.BlockSignature.Signature)));
                signature = ECDSASignature.FromDER(block.BlockSignature.Signature);
                bool match = false;
                for (int recId = 0; !match; recId++)
                {
                    PubKey pubKeyForSig = PubKey.RecoverFromSignature(recId, signature, block.GetHash(), true);
                    if (pubKeyForSig == null)
                    {
                        break;
                    }

                    match = pubKeyForSig == key.PubKey;
                }
                Assert.True(match);
            }
        }
Пример #4
0
        private IFederationMember GetFederationMemberForBlockInternal(ChainedHeader chainedHeader, List <IFederationMember> federation)
        {
            if (chainedHeader.Height == 0)
            {
                return(federation.Last());
            }

            // Try to provide the public key that signed the block.
            try
            {
                var header = chainedHeader.Header as PoABlockHeader;

                var signature = ECDSASignature.FromDER(header.BlockSignature.Signature);
                for (int recId = 0; recId < 4; recId++)
                {
                    PubKey pubKeyForSig = PubKey.RecoverFromSignature(recId, signature, header.GetHash(), true);
                    if (pubKeyForSig == null)
                    {
                        break;
                    }

                    IFederationMember federationMember = federation.FirstOrDefault(m => m.PubKey == pubKeyForSig);
                    if (federationMember != null)
                    {
                        this.minersByBlockHash[chainedHeader.HashBlock] = federationMember;
                        return(federationMember);
                    }
                }
            }
            catch (Exception)
            {
            }

            return(null);
        }
Пример #5
0
        public bool VerifySignature(byte[] hash, byte[] signature)
        {
            ECDsaSigner    signer          = new ECDsaSigner();
            ECDSASignature parsedSignature = ECDSASignature.FromDER(signature);

            signer.Init(false, key);
            return(signer.VerifySignature(hash, parsedSignature.R, parsedSignature.S));
        }
Пример #6
0
        public ECDSASignature Sign(uint256 hash, bool useLowR = true)
        {
            AssertPrivateKey();
            var signer = new DeterministicECDSA(useLowR);

            signer.setPrivateKey(PrivateKey);
            var sig = ECDSASignature.FromDER(signer.signHash(hash.ToBytes()));

            return(sig.MakeCanonical());
        }
Пример #7
0
		private void TestSig(ECPrivateKeyParameters key, DeterministicSigTest test)
		{
			var dsa = new DeterministicECDSA(GetHash(test.Hash));
			dsa.setPrivateKey(key);
			dsa.update(Encoding.UTF8.GetBytes(test.Message));
			var result = dsa.sign();

			var signature = ECDSASignature.FromDER(result);
			Assert.Equal(test.S, signature.S);
			Assert.Equal(test.R, signature.R);
		}
Пример #8
0
        public void ToFromDer()
        {
            var signature = new ECDSASignature(
                TestUtils.HexToBigInteger("657912a72d3ac8169fe8eaecd5ab401c94fc9981717e3e6dd4971889f785790c"),
                TestUtils.HexToBigInteger("00ed3bf3456eb76677fd899c8ccd1cc6d1ebc631b94c42f7c4578f28590d651c6e"));

            var expected = Encoders.Hex.GetBytes("30450220657912a72d3ac8169fe8eaecd5ab401c94fc9981717e3e6dd4971889f785790c022100ed3bf3456eb76677fd899c8ccd1cc6d1ebc631b94c42f7c4578f28590d651c6e");

            CollectionAssert.AreEqual(expected, signature.ToDER());

            var signature1 = ECDSASignature.FromDER(signature.ToDER());

            Assert.AreEqual(signature.R, signature1.R);
            Assert.AreEqual(signature.S, signature1.S);
        }
        public async Task <IActionResult> LoginResponse(string userId, string sig, string key)
        {
            if (await _lnurlAuthService.CompleteLogin(userId,
                                                      ECDSASignature.FromDER(Encoders.Hex.DecodeData(sig)), new PubKey(key)))
            {
                return(Ok(new LNUrlStatusResponse()
                {
                    Status = "OK"
                }));
            }

            return(BadRequest(new LNUrlStatusResponse()
            {
                Reason = "The challenge could not be verified", Status = "ERROR"
            }));
        }
Пример #10
0
        private void TestSig(ECPrivateKeyParameters key, DeterministicSigTest test)
        {
            if (test.Hash.Equals("SHA-1", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }
            var dsa = new DeterministicECDSA(GetHash(test.Hash), false);

            dsa.setPrivateKey(key);
            dsa.update(Encoding.UTF8.GetBytes(test.Message));
            var result = dsa.sign();

            var signature = ECDSASignature.FromDER(result);

            Assert.Equal(test.S, signature.S);
            Assert.Equal(test.R, signature.R);
        }
Пример #11
0
 public void Signatures(string name, JArray sig, bool isDER, bool isValid)
 {
     try
     {
         var derSig = sig.Select(x => (byte)x).ToArray();
         var s      = ECDSASignature.FromDER(derSig);
         Assert.IsTrue(isValid);
     }
     catch (Exception e)
     {
         if (e is FormatException || e is EndOfStreamException)
         {
             Assert.False(isValid);
         }
         else
         {
             Assert.Fail(name);
         }
     }
 }
Пример #12
0
        public static bool VerifySignature(JsonEnvelope envelope)
        {
            if (string.IsNullOrEmpty(envelope.Payload))
            {
                throw new BadRequestException("JsonEnvelope must contain non-empty 'payload'");
            }

            if (string.IsNullOrEmpty(envelope.PublicKey))
            {
                throw new BadRequestException("JsonEnvelope must contain non-empty publicKey");
            }

            if (string.IsNullOrEmpty(envelope.Signature))
            {
                throw new BadRequestException("JsonEnvelope must contain non-empty signature");
            }

            var signature = ECDSASignature.FromDER(Encoders.Hex.DecodeData(envelope.Signature));

            var pubKey = new PubKey(envelope.PublicKey);


            return(pubKey.Verify(new uint256(GetSigHash(envelope.Payload, envelope.Encoding)), signature));
        }
Пример #13
0
 public bool Verify(uint256 hash, byte[] sig)
 {
     return(Verify(hash, ECDSASignature.FromDER(sig)));
 }
Пример #14
0
 public TransactionSignature(byte[] sigSigHash)
 {
     _Signature = ECDSASignature.FromDER(sigSigHash.Take(sigSigHash.Length - 1).ToArray()).MakeCanonical();
     _SigHash   = (SigHash)sigSigHash[sigSigHash.Length - 1];
 }
 public TransactionSignature(byte[] sig, SigHash sigHash)
 {
     _Signature = ECDSASignature.FromDER(sig);
     _SigHash   = sigHash;
 }
 public TransactionSignature(byte[] sigSigHash)
 {
     _Signature = ECDSASignature.FromDER(sigSigHash);
     _SigHash   = (SigHash)sigSigHash[sigSigHash.Length - 1];
 }
Пример #17
0
        public override void Run(RuleContext context)
        {
            var header = context.ValidationContext.ChainedHeaderToValidate.Header as PoABlockHeader;

            PubKey pubKey = this.slotsManager.GetFederationMemberForBlock(context.ValidationContext.ChainedHeaderToValidate, this.votingManager).PubKey;

            if (!this.validator.VerifySignature(pubKey, header))
            {
                if (this.votingEnabled)
                {
                    ChainedHeader currentHeader = context.ValidationContext.ChainedHeaderToValidate;

                    // If we're evaluating a batch of received headers it's possible that we're so far beyond the current tip
                    // that we have not yet processed all the votes that may determine the federation make-up.
                    bool mightBeInsufficient = currentHeader.Height - this.chainState.ConsensusTip.Height > this.maxReorg;
                    if (mightBeInsufficient)
                    {
                        // Mark header as insufficient to avoid banning the peer that presented it.
                        // When we advance consensus we will be able to validate it.
                        context.ValidationContext.InsufficientHeaderInformation = true;
                    }
                }

                try
                {
                    // Gather all past and present mining public keys.
                    IEnumerable <PubKey> genesisFederation = ((PoAConsensusOptions)this.network.Consensus.Options).GenesisFederationMembers.Select(m => m.PubKey);
                    var knownKeys = new HashSet <PubKey>(genesisFederation);
                    foreach (Poll poll in this.votingManager.GetFinishedPolls().Where(x => ((x.VotingData.Key == VoteKey.AddFederationMember) || (x.VotingData.Key == VoteKey.KickFederationMember))))
                    {
                        IFederationMember federationMember = ((PoAConsensusFactory)(this.network.Consensus.ConsensusFactory)).DeserializeFederationMember(poll.VotingData.Data);
                        knownKeys.Add(federationMember.PubKey);
                    }

                    // Try to provide the public key that signed the block.
                    var signature = ECDSASignature.FromDER(header.BlockSignature.Signature);
                    for (int recId = 0; recId < 4; recId++)
                    {
                        PubKey pubKeyForSig = PubKey.RecoverFromSignature(recId, signature, header.GetHash(), true);
                        if (pubKeyForSig == null)
                        {
                            this.Logger.LogDebug($"Could not match candidate keys to any known key.");
                            break;
                        }

                        this.Logger.LogDebug($"Attempting to match candidate key '{ pubKeyForSig.ToHex() }' to known keys.");

                        if (!knownKeys.Any(pk => pk == pubKeyForSig))
                        {
                            continue;
                        }

                        IEnumerable <PubKey> modifiedFederation = this.votingManager?.GetModifiedFederation(context.ValidationContext.ChainedHeaderToValidate).Select(m => m.PubKey) ?? genesisFederation;

                        this.Logger.LogDebug($"Block is signed by '{0}' but expected '{1}' from: {2}.", pubKeyForSig.ToHex(), pubKey, string.Join(" ", modifiedFederation.Select(pk => pk.ToHex())));

                        break;
                    }
                    ;
                }
                catch (Exception) { }

                this.Logger.LogTrace("(-)[INVALID_SIGNATURE]");
                PoAConsensusErrors.InvalidHeaderSignature.Throw();
            }
        }