Exemple #1
0
        /// <summary>
        /// Signs with blinding factor.
        /// </summary>
        /// <returns>The with blinding.</returns>
        /// <param name="msg">Message.</param>
        /// <param name="blinding">Blinding.</param>
        public byte[] SignWithBlinding(byte[] msg, byte[] blinding)
        {
            if (msg == null)
            {
                throw new ArgumentNullException(nameof(msg));
            }

            if (msg.Length > 32)
            {
                throw new IndexOutOfRangeException(nameof(msg));
            }

            if (blinding == null)
            {
                throw new ArgumentNullException(nameof(blinding));
            }

            if (blinding.Length > 32)
            {
                throw new IndexOutOfRangeException(nameof(blinding));
            }

            using (var secp256k1 = new Secp256k1())
            {
                var msgHash = Cryptography.GenericHashNoKey(Encoding.UTF8.GetString(msg));
                return(secp256k1.Sign(msgHash, blinding));
            }
        }
Exemple #2
0
        private string GetDelegator()
        {
            if (!this.GetDelegated())
            {
                return("");
            }

            if (!this.GetSignatureValid())
            {
                return("");
            }

            try
            {
                byte[] signingHash        = this.SigningHash(this.Origin);
                byte[] delegatorSignature = new byte[65];
                Array.Copy(this.Signature, 65, delegatorSignature, 0, 65);
                byte[] delegatorpubKey = Secp256k1.RecoverPublickey(signingHash, delegatorSignature);
                return(SimpleWallet.PublicKeyToAddress(delegatorpubKey));
            }
            catch
            {
                return("");
            }
        }
Exemple #3
0
        public void Schnorrsig_Wrong_Verify()
        {
            using (var secp256k1 = new Secp256k1())
                using (var schnorrSig = new SchnorrSig())
                {
                    var keyPair = secp256k1.GenerateKeyPair();

                    var msg      = "Message for signing";
                    var msgBytes = Encoding.UTF8.GetBytes(msg);
                    var msgHash  = System.Security.Cryptography.SHA256.Create().ComputeHash(msgBytes);

                    var sig = schnorrSig.SchnorrsigSign(msgHash, keyPair.privateKey);

                    Assert.NotNull(sig);
                    Assert.InRange(sig.Length, 0, Constant.SIGNATURE_SIZE);

                    msg      = "Wrong message for signing";
                    msgBytes = Encoding.UTF8.GetBytes(msg);
                    msgHash  = System.Security.Cryptography.SHA256.Create().ComputeHash(msgBytes);

                    var valid = schnorrSig.SchnorrsigVerify(sig, msgHash, keyPair.publicKey);

                    Assert.False(valid);
                }
        }
Exemple #4
0
        public void should_verify_signature()
        {
            var hexReader = new HexReader();
            var secp256K1 = new Secp256k1();

            // https://www.blockchain.com/btc/tx/9f3eca62d13c2e7bf104a8539f5768674d551ecc140f3bb9bdaf3f07d6d3f6de
            // 15RpkAiu17FiYJmMiTJBvEwNQQdgEr1KvK
            // 1HvRorjpF5wyY7To5QhgJDzB3C9nEPcMo1
            var data = "9f3eca62d13c2e7bf104a8539f5768674d551ecc140f3bb9bdaf3f07d6d3f6de";

            var signature =
                "3046022100a7a1bfc118676e8dc1779a6c6dfaece6435ca20e8e2fcf4399300cc930c791e00221009a88d6a51b763fa748254fc487710998c9572bc2f01be06d1a7532c8e38a4c1901";

            var pubkey = "03a5cc256133f721c66201b54f18f08053b6fc62f3dfc84c43a3a2d1c87afbe30c";

            var bData      = hexReader.ToByteArray(data);
            var bSignature = hexReader.ToByteArray(signature);
            var bPubKey    = hexReader.ToByteArray(pubkey);

            var output = new Span <byte>(new byte[66]);

            var normalize = secp256K1.PublicKeyParse(output, bPubKey);

            var res = secp256K1.Verify(bSignature.AsSpan(), bData.AsSpan(), output);

            Console.WriteLine(res);
        }
Exemple #5
0
        public void should_verify_pizza_transaction_ec()
        {
            var hexReader = new HexReader();
            var secp256K1 = new Secp256k1();


            // https://bitcoin.stackexchange.com/questions/32305/how-does-the-ecdsa-verification-algorithm-work-during-transaction
            var digest = "692678553d1b85ccf87d4d4443095f276cdf600f2bb7dd44f6effbd7458fd4c2";

            var signature =
                "30450221009908144ca6539e09512b9295c8a27050d478fbb96f8addbc3d075544dc41328702201aa528be2b907d316d2da068dd9eb1e23243d97e444d59290d2fddf25269ee0e01";

            var pubkey =
                "042e930f39ba62c6534ee98ed20ca98959d34aa9e057cda01cfd422c6bab3667b76426529382c23f42b9b08d7832d4fee1d6b437a8526e59667ce9c4e9dcebcabb";



            var bData      = hexReader.ToByteArray(digest);
            var bSignature = hexReader.ToByteArray(signature);
            var bPubKey    = hexReader.ToByteArray(pubkey);



            var res = secp256K1.Verify(bSignature.AsSpan(), bData.AsSpan(), bPubKey);
        }
Exemple #6
0
        static void Main(string[] args)
        {
            // Create a secp256k1 context (ensure disposal to prevent unmanaged memory leaks).
            using (var secp256k1 = new Secp256k1())
            {
                // Generate a private key.
                var privateKey = new byte[32];
                var rnd        = System.Security.Cryptography.RandomNumberGenerator.Create();
                do
                {
                    rnd.GetBytes(privateKey);
                }while (!secp256k1.SecretKeyVerify(privateKey));


                // Create public key from private key.
                var publicKey = new byte[64];
                Debug.Assert(secp256k1.PublicKeyCreate(publicKey, privateKey));


                // Sign a message hash.
                var messageBytes = Encoding.UTF8.GetBytes("Hello world.");
                var messageHash  = System.Security.Cryptography.SHA256.Create().ComputeHash(messageBytes);
                var signature    = new byte[64];
                Debug.Assert(secp256k1.Sign(signature, messageHash, privateKey));

                // Serialize a DER signature from ECDSA signature
                byte[] signatureDer = new byte[Secp256k1.SERIALIZED_DER_SIGNATURE_MAX_SIZE];
                int    outL         = 0;
                Debug.Assert(secp256k1.SignatureSerializeDer(signatureDer, signature, out outL));
                Array.Resize(ref signatureDer, outL);

                // Verify message hash.
                Debug.Assert(secp256k1.Verify(signature, messageHash, publicKey));
            }
        }
Exemple #7
0
        static void Main(string[] args)
        {
            // Create a secp256k1 context (ensure disposal to prevent unmanaged memory leaks).
            using (var secp256k1 = new Secp256k1())
            {
                // Generate a private key.
                var privateKey = new byte[32];
                var rnd        = System.Security.Cryptography.RandomNumberGenerator.Create();
                do
                {
                    rnd.GetBytes(privateKey);
                }while (!secp256k1.SecretKeyVerify(privateKey));


                // Create public key from private key.
                var publicKey = new byte[64];
                Debug.Assert(secp256k1.PublicKeyCreate(publicKey, privateKey));


                // Sign a message hash.
                var messageBytes = Encoding.UTF8.GetBytes("Hello world.");
                var messageHash  = System.Security.Cryptography.SHA256.Create().ComputeHash(messageBytes);
                var signature    = new byte[64];
                Debug.Assert(secp256k1.Sign(signature, messageHash, privateKey));


                // Verify message hash.
                Debug.Assert(secp256k1.Verify(signature, messageHash, publicKey));
            }
        }
Exemple #8
0
        /// <summary>
        /// </summary>
        /// <param name="transaction"></param>
        /// <returns></returns>
        public VerifyResult VerifyBulletProof(Transaction transaction)
        {
            Guard.Argument(transaction, nameof(transaction)).NotNull();
            Guard.Argument(transaction.Vout, nameof(transaction)).NotNull();
            try
            {
                if (transaction.Validate().Any())
                {
                    return(VerifyResult.UnableToVerify);
                }
                using var secp256K1   = new Secp256k1();
                using var bulletProof = new BulletProof();
                if (transaction.Bp.Select((t, i) => bulletProof.Verify(transaction.Vout[i + 2].C, t.Proof, null))
                    .Any(verified => !verified))
                {
                    return(VerifyResult.UnableToVerify);
                }
            }
            catch (Exception ex)
            {
                _logger.Here().Error(ex, "Unable to verify the bullet proof");
                return(VerifyResult.UnableToVerify);
            }

            return(VerifyResult.Succeed);
        }
Exemple #9
0
        /// <summary>
        /// Builds the receiver.
        /// </summary>
        /// <returns>The receiver.</returns>
        public (ReceiverOutput, CoinDto) BuildReceiver()
        {
            ReceiverOutput receiver = null;
            CoinDto        coin     = null;

            using (var secp256k1 = new Secp256k1())
                using (var pedersen = new Pedersen())
                {
                    var blind    = DeriveKey(Output());
                    var blindSum = pedersen.BlindSum(new List <byte[]> {
                        blind, blind
                    }, new List <byte[]> {
                    });
                    var commitPos = Commit((ulong)Output(), blind);
                    var commitNeg = Commit(0, blind);

                    Stamp(GetNewStamp());
                    Version(-1);

                    coin     = BuildCoin(blindSum, commitPos, commitNeg, true);
                    receiver = new ReceiverOutput(Output(), commitPos, blindSum);
                }

            return(receiver, coin);
        }
Exemple #10
0
        /// <summary>
        /// Attachs the envelope.
        /// </summary>
        /// <param name="blindSum">Blind sum.</param>
        /// <param name="commitSum">Commit sum.</param>
        /// <param name="balance">Balance.</param>
        /// <param name="secret">Secret.</param>
        /// <param name="coin">Coin.</param>
        private void AttachEnvelope(byte[] blindSum, byte[] commitSum, ulong balance, SecureString secret, SecureString salt, ref CoinDto coin)
        {
            var(k1, k2) = Split(blindSum, secret, salt, coin.Stamp, coin.Version);

            using (var secp256k1 = new Secp256k1())
                using (var pedersen = new Pedersen())
                    using (var bulletProof = new BulletProof())
                    {
                        coin.Envelope.Commitment = commitSum.ToHex();
                        coin.Envelope.Proof      = k2.ToHex();
                        coin.Envelope.PublicKey  = pedersen.ToPublicKey(pedersen.Commit(0, k1)).ToHex();
                        coin.Hash = Hash(coin).ToHex();
                        coin.Envelope.Signature = secp256k1.Sign(coin.Hash.FromHex(), k1).ToHex();

                        var @struct = bulletProof.ProofSingle(balance, blindSum, Cryptography.RandomBytes(), null, null, null);
                        var success = bulletProof.Verify(commitSum, @struct.proof, null);

                        if (!success)
                        {
                            throw new ArgumentOutOfRangeException(nameof(success), "Bullet proof failed.");
                        }

                        coin.Envelope.RangeProof = @struct.proof.ToHex();
                    }
        }
Exemple #11
0
        public void Schnorrsig_Verify_Batch()
        {
            using (var secp256k1 = new Secp256k1())
                using (var schnorrSig = new SchnorrSig())
                {
                    var signatures = new List <byte[]>();
                    var messages   = new List <byte[]>();
                    var publicKeys = new List <byte[]>();

                    for (int i = 0; i < 10; i++)
                    {
                        var keyPair = secp256k1.GenerateKeyPair();

                        var msg      = $"Message for signing {i}";
                        var msgBytes = Encoding.UTF8.GetBytes(msg);
                        var msgHash  = System.Security.Cryptography.SHA256.Create().ComputeHash(msgBytes);

                        var sig = schnorrSig.SchnorrsigSign(msgHash, keyPair.privateKey);

                        Assert.NotNull(sig);
                        Assert.InRange(sig.Length, 0, Constant.SIGNATURE_SIZE);

                        signatures.Add(sig);
                        messages.Add(msgHash);
                        publicKeys.Add(keyPair.publicKey);
                    }

                    var valid = schnorrSig.SchnorrsigVerifyBatch(signatures, messages, publicKeys);

                    Assert.True(valid);
                }
        }
        static void TestToPublicKey()
        {
            using (var secp256k1 = new Secp256k1())
                using (var pedersen = new Pedersen())
                {
                    var blinding  = secp256k1.CreatePrivateKey();
                    var commitPos = pedersen.Commit(0, blinding);
                    var commitNeg = pedersen.Commit(0, blinding);

                    var blindSum = pedersen.BlindSum(new List <byte[]> {
                        blinding, blinding
                    }, new List <byte[]> {
                    });

                    var commitSum = pedersen.CommitSum(new List <byte[]> {
                        commitPos
                    }, new List <byte[]> {
                        commitNeg
                    });

                    var msg      = "Message for signing";
                    var msgBytes = Encoding.UTF8.GetBytes(msg);
                    var msgHash  = System.Security.Cryptography.SHA256.Create().ComputeHash(msgBytes);

                    var sig = secp256k1.Sign(msgHash, blinding);

                    var pubKey = pedersen.ToPublicKey(commitSum);

                    var verified1 = secp256k1.Verify(sig, msgHash, pubKey);
                    var pub       = secp256k1.CreatePublicKey(blinding);
                }
        }
Exemple #13
0
        public void Bullet_Proof_Extra_Commit_Wrong()
        {
            using (var secp256k1 = new Secp256k1())
                using (var pedersen = new Pedersen())
                    using (var bulletProof = new BulletProof())
                    {
                        // Correct extra commit
                        var   extraCommit = new byte[32];
                        var   blinding    = secp256k1.CreatePrivateKey();
                        ulong value       = 100033;
                        var   commit      = pedersen.Commit(value, blinding);
                        var   @struct     = bulletProof.GenProof(value, blinding, (byte[])blinding.Clone(), (byte[])blinding.Clone(), extraCommit, null);
                        var   success     = bulletProof.Verify(commit, @struct.proof, extraCommit);

                        Assert.True(success);


                        //Wrong extra commit
                        var extraCommitWrong = new byte[32];
                        extraCommitWrong[0] = 1;
                        success             = bulletProof.Verify(commit, @struct.proof, extraCommitWrong);

                        Assert.False(success);
                    }
        }
Exemple #14
0
        public void Bullet_Proof_Minimum_Amount()
        {
            using (var secp256k1 = new Secp256k1())
                using (var pedersen = new Pedersen())
                    using (var bulletProof = new BulletProof())
                    {
                        int   minValue = 1000;
                        ulong value    = 300;

                        // Correct value and minimum value
                        var blinding = secp256k1.CreatePrivateKey();
                        var commit   = pedersen.Commit(value, blinding);
                        var @struct  = bulletProof.GenProof(value, blinding, (byte[])blinding.Clone(), (byte[])blinding.Clone(), null, null);
                        var success  = bulletProof.Verify(commit, @struct.proof, null);

                        Assert.True(success);

                        // Wrong value < 1000 and minimum value.
                        var commitWrong = pedersen.Commit(value, blinding);
                        @struct = bulletProof.GenProof(value, blinding, (byte[])blinding.Clone(), (byte[])blinding.Clone(), null, null, minValue);
                        success = bulletProof.Verify(commit, @struct.proof, null, minValue);

                        Assert.False(success);
                    }
        }
Exemple #15
0
        public void Sign_With_PubKey_From_Commitment()
        {
            using (var secp256k1 = new Secp256k1())
                using (var pedersen = new Pedersen())
                {
                    string ToHex(byte[] data)
                    {
                        return(BitConverter.ToString(data).Replace("-", string.Empty));
                    }

                    var blinding = secp256k1.CreatePrivateKey();
                    var commit   = pedersen.Commit(0, blinding);

                    var msg      = "Message for signing";
                    var msgBytes = Encoding.UTF8.GetBytes(msg);
                    var msgHash  = System.Security.Cryptography.SHA256.Create().ComputeHash(msgBytes);

                    var sig = secp256k1.Sign(msgHash, blinding);

                    var pubKey = pedersen.ToPublicKey(commit);

                    Assert.True(secp256k1.Verify(sig, msgHash, pubKey));

                    var actualPubKey = secp256k1.CreatePublicKey(blinding);

                    Assert.Equal(ToHex(pubKey), ToHex(actualPubKey));
                }
        }
Exemple #16
0
        public void Bullet_Proof()
        {
            using (var secp256k1 = new Secp256k1())
                using (var pedersen = new Pedersen())
                    using (var bulletProof = new BulletProof())
                    {
                        // Correct value
                        ulong value    = 300;
                        var   blinding = secp256k1.CreatePrivateKey();
                        var   commit   = pedersen.Commit(value, blinding);
                        var   @struct  = bulletProof.GenProof(value, blinding, (byte[])blinding.Clone(), (byte[])blinding.Clone(), null, null);
                        var   success  = bulletProof.Verify(commit, @struct.proof, null);

                        Assert.True(success);

                        // Wrong value
                        value = 1222344;
                        var commitWrong = pedersen.Commit(122111, blinding);
                        @struct = bulletProof.GenProof(value, blinding, (byte[])blinding.Clone(), (byte[])blinding.Clone(), null, null);
                        success = bulletProof.Verify(commit, @struct.proof, null);

                        Assert.False(success);

                        // Wrong binding
                        value    = 122322;
                        commit   = pedersen.Commit(value, blinding);
                        blinding = secp256k1.CreatePrivateKey();
                        @struct  = bulletProof.GenProof(value, blinding, (byte[])blinding.Clone(), (byte[])blinding.Clone(), null, null);
                        success  = bulletProof.Verify(commit, @struct.proof, null);

                        Assert.False(success);
                    }
        }
Exemple #17
0
        public void Commit_Sum_Random_Keys()
        {
            using (var secp256k1 = new Secp256k1())
                using (var pedersen = new Pedersen())
                {
                    byte[] Commit(ulong value, byte[] blinding)
                    {
                        return(pedersen.Commit(value, blinding));
                    }

                    var blindPos = secp256k1.CreatePrivateKey();
                    var blindNeg = secp256k1.CreatePrivateKey();

                    var blindSum = pedersen.BlindSum(new List <byte[]> {
                        blindPos
                    }, new List <byte[]> {
                        blindNeg
                    });

                    Assert.True(pedersen.VerifyCommitSum(new List <byte[]> {
                        Commit(101, blindPos)
                    }, new List <byte[]> {
                        Commit(75, blindNeg), Commit(26, blindSum)
                    }));
                }
        }
Exemple #18
0
        public void Verify_Commit_Sum_Random_Keys_Switch()
        {
            using (var secp256k1 = new Secp256k1())
                using (var pedersen = new Pedersen())
                {
                    byte[] Commit(ulong value, byte[] blinding)
                    {
                        return(pedersen.Commit(value, blinding));
                    }

                    ulong posValue = 101;
                    ulong negValue = 75;

                    var blindPos = pedersen.BlindSwitch(posValue, secp256k1.CreatePrivateKey());
                    var blindNeg = pedersen.BlindSwitch(negValue, secp256k1.CreatePrivateKey());

                    var blindSum = pedersen.BlindSum(new List <byte[]> {
                        blindPos
                    }, new List <byte[]> {
                        blindNeg
                    });

                    var diff = posValue - negValue;

                    Assert.True(pedersen.VerifyCommitSum(new List <byte[]> {
                        Commit(posValue, blindPos)
                    }, new List <byte[]> {
                        Commit(negValue, blindNeg), Commit(diff, blindSum)
                    }));
                }
        }
        static void TestRangeProof()
        {
            using (var secp256k1 = new Secp256k1())
                using (var pedersen = new Pedersen())
                    using (var rangeProof = new RangeProof())
                    {
                        var blinding  = secp256k1.CreatePrivateKey();
                        var commit    = pedersen.Commit(100, blinding);
                        var msg       = "Message for signing";
                        var msgBytes  = Encoding.UTF8.GetBytes(msg);
                        var msgHash   = System.Security.Cryptography.SHA256.Create().ComputeHash(msgBytes);
                        var proof     = rangeProof.Proof(0, 100, blinding, commit, msgHash);
                        var verified  = rangeProof.Verify(commit, proof);
                        var proofInfo = rangeProof.Info(proof);

                        proofInfo = rangeProof.Rewind(commit, proof, blinding);

                        var badNonce = secp256k1.CreatePrivateKey();
                        var badInfo  = rangeProof.Rewind(commit, proof, badNonce);

                        commit = pedersen.Commit(0, blinding);
                        proof  = rangeProof.Proof(0, 0, blinding, commit, msgHash);
                        rangeProof.Verify(commit, proof);
                        proofInfo = rangeProof.Rewind(commit, proof, blinding);
                    }
        }
Exemple #20
0
        public static Address GetLegacyAddress(string _private = "", bool _mainnet = true)
        {
            _private = _private == "" ? RandomPlus.RandomHex(64) : _private;

            BigInteger _privateInt = BigInteger.Parse("0" + _private, NumberStyles.HexNumber);

            byte[] _public = Secp256k1.PrivateKeyToPublicKey(_privateInt, false);

            RIPEMD160Managed _ripemd = new RIPEMD160Managed();

            byte[] _ripemdHashed = _ripemd.ComputeHash(SHA.EncodeSHA256(_public));
            byte[] _addedVersion = new byte[_ripemdHashed.Length + 1];
            _addedVersion[0] = (byte)(_mainnet ? 0x00 : 0x6f);
            Array.Copy(_ripemdHashed, 0, _addedVersion, 1, _ripemdHashed.Length);

            byte[] _shaHashed = SHA.EncodeSHA256(SHA.EncodeSHA256(_addedVersion));
            Array.Resize(ref _shaHashed, 4);

            byte[] _result = new byte[_addedVersion.Length + _shaHashed.Length];
            Array.Copy(_addedVersion, 0, _result, 0, _addedVersion.Length);
            Array.Copy(_shaHashed, 0, _result, _addedVersion.Length, _shaHashed.Length);

            string _key1 = string.Join("", (_mainnet ? "80" : "ef"), _private);
            string _key2 = HexPlus.ByteArrayToHexString(SHA.EncodeSHA256(SHA.EncodeSHA256(HexPlus.HexStringToByteArray(_key1))).Take(4).ToArray());

            Address _address = new Address
            {
                Text    = Base58.Encode(_result),
                Public  = HexPlus.ByteArrayToHexString(_public),
                Private = Base58.Encode(_key1 + _key2)
            };

            return(_address);
        }
Exemple #21
0
        public static Address GenerateAddress(string _privateKey = "", bool _mainNet = true)
        {
            _privateKey = _privateKey == "" ? RandomPlus.RandomHex(64) : _privateKey;

            BigInteger _privateInt = BigInteger.Parse("0" + _privateKey, System.Globalization.NumberStyles.HexNumber);

            byte[] _publicKey = Secp256k1.PrivateKeyToPublicKey(_privateInt);

            SHA256Managed    _sha256 = new SHA256Managed();
            RIPEMD160Managed _ripemd = new RIPEMD160Managed();

            byte[] _ripemdHashed = _ripemd.ComputeHash(_sha256.ComputeHash(_publicKey));
            byte[] _addedVersion = new byte[_ripemdHashed.Length + 1];
            _addedVersion[0] = (byte)(_mainNet ? 0x00 : 0x6f);
            Array.Copy(_ripemdHashed, 0, _addedVersion, 1, _ripemdHashed.Length);

            byte[] _shaHashed = _sha256.ComputeHash(_sha256.ComputeHash(_addedVersion));
            Array.Resize(ref _shaHashed, 4);

            byte[] _result = new byte[_addedVersion.Length + _shaHashed.Length];
            Array.Copy(_addedVersion, 0, _result, 0, _addedVersion.Length);
            Array.Copy(_shaHashed, 0, _result, _addedVersion.Length, _shaHashed.Length);

            string _key1 = string.Join("", (_mainNet ? "80" : "ef"), _privateKey);
            string _key2 = HexPlus.ByteArrayToHexString(SHA.EncodeSHA256(SHA.EncodeSHA256(HexPlus.HexStringToByteArray(_key1))).Take(4).ToArray());

            Address _address = new Address();

            _address.Text       = Base58.Encode(_result);
            _address.PublicKey  = HexPlus.ByteArrayToHexString(_publicKey);
            _address.PrivateKey = Base58.Encode(_key1 + _key2);
            _address.Text       = (_mainNet ? (_address.Text.StartsWith("1") ? "" : "1") : "") + _address.Text;
            return(_address);
        }
Exemple #22
0
        /// <summary>
        /// Builds the receiver.
        /// </summary>
        /// <returns>The receiver.</returns>
        public CoinService BuildReceiver()
        {
            using (var secp256k1 = new Secp256k1())
                using (var pedersen = new Pedersen())
                {
                    var naTOutput = NaT(Output());
                    var blind     = DeriveKey(naTOutput);

                    byte[] blindSum = new byte[32];

                    try
                    {
                        blindSum = pedersen.BlindSum(new List <byte[]> {
                            blind, blind
                        }, new List <byte[]> {
                        });
                    }
                    catch (Exception ex)
                    {
                        logger.LogError($"Message: {ex.Message}\n Stack: {ex.StackTrace}");
                        throw ex;
                    }

                    var commitPos = Commit(naTOutput, blind);
                    var commitNeg = Commit(0, blind);

                    Stamp(GetNewStamp());
                    Version(-1);

                    mintedCoin     = BuildCoin(blindSum, commitPos, commitNeg, true);
                    receiverOutput = new ReceiverOutput(Output(), commitPos, blindSum);
                }

            return(this);
        }
Exemple #23
0
        /// <summary>
        /// Sign the specified amount, version, stamp, password and msg.
        /// </summary>
        /// <returns>The sign.</returns>
        /// <param name="amount">Amount.</param>
        /// <param name="version">Version.</param>
        /// <param name="stamp">Stamp.</param>
        /// <param name="password">Password.</param>
        /// <param name="msg">Message.</param>
        public byte[] Sign(ulong amount, int version, string stamp, SecureString password, byte[] msg)
        {
            if (string.IsNullOrEmpty(stamp))
            {
                throw new ArgumentNullException(nameof(stamp));
            }

            if (password == null)
            {
                throw new ArgumentNullException(nameof(password));
            }

            if (msg == null)
            {
                throw new ArgumentNullException(nameof(msg));
            }

            if (msg.Length > 32)
            {
                throw new IndexOutOfRangeException(nameof(msg));
            }

            using (var secp256k1 = new Secp256k1())
            {
                var blind = DeriveKey(version, stamp, password).FromHex();
                var sig   = secp256k1.Sign(msg, blind);

                return(sig);
            }
        }
Exemple #24
0
        public static Address GenerateAddress(out string _uncompressKey, string _existsPrivateKey = "", bool _mainNet = true)
        {
            string _netVersion = _mainNet ? "00" : "6f";
            string _privateKey = string.IsNullOrWhiteSpace(_existsPrivateKey) ? Lion.RandomPlus.RandomHex() : _existsPrivateKey;

            _uncompressKey = _privateKey;
            BigInteger    _bigPrivateKey = BigInteger.Parse("0" + _privateKey, System.Globalization.NumberStyles.HexNumber);
            var           _publicKey     = Secp256k1.PrivateKeyToPublicKey(_bigPrivateKey);
            SHA256Managed sha256         = new SHA256Managed();
            var           _ripemd        = new RIPEMD160Managed();
            var           _ripemdHashed  = _ripemd.ComputeHash(sha256.ComputeHash(_publicKey));
            var           _addedVersion  = new byte[_ripemdHashed.Length + 1];

            if (!_mainNet)
            {
                _addedVersion[0] = 0x6f;
            }
            Buffer.BlockCopy(_ripemdHashed, 0, _addedVersion, 1, _ripemdHashed.Length);
            var _doubleSha = sha256.ComputeHash(sha256.ComputeHash(_addedVersion));

            Array.Resize(ref _doubleSha, 4);

            byte[] _result = new byte[_addedVersion.Length + _doubleSha.Length];
            Buffer.BlockCopy(_addedVersion, 0, _result, 0, _addedVersion.Length);
            Buffer.BlockCopy(_doubleSha, 0, _result, _addedVersion.Length, _doubleSha.Length);

            Address _address = new Address();

            _address.Text       = Base58.Encode(_result);
            _address.PublicKey  = Lion.HexPlus.ByteArrayToHexString(_publicKey);
            _address.PrivateKey = CompressPrivateKey(_privateKey, _mainNet);
            _address.Text       = (_mainNet ? (_address.Text.StartsWith("1") ? "" : "1") : "") + _address.Text;
            return(_address);
        }
Exemple #25
0
        private void generateBtn_Click(object sender, EventArgs e)
        {
            var s = new Secp256k1();

            _keyPair           = WalletHelper.GenerateKeyPair(s);
            privateKeyTxt.Text = _keyPair.PrivateKey;
            publicKeyTxt.Text  = _keyPair.PublicKey;
        }
Exemple #26
0
 static KzPubKey()
 {
     lazySecp256k1 = new Lazy <Secp256k1>(() => {
         var ctx = new Secp256k1(sign: true, verify: true);
         ctx.Randomize(KzRandom.GetStrongRandBytes(32));
         return(ctx);
     }, true);
 }
Exemple #27
0
 public void SignatureNormalize()
 {
     using (var secp256k1 = new Secp256k1())
     {
         Span <byte> secretKey = "e815acba8fcf085a0b4141060c13b8017a08da37f2eb1d6a5416adbb621560ef".HexToBytes();
         Assert.False(secp256k1.SignatureNormalize(secretKey, secretKey));
     }
 }
        public void TestIsValidPrivateKey1()
        {
            var priKey1 = "0xdce1443bd2ef0c2631adc1c67e5c93f13dc23a41c18b536effbbdcbcdb96fb65";
            var priKey2 = "0x1c67e5c93f13dc23a41c18b536effbb1";

            Assert.True(Secp256k1.IsValidPrivateKey(priKey1.ToBytes()));
            Assert.False(Secp256k1.IsValidPrivateKey(priKey2.ToBytes()));
        }
Exemple #29
0
 public static string Private2Public(string _private, bool _base58 = false, bool _compressedPublicKey = false)
 {
     if (_base58)
     {
         byte[] _base58s = Base58.Decode(_private);
         _private = HexPlus.ByteArrayToHexString(_base58s.Skip(1).Take(_base58s.Length - 5).ToArray());
     }
     return(HexPlus.ByteArrayToHexString(Secp256k1.PrivateKeyToPublicKey(_private, _compressedPublicKey)));
 }
Exemple #30
0
 private static byte[] _PrivToPubKey(byte[] privKey)
 {
     using (var secp256K1 = new Secp256k1())
     {
         var pubKey = new byte[64];
         secp256K1.PublicKeyCreate(pubKey, privKey);
         return(pubKey);
     }
 }