Esempio n. 1
0
            public static bool TryFromScript(byte[] script, out PubKey pubKey)
            {
                if (script == null)
                    throw new ArgumentNullException(nameof(script));

                throw new NotImplementedException();
            }
 public FullBlockTestGenerator(Network network)
 {
     _Network = network;
     coinbaseOutKey = new Key();
     coinbaseOutKeyPubKey = coinbaseOutKey.PubKey;
     //Utils.rollMockClock(0); // Set a mock clock for timestamp tests
 }
Esempio n. 3
0
		public static Script CreatePaymentScript(int sigCount, PubKey[] uncoveredPubKeys)
		{
			if(sigCount == 1 && uncoveredPubKeys.Length == 1)
			{
				return PayToPubkeyHashTemplate.Instance.GenerateScriptPubKey(uncoveredPubKeys[0].Hash);
			}
			else
			{
				return PayToMultiSigTemplate.Instance.GenerateScriptPubKey(sigCount, uncoveredPubKeys);
			}
		}
Esempio n. 4
0
		public void CanUseSegwitAddress()
		{
			var address = (BitcoinWitPubKeyAddress)BitcoinAddress.Create("p2xtZoXeX5X8BP8JfFhQK2nD3emtjch7UeFm");
			Assert.Equal("0014010966776006953d5567439e5e39f86a0d273bee", address.ScriptPubKey.ToHex());
			Assert.Equal("0014010966776006953d5567439e5e39f86a0d273bee", address.Hash.ScriptPubKey.ToHex());
			Assert.Equal("3R1ZpeYRXx5oFtJWNoUwLFoACixRQ7sDQa", address.GetScriptAddress().ToString());

			//Example of the BIP
			var pubkey = new PubKey("0450863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B23522CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6");
			Assert.Equal(new Script("OP_0 010966776006953D5567439E5E39F86A0D273BEE"), pubkey.GetSegwitAddress(Network.Main).ScriptPubKey);
			Assert.Equal("p2xtZoXeX5X8BP8JfFhQK2nD3emtjch7UeFm", pubkey.GetSegwitAddress(Network.Main).ToString());
		}
Esempio n. 5
0
 private static Gen <TxOut> OutputFromRedeemOrKey(Script sc, PubKey key) =>
 sc != null?OutputFromRedeem(sc) : OutputFromKey(key);
Esempio n. 6
0
 public static void PubKeyNotCompressed(string argumentName, PubKey pk) =>
 throw new InvalidDataException($"invalid {argumentName}: public key must be compressed. {pk.ToHex()}");
        public static Transaction SetupValidTransaction(Features.Wallet.Wallet wallet, string password, HdAddress spendingAddress, PubKey destinationPubKey, HdAddress changeAddress, Money amount, Money fee)
        {
            var  spendingTransaction = spendingAddress.Transactions.ElementAt(0);
            Coin coin = new Coin(spendingTransaction.Id, (uint)spendingTransaction.Index, spendingTransaction.Amount, spendingTransaction.ScriptPubKey);

            var privateKey = Key.Parse(wallet.EncryptedSeed, password, wallet.Network);

            var         builder = new TransactionBuilder(wallet.Network);
            Transaction tx      = builder
                                  .AddCoins(new List <Coin> {
                coin
            })
                                  .AddKeys(new ExtKey(privateKey, wallet.ChainCode).Derive(new KeyPath(spendingAddress.HdPath)).GetWif(wallet.Network))
                                  .Send(destinationPubKey.ScriptPubKey, amount)
                                  .SetChange(changeAddress.ScriptPubKey)
                                  .SendFees(fee)
                                  .BuildTransaction(true);

            if (!builder.Verify(tx))
            {
                throw new WalletException("Could not build transaction, please make sure you entered the correct data.");
            }

            return(tx);
        }
Esempio n. 8
0
 public BitcoinWitPubKeyAddress GetP2wpkhAddress(Network network) => PubKey.GetSegwitAddress(network);
Esempio n. 9
0
			internal void AddKeyPubKey(Key key, PubKey pubkey)
			{
				_Keys.Add(Tuple.Create(key, pubkey));
			}
Esempio n. 10
0
		private static byte[] GenerateBytes(PubKey scanKey, PubKey[] pubKeys, BitField bitField, int signatureCount)
		{
			MemoryStream ms = new MemoryStream();
			ms.WriteByte(0); //Options
			ms.Write(scanKey.Compress().ToBytes(), 0, 33);
			ms.WriteByte((byte)pubKeys.Length);
			foreach(var key in pubKeys)
			{
				ms.Write(key.Compress().ToBytes(), 0, 33);
			}
			ms.WriteByte((byte)signatureCount);
			if(bitField == null)
				ms.Write(new byte[] { 0 }, 0, 1);
			else
			{
				ms.WriteByte((byte)bitField.BitCount);
				var raw = bitField.GetRawForm();
				ms.Write(raw, 0, raw.Length);
			}
			return ms.ToArray();
		}
 public SignedContractsPoARegTest()
 {
     this.Name = "SignedContractsPoARegTest";
     this.SigningContractPrivKey = new Mnemonic("lava frown leave wedding virtual ghost sibling able mammal liar wide wisdom").DeriveExtKey().PrivateKey;
     this.SigningContractPubKey  = this.SigningContractPrivKey.PubKey;
 }
Esempio n. 12
0
        public bool VerifySignature(string url, PubKey key)
        {
            uint256 hash = new uint256(Hashes.SHA256(Encoding.UTF8.GetBytes(GetMessage(url))));

            return(key.Verify(hash, new ECDSASignature(Encoders.Hex.DecodeData(Signature))));
        }
Esempio n. 13
0
 public EscrowScriptPubKeyParameters(PubKey initiator, PubKey receiver, LockTime lockTime)
 {
     this.Initiator = initiator;
     this.Receiver  = receiver;
     this.LockTime  = lockTime;
 }
        private TxOut BuildToRemoteOutput(ulong toRemote)
        {
            PubKey pubKey = new PubKey(RemotePaymentPubKey.PublicKeyCompressed);

            return(new TxOut(Money.Satoshis(toRemote), pubKey.WitHash.ScriptPubKey));
        }
Esempio n. 15
0
        public static bool Match(BitcoinExtPubKey bitcoinExtPubKey, int change, int i, FilterModel[] filterArray, out PubKey pubKey)
        {
            KeyPath path = new KeyPath($"{change}/{i}");

            pubKey = bitcoinExtPubKey.ExtPubKey.Derive(path).PubKey;
            byte[] bytes = pubKey.WitHash.ScriptPubKey.ToCompressedBytes();

            foreach (var filterModel in filterArray)
            {
                bool?matchFoundNow = filterModel.Filter?.Match(bytes, filterModel.FilterKey);
                if (matchFoundNow is true)
                {
                    return(true);
                }
            }

            return(false);
        }
        /// <summary>
        /// Checks if block signature is valid.
        /// </summary>
        /// <param name="block">The block.</param>
        /// <returns><c>true</c> if the signature is valid, <c>false</c> otherwise.</returns>
        private bool CheckBlockSignature(Block block)
        {
            this.Logger.LogTrace("()");

            if (BlockStake.IsProofOfWork(block))
            {
                bool res = block.BlockSignatur.IsEmpty();
                this.Logger.LogTrace("(-)[POW]:{0}", res);
                return(res);
            }

            if (block.BlockSignatur.IsEmpty())
            {
                this.Logger.LogTrace("(-)[EMPTY]:false");
                return(false);
            }

            TxOut txout = block.Transactions[1].Outputs[1];

            if (PayToPubkeyTemplate.Instance.CheckScriptPubKey(txout.ScriptPubKey))
            {
                PubKey pubKey = PayToPubkeyTemplate.Instance.ExtractScriptPubKeyParameters(txout.ScriptPubKey);
                bool   res    = pubKey.Verify(block.GetHash(), new ECDSASignature(block.BlockSignatur.Signature));
                this.Logger.LogTrace("(-)[P2PK]:{0}", res);
                return(res);
            }

            // Block signing key also can be encoded in the nonspendable output.
            // This allows to not pollute UTXO set with useless outputs e.g. in case of multisig staking.

            List <Op> ops = txout.ScriptPubKey.ToOps().ToList();

            if (!ops.Any()) // script.GetOp(pc, opcode, vchPushValue))
            {
                this.Logger.LogTrace("(-)[NO_OPS]:false");
                return(false);
            }

            if (ops.ElementAt(0).Code != OpcodeType.OP_RETURN) // OP_RETURN)
            {
                this.Logger.LogTrace("(-)[NO_OP_RETURN]:false");
                return(false);
            }

            if (ops.Count < 2) // script.GetOp(pc, opcode, vchPushValue)
            {
                this.Logger.LogTrace("(-)[NO_SECOND_OP]:false");
                return(false);
            }

            byte[] data = ops.ElementAt(1).PushData;
            if (!ScriptEvaluationContext.IsCompressedOrUncompressedPubKey(data))
            {
                this.Logger.LogTrace("(-)[NO_PUSH_DATA]:false");
                return(false);
            }

            bool verifyRes = new PubKey(data).Verify(block.GetHash(this.Parent.ConsensusParams.NetworkOptions), new ECDSASignature(block.BlockSignatur.Signature));

            this.Logger.LogTrace("(-):{0}", verifyRes);
            return(verifyRes);
        }
Esempio n. 17
0
        private void Peer_NewMessage(object sender, Message message)
        {
            if (ProcessedMessages.Contains(message))
            {
                return;
            }
            ProcessedMessages.Add(message);
            Console.Write($"{Name} received message: ");
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine(message);
            Console.ResetColor();

            NewMessage?.Invoke(this, message);

            if (message.Type == MessageType.PublicKey)
            {
                var pubKey = new PubKey(message.GetDataString());
                AllPubKeys.Add(pubKey);

                if (AllPubKeys.Count == RequiredPeerCount)
                {
                    // every participant (say participant i in a predefined shuffling
                    // order) uses the encryption keys of every participant j > i to create a layered
                    // encryption of her output address.
                    string onion = OnionEncrypt(AllPubKeys, OutputScript.ToString());
                    Broadcast(new Message(MessageType.Onions, onion));
                }
            }
            else if (message.Type == MessageType.Onions)
            {
                var onions = message.GetDataCollection();
                if (onions.Count() == 1)
                {
                    Onions.Add(onions.Single());

                    if (Onions.Count == RequiredPeerCount)
                    {
                        if (SecretKey.CanDecrypt(Onions.First()))
                        {
                            var stripped = Decrypt(SecretKey, Onions).ToList();
                            stripped.Shuffle();
                            Broadcast(new Message(MessageType.Onions, stripped));
                        }
                    }
                }
                else if (SecretKey.CanDecrypt(onions.First()))
                {
                    var stripped = Decrypt(SecretKey, onions).ToList();
                    stripped.Shuffle();

                    if (NBitcoinHelpers.IsScript(stripped.First()))
                    {
                        Broadcast(new Message(MessageType.ShuffledScripts, stripped));
                    }
                    else
                    {
                        Broadcast(new Message(MessageType.Onions, stripped));
                    }
                }
            }
        }
Esempio n. 18
0
		public void CanVerifyTrezorSignature()
		{
			string visual_challenge = "2015-03-23 17:39:22";
			byte[] random_challenge = Encoders.Hex.DecodeData("cd8552569d6e4509266ef137584d1e62c7579b5b8ed69bbafa4b864c6521e7c2");
			byte[] signature = Encoders.Hex.DecodeData("20f2d1a42d08c3a362be49275c3ffeeaa415fc040971985548b9f910812237bb41770bf2c8d488428799fbb7e52c11f1a3404011375e4080e077e0e42ab7a5ba02");

			var hiddenChallenge_Sha = Hashes.SHA256(random_challenge);
			var visualChallenge_Sha = Hashes.SHA256(Encoding.ASCII.GetBytes(visual_challenge));

			PubKey pubKey = new PubKey("023a472219ad3327b07c18273717bb3a40b39b743756bf287fbd5fa9d263237f45");
			bool verified = pubKey.VerifyMessage(hiddenChallenge_Sha.Concat(visualChallenge_Sha).ToArray(), Encoders.Base64.EncodeData(signature));
			Assert.True(verified);
		}
Esempio n. 19
0
 public BitcoinBlindedAddress(PubKey blindingKey, BitcoinAddress address)
     : base(GetBase58(blindingKey, address), address.Network)
 {
     _BlindingKey      = blindingKey;
     _UnblindedAddress = address;
 }
Esempio n. 20
0
 public SchnorrPubKey(PubKey signerPubKey, PubKey rPubKey)
 {
     SignerPubKey = Guard.NotNull(nameof(signerPubKey), signerPubKey);
     RpubKey      = Guard.NotNull(nameof(rPubKey), rPubKey);
 }
Esempio n. 21
0
        /// <summary>
        /// Try to interpret the given string in a few ways in order to detect what object it's supposed to represent.
        /// </summary>
        /// <returns>The object represented by the input string. This may be a Bitcoin address, a script, a signature, a public key, etc.</returns>
        public async Task <object> Find(string data)
        {
            data = data.Trim();


            // Is it a Bitcoin address?
            var b58 = NoException(() => WhatIsBase58.GetFromBitcoinString(data));

            if (b58 != null)
            {
                if (b58 is WhatIsAddress address)
                {
                    await TryFetchRedeemOrPubKey(address);  // Shouldn't the return value here be checked?
                }

                return(b58);
            }


            // Is it a transaction ID?
            if (data.Length == 0x40)
            {
                try
                {
                    return(await Controller.JsonTransaction(uint256.Parse(data), false));
                }
                catch
                {
                    // Well, apparently it's not a transaction ID.
                }
            }


            // Is it a block feature?
            var b = NoException(() => Controller.JsonBlock(BlockFeature.Parse(data), true, false));

            if (b != null)
            {
                return(b);
            }


            // Is it the hash of a public key (modeled as KeyId in NBitcoin), or is it the hash of a script ID?
            if (data.Length == 0x28) // Hash of pubkey or script
            {
                TxDestination dest = new KeyId(data);

                var address = new WhatIsAddress(dest.GetAddress(Network));

                if (await TryFetchRedeemOrPubKey(address))
                {
                    return(address);
                }

                dest    = new ScriptId(data);
                address = new WhatIsAddress(dest.GetAddress(Network));

                if (await TryFetchRedeemOrPubKey(address))
                {
                    return(address);
                }
            }


            // Is it a script?
            var script = NoException(() => GetScriptFromBytes(data));

            if (script != null)
            {
                return(new WhatIsScript(script, Network));
            }

            script = NoException(() => GetScriptFromText(data));

            if (script != null)
            {
                return(new WhatIsScript(script, Network));
            }


            // Is it a transaction signature?
            var sig = NoException(() => new TransactionSignature(Encoders.Hex.DecodeData(data)));

            if (sig != null)
            {
                return(new WhatIsTransactionSignature(sig));
            }


            // Is it a hexstring representing the bytes of a public key?
            var pubkeyBytes = NoException(() => Encoders.Hex.DecodeData(data));

            if (pubkeyBytes != null && PubKey.Check(pubkeyBytes, true))
            {
                var pubKey = NoException(() => new PubKey(data));

                if (pubKey != null)
                {
                    return(new WhatIsPublicKey(pubKey, Network));
                }
            }


            // Is it a blockheader?
            if (data.Length == 80 * 2)
            {
                var blockHeader = NoException(() =>
                {
                    var h = ConsensusFactory.CreateBlockHeader();
                    h.ReadWrite(Encoders.Hex.DecodeData(data), ConsensusFactory);
                    return(h);
                });

                if (blockHeader != null)
                {
                    return(new WhatIsBlockHeader(blockHeader));
                }
            }


            // No idea what this is.
            return(null);
        }
Esempio n. 22
0
        public static bool VerifySignature(uint256 message, UnblindedSignature signature, PubKey signerPubKey)
        {
            if (!Context.Instance.TryCreatePubKey(signerPubKey.ToBytes(), out var signerECPubkey))
            {
                throw new FormatException("Invalid signer pubkey.");
            }

            var p = signerECPubkey.Q;

            var sG = (signature.S * EC.G).ToGroupElement();
            var cP = p * signature.C;
            var r  = cP + sG;
            var t  = r.ToGroupElement().x.Normalize();

            using var sha = new SHA256();
            Span <byte> tmp = stackalloc byte[32];

            message.ToBytes(tmp, false);
            sha.Write(tmp);
            t.WriteToSpan(tmp);
            sha.Write(tmp);
            sha.GetHash(tmp);
            return(new Scalar(tmp) == signature.C);
        }
 public StealthPaymentScanner(BitField prefix, PubKey[] spendKeys, Key scan)
 {
     _Scan = scan;
     _Prefix = prefix;
     _SpendKeys = spendKeys.ToArray();
 }
Esempio n. 24
0
            public uint256 BlindScript(PubKey signerPubKey, PubKey rPubKey, Script script)
            {
                var msg = new uint256(Hashes.SHA256(script.ToBytes()));

                return(BlindMessage(msg, rPubKey, signerPubKey));
            }
 /// <summary>
 /// Generates the scriptSig.
 /// </summary>
 /// <param name="signature">The transaction signature. For unsigned inputs this can be <c>null</c> in which case it is encoded as an <c>OP_0</c>.</param>
 /// <param name="coldPubKey">A flag indicating whether the cold wallet versus the hot wallet is signing.</param>
 /// <param name="publicKey">The cold or hot wallet public key.</param>
 /// <returns>The scriptSig.</returns>
 public Script GenerateScriptSig(TransactionSignature signature, bool coldPubKey, PubKey publicKey)
 {
     return(new Script(
                Op.GetPushOp(signature.ToBytes()),
                coldPubKey ? OpcodeType.OP_0 : OpcodeType.OP_1,
                Op.GetPushOp(publicKey.ToBytes())
                ));
 }
Esempio n. 26
0
            public uint256 BlindMessage(uint256 message, PubKey rpubkey, PubKey signerPubKey)
            {
                var         ctx = new ECMultGenContext();
                Span <byte> tmp = stackalloc byte[32];

                if (!Context.Instance.TryCreatePubKey(signerPubKey.ToBytes(), out var signerECPubkey))
                {
                    throw new FormatException("Invalid signer pubkey.");
                }
                if (!Context.Instance.TryCreatePubKey(rpubkey.ToBytes(), out var rECPubKey))
                {
                    throw new FormatException("Invalid r pubkey.");
                }

                var p = signerECPubkey.Q;
                var r = rECPubKey.Q.ToGroupElementJacobian();
                var t = FE.Zero;

retry:

                RandomUtils.GetBytes(tmp);
                _v = new Scalar(tmp, out int overflow);
                if (overflow != 0 || _v.IsZero)
                {
                    goto retry;
                }

                RandomUtils.GetBytes(tmp);
                _w = new Scalar(tmp, out overflow);
                if (overflow != 0 || _v.IsZero)
                {
                    goto retry;
                }

                var a1 = ctx.MultGen(_v);
                var a2 = _w * p;
                var a  = r.AddVariable(a1, out _).AddVariable(a2, out _).ToGroupElement();

                t = a.x.Normalize();
                if (t.IsZero)
                {
                    goto retry;
                }

                using (var sha = new SHA256())
                {
                    message.ToBytes(tmp, false);
                    sha.Write(tmp);
                    t.WriteToSpan(tmp);
                    sha.Write(tmp);
                    sha.GetHash(tmp);
                }
                _c = new Scalar(tmp, out overflow);
                if (overflow != 0 || _c.IsZero)
                {
                    goto retry;
                }

                var cp = _c + _w.Negate();                 // this is sent to the signer (blinded message)

                if (cp.IsZero)
                {
                    goto retry;
                }

                cp.WriteToSpan(tmp);
                return(new uint256(tmp));
            }
Esempio n. 27
0
        private void RemoveFederationMember(byte[] pubKeyBytes)
        {
            var key = new PubKey(pubKeyBytes);

            this.federationManager.RemoveFederationMember(key);
        }
Esempio n. 28
0
 public BitcoinStealthAddress(PubKey scanKey, PubKey[] pubKeys, int signatureCount, BitField bitfield, Network network)
     : base(GenerateBytes(scanKey, pubKeys, bitfield, signatureCount), network)
 {
 }
Esempio n. 29
0
        static void Main(string[] args)
        {
            Key privateKey = new Key();

            // Generting Bitcoin Secret from Private Key for the Main Network
            BitcoinSecret mainNetPrivateKey = privateKey.GetBitcoinSecret(Network.Main);
            // Generting Bitcoin Secret from Private Key for the Test Network
            BitcoinSecret testNetPrivateKey = privateKey.GetBitcoinSecret(Network.TestNet);

            Console.WriteLine(mainNetPrivateKey);
            Console.WriteLine(testNetPrivateKey);

            bool WifISBitcoinSecret = mainNetPrivateKey == privateKey.GetWif(Network.Main);

            Console.WriteLine(WifISBitcoinSecret);

            //Generating Private Key from Bitcoin Secret
            Key samePrivateKey = mainNetPrivateKey.PrivateKey;

            Console.WriteLine(samePrivateKey == privateKey);

            PubKey publicKey = privateKey.PubKey;
            BitcoinPubKeyAddress bitcoinPublicKey = publicKey.GetAddress(Network.Main);

            //Not possible to get the Public Key from Bitcoin Address

            //Generting Bitcoin Address
            Console.WriteLine(publicKey);
            Console.WriteLine(publicKey.GetAddress(Network.Main));    //Using Main Network
            Console.WriteLine(publicKey.GetAddress(Network.TestNet)); //Using TestNet Network

            var publicKeyHash = publicKey.Hash;

            Console.WriteLine(publicKeyHash);
            var mainNetAddress = publicKeyHash.GetAddress(Network.Main);    //Using Main Network
            var testNetAddress = publicKeyHash.GetAddress(Network.TestNet); //Using TestNet Network

            Console.WriteLine(mainNetAddress);
            Console.WriteLine(testNetAddress);

            //Generating ScriptPubKey from Bitcoin Address
            Console.WriteLine(mainNetAddress.ScriptPubKey);
            Console.WriteLine(testNetAddress.ScriptPubKey);


            //Generating Public Bitcoin Address from ScriptPubKey
            var paymentScript      = publicKeyHash.ScriptPubKey;
            var sameMainNetAddress = paymentScript.GetDestinationAddress(Network.Main);

            //True: Bitcoin Address for Main is same as Bitcoin Address Generated from ScriptPubKey
            Console.WriteLine(mainNetAddress == sameMainNetAddress);

            //Generating Public Key Hash from ScriptPubKey
            var samePublicKeyHash = (KeyId)paymentScript.GetDestination();

            //True: Public Key Hash is same as public key has generated from ScriptPubKey
            Console.WriteLine(publicKeyHash == samePublicKeyHash);
            var sameMainNetAddress2 = new BitcoinPubKeyAddress(samePublicKeyHash, Network.Main);

            Console.WriteLine(mainNetAddress == sameMainNetAddress2); //True

            Transaction tx = new Transaction("0100000009dd9e20cecf519ce7cdec2c4890e60bbff540b2fafdca2b426304fd8fefc58847000000006b483045022100d08870b424f19d8b3921861bedec81599a9cd5f179e35e80d16709a296d41484022023f1c2a9eab7d5dd8a1043d1d423e185641e79d33f32491638c7caf6029105410121035904165d4ed4aae69b1adef8dd99a21dac2c1ad479188d9d7de3b341aae229deffffffffc5a6457d1532d7cfe5dc6802323806bfd81c365bc4bb9fdadd8cfb2fd39280c3000000006b483045022100f337bc11e419e2317a59a0acd33c2937823aa2b015a1579bd6caab6f55dc828602201cc6985189b2b654ee9b71850697460086429c91f5e90598ca927dfbe315a3940121034e1304481c7403a35e1348289468df9982bbd516a3aedb7f1bc81667f7a09c5dffffffffa94e871f35a616b5a22139cc7dc5a4da35061d6317accb935a4af037573c1dc3000000008a473044022045476041f0d2910269ee4e707dda5678af483339962c0a2d7897c3aa78cb29ea0220476032a6bbe59e67ad5f95cc2f3e5264bb2bca8ea88eb30c96123b9ff7a33a5001410482d593f88a39160eaed14470ee4dad283c29e88d9abb904f953115b1a93d6f3881d6f8c29c53ddb30b2d1c6b657068d60a93ed240d5efca247836f6395807bcdffffffff8d199257330921571d8984bf38c47304b26e3c497a09acc298941e60b998ccfb010000008b483045022100fc8e579f4cabda1e26a294b3f7f227087b64ca2451155b8747bd1f6c96780d6d022041912d38512030e1ec1d3df6b8d91d8b9aa4c564642fd7cafc48f97fd550100101410482d593f88a39160eaed14470ee4dad283c29e88d9abb904f953115b1a93d6f3881d6f8c29c53ddb30b2d1c6b657068d60a93ed240d5efca247836f6395807bcdffffffff0246c072469f817ec87273c0a0d6b30fc840a6aa31f56427cca2ce31163c49fd000000006a473044022034cd8a6ecc391539af0e0af1075cf48599a40fb011936f2397a6b457e5fb60bd02201d059c7cf571d80bb6ead165639334fc6e45985c34a0cf7bc10d9a1817d22d0501210249af09f7a52e81c6de1df85a00792522df76b6a529178673d27754772f5d2758ffffffff2515c8cbc51039bc50bc8b4504617410824d1858dcff721ab3716dae44f350a9000000008b48304502210095a36910e3a466697f0a3a42cd0e487c280b1d48f8a8ea3d2867c1bb6fa6a4cf0220486eb68f95ae081e42dd48cb96d01b9536761e17b4f2ae10935aa406ceed268d01410482d593f88a39160eaed14470ee4dad283c29e88d9abb904f953115b1a93d6f3881d6f8c29c53ddb30b2d1c6b657068d60a93ed240d5efca247836f6395807bcdffffffff36c456759b51e87a75673d8bd8a1d91177164767ea937a4365578930cd8bf855000000006b483045022100eae7bf8ead57bedc858700ff7e8f0f917650a97d905ecc5264c29c6a4e87f7ac022055483fac8618831d163370bb8a083aff5111c795bafdbd48693cf98b5f2e420b012103b1534714e589d87484e2305e32261fc157a7ddd3ca060f5293a3dfbc76b7576bffffffff50a85ca81a0c667b6484ac371493be2a5298fe9e04b095f545cc795ba7dfda19000000006b483045022100dab39ceb5f48718fd3f7f549f5cb28fdd9bca755d031a15f608ebc7902ede62502200fcd17229262dd183fbc134279a9139d9e2a1e1e5723adfec8f3599e3f62b6ed0121025fbd9ac3c3277a06e623dfed29f9d490c643c023987a0412308c4a8e78b12b55ffffffff66fb69807af8e4d8f0cbfece1f02fed8c130c168f3b06d10640d02ffdebf2d90000000008b483045022100df2e15424b9664be46e5eef90030b557655ffd4b9f1dfc4dfd5a0422e8e8d13202204c94a8c9975f914f7926cda55b04193328f612d154fa6c6c908c88b4a4f9729201410482d593f88a39160eaed14470ee4dad283c29e88d9abb904f953115b1a93d6f3881d6f8c29c53ddb30b2d1c6b657068d60a93ed240d5efca247836f6395807bcdffffffff01a4c5a84e000000001976a914b6cefbb855cabf6ee45598f518a98011c22961aa88ac00000000");

            Console.WriteLine(tx);


            Console.ReadLine();
        }
Esempio n. 30
0
 public static Gen <Script> FromKey(PubKey key)
 {
     return(Gen.Constant(new Script()));
 }
Esempio n. 31
0
 private static Gen <TxOut> OutputFromKey(PubKey key) =>
 from money in MoneyGenerator.Money()
 from isP2WPKH in PrimitiveGenerator.Bool()
 from isP2SH in PrimitiveGenerator.Bool()
 let scriptPubKey = (isP2SH && isP2WPKH) ? key.WitHash.ScriptPubKey.Hash.ScriptPubKey : isP2WPKH ? key.WitHash.ScriptPubKey : key.Hash.ScriptPubKey
                    select new TxOut(money, scriptPubKey);
Esempio n. 32
0
		public bool CheckSignature(PubKey key)
		{
			if (key == null) throw new ArgumentNullException("key");
			return key.Verify(Hashes.Hash256(payload.GetString()), signature.GetString());
		}
Esempio n. 33
0
 public PubKeyScanner(PubKey pubKey)
 {
     _PubKey = pubKey;
 }
Esempio n. 34
0
		public void CanUseSegwitAddress()
		{
			var address = (BitcoinWitPubKeyAddress)BitcoinAddress.Create("p2xuirpcDHjyETjKozsw1S19Hs23q6wJxvvX");
			Assert.Equal("00140db804a04a249f53c53e1b3619a1411b4c41e2e2", address.ScriptPubKey.ToHex());
			Assert.Equal("00140db804a04a249f53c53e1b3619a1411b4c41e2e2", address.Hash.ScriptPubKey.ToHex());
			Assert.Equal("MUGbdic7BDYtn2K7TVyk47aArXKGk9XC1j", address.GetScriptAddress().ToString());
			Assert.Equal("a914df70747a4fce42b9f8dc62318da432d067669eff87", address.GetScriptAddress().ScriptPubKey.ToHex());

			//Example of the BIP
			var pubkey = new PubKey("0450863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B23522CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6");
			Assert.Equal(new Script("OP_0 010966776006953D5567439E5E39F86A0D273BEE"), pubkey.GetSegwitAddress(Network.Main).ScriptPubKey);
			Assert.Equal("YMeG5MzsnmVKk86fzdjzhfJ5FXmexT8gvwi5", pubkey.GetSegwitAddress(Network.Main).ToString());
		}
Esempio n. 35
0
        public static EscrowScriptPubKeyParameters ExtractEscrowScriptPubKeyParameters(Script script)
        {
            var ops = script.ToOps().ToArray();

            if (ops.Length != 16)
            {
                return(null);
            }
            try
            {
                if (ops[0].Code != OpcodeType.OP_DEPTH ||
                    ops[1].Code != OpcodeType.OP_3 ||
                    ops[2].Code != OpcodeType.OP_EQUAL ||
                    ops[3].Code != OpcodeType.OP_IF ||
                    ops[4].Code != OpcodeType.OP_2)
                {
                    return(null);
                }

                var k1 = new PubKey(ops[5].PushData);
                var k2 = new PubKey(ops[6].PushData);

                if (ops[7].Code != OpcodeType.OP_2 ||
                    ops[8].Code != OpcodeType.OP_CHECKMULTISIG ||
                    ops[9].Code != OpcodeType.OP_ELSE)
                {
                    return(null);
                }

                var timeout = new LockTime((uint)ops[10].GetLong().Value);

                if (ops[11].Code != OpcodeType.OP_CHECKLOCKTIMEVERIFY ||
                    ops[12].Code != OpcodeType.OP_DROP)
                {
                    return(null);
                }

                var redeem = new PubKey(ops[13].PushData);

                if (ops[14].Code != OpcodeType.OP_CHECKSIG ||
                    ops[15].Code != OpcodeType.OP_ENDIF)
                {
                    return(null);
                }
                var keys        = new[] { k1, k2 };
                var orderedKeys = keys.OrderBy(o => o.ToHex()).ToArray();
                if (!keys.SequenceEqual(orderedKeys))
                {
                    return(null);
                }
                return(new EscrowScriptPubKeyParameters
                {
                    EscrowKeys = new[] { k1, k2 },
                    LockTime = timeout,
                    RedeemKey = redeem
                });
            }
            catch
            {
                return(null);
            }
        }
Esempio n. 36
0
        public BitcoinBlindedAddress(string base58, Network network)
            : base(base58, network)
        {
            var prefix  = network.GetVersionBytes(Base58Type.BLINDED_ADDRESS, true);
            var version = network.GetVersionBytes(Base58Type.PUBKEY_ADDRESS, false);
            var blech32 = network.GetBech32Encoder(Bech32Type.BLINDED_ADDRESS, false);

            if (blech32 != null && NBitcoin.DataEncoders.Encoders.ASCII
                .DecodeData(base58.Substring(0, blech32.HumanReadablePart.Length))
                .SequenceEqual(blech32.HumanReadablePart))
            {
                var    vchData  = blech32.Decode(base58, out var witnessVerion);
                bool   p2pkh    = !(version == null || !StartWith(prefix.Length, vchData, version));
                var    script   = false;
                var    blinding = vchData.SafeSubarray(0, 33);
                byte[] hash;
                if (vchData.Length == 53)
                {
                    hash = vchData.SafeSubarray(version.Length + 32, 20);
                }
                else
                {
                    hash   = vchData.SafeSubarray(version.Length + 32, vchData.Length - version.Length - 32);
                    script = true;
                }
                if (PubKey.Check(blinding, true))
                {
                    _BlindingKey = new PubKey(blinding);
                    if (witnessVerion == 0)
                    {
                        _UnblindedAddress = script?  (BitcoinAddress) new BitcoinWitScriptAddress(new WitScriptId(hash), network):  new BitcoinWitPubKeyAddress(new WitKeyId(hash), network);
                    }
                    else if (witnessVerion > 16 || hash.Length < 2 || hash.Length > 40)
                    {
                        throw new FormatException("Invalid Bitcoin Blinded Address");
                    }
                }
                else
                {
                    throw new FormatException("Invalid Bitcoin Blinded Address");
                }
            }
            else
            {
                var  vchData = NBitcoin.DataEncoders.Encoders.Base58Check.DecodeData(base58);
                bool p2pkh   = true;
                if (version == null || !StartWith(prefix.Length, vchData, version))
                {
                    p2pkh   = false;
                    version = network.GetVersionBytes(Base58Type.SCRIPT_ADDRESS, false);
                    if (version == null || !StartWith(prefix.Length, vchData, version))
                    {
                        throw new FormatException("Invalid Bitcoin Blinded Address");
                    }
                }

                if (vchData.Length != prefix.Length + version.Length + 33 + 20)
                {
                    throw new FormatException("Invalid Bitcoin Blinded Address");
                }
                var blinding = vchData.SafeSubarray(prefix.Length + version.Length, 33);
                if (PubKey.Check(blinding, true))
                {
                    _BlindingKey = new PubKey(blinding);

                    var hash = vchData.SafeSubarray(prefix.Length + version.Length + 33, 20);
                    _UnblindedAddress =
                        p2pkh
                                                        ? (BitcoinAddress) new BitcoinPubKeyAddress(new KeyId(hash), network)
                                                        : new BitcoinScriptAddress(new ScriptId(hash), network);
                }
                else
                {
                    throw new FormatException("Invalid Bitcoin Blinded Address");
                }
            }
        }
Esempio n. 37
0
		public void CanGenerateScriptFromAddress()
		{
			var address = new BitcoinPubKeyAddress(new KeyId("47376c6f537d62177a2c41c4ca9b45829ab99083"), Network.Main);
			Assert.Equal("OP_DUP OP_HASH160 47376c6f537d62177a2c41c4ca9b45829ab99083 OP_EQUALVERIFY OP_CHECKSIG", address.ScriptPubKey.ToString());

			var scriptAddress = new BitcoinScriptAddress(new ScriptId("8f55563b9a19f321c211e9b9f38cdf686ea07845"), Network.Main);
			Assert.Equal("OP_HASH160 8f55563b9a19f321c211e9b9f38cdf686ea07845 OP_EQUAL", scriptAddress.ScriptPubKey.ToString());

			var pubKey = new PubKey("0359d3092e4a8d5f3b3948235b5dec7395259273ccf3c4e9d5e16695a3fc9588d6");
			Assert.Equal("OP_DUP OP_HASH160 4d29186f76581c7375d70499afd1d585149d42cd OP_EQUALVERIFY OP_CHECKSIG", pubKey.Hash.ScriptPubKey.ToString());
			Assert.Equal("0359d3092e4a8d5f3b3948235b5dec7395259273ccf3c4e9d5e16695a3fc9588d6 OP_CHECKSIG", pubKey.ScriptPubKey.ToString());

			Script script = new Script("0359d3092e4a8d5f3b3948235b5dec7395259273ccf3c4e9d5e16695a3fc9588d6 OP_CHECKSIG");
			Assert.Equal("OP_HASH160 a216e3bce8c1b3adf376731b6cd0b6936c4e053f OP_EQUAL", script.PaymentScript.ToString());
		}
Esempio n. 38
0
        public object Find(string data)
        {
            data = data.Trim();
            var b58 = NoException(() => WhatIsBase58.GetFromBase58Data(data));

            if (b58 != null)
            {
                if (b58 is WhatIsAddress)
                {
                    var address = (WhatIsAddress)b58;
                    TryFetchRedeemOrPubKey(address);
                }
                return(b58);
            }

            if (data.Length == 0x40)
            {
                var tx = NoException(() => Controller.JsonTransaction(new uint256(data)));
                if (tx != null)
                {
                    return(tx);
                }
            }
            var b = NoException(() => Controller.JsonBlock(BlockFeature.Parse(data), true));

            if (b != null)
            {
                return(b);
            }

            if (data.Length == 0x28) //Hash of pubkey or script
            {
                TxDestination dest    = new KeyId(data);
                var           address = new WhatIsAddress(dest.GetAddress(Network));
                if (TryFetchRedeemOrPubKey(address))
                {
                    return(address);
                }

                dest    = new ScriptId(data);
                address = new WhatIsAddress(dest.GetAddress(Network));
                if (TryFetchRedeemOrPubKey(address))
                {
                    return(address);
                }
            }


            var script = NoException(() => GetScriptFromBytes(data));

            if (script != null)
            {
                return(new WhatIsScript(script, Network));
            }
            script = NoException(() => GetScriptFromText(data));
            if (script != null)
            {
                return(new WhatIsScript(script, Network));
            }

            var sig = NoException(() => new TransactionSignature(Encoders.Hex.DecodeData(data)));

            if (sig != null)
            {
                return(new WhatIsTransactionSignature(sig));
            }

            var pubkeyBytes = NoException(() => Encoders.Hex.DecodeData(data));

            if (pubkeyBytes != null && PubKey.Check(pubkeyBytes, true))
            {
                var pubKey = NoException(() => new PubKey(data));
                if (pubKey != null)
                {
                    return(new WhatIsPublicKey(pubKey, Network));
                }
            }

            if (data.Length == 80 * 2)
            {
                var blockHeader = NoException(() =>
                {
                    var h = new BlockHeader();
                    h.ReadWrite(Encoders.Hex.DecodeData(data));
                    return(h);
                });
                if (blockHeader != null)
                {
                    return(new WhatIsBlockHeader(blockHeader));
                }
            }
            return(null);
        }
Esempio n. 39
0
		public BitcoinStealthAddress(PubKey scanKey, PubKey[] pubKeys, int signatureCount, BitField bitfield, Network network)
			: base(GenerateBytes(scanKey, pubKeys, bitfield, signatureCount), network)
		{
		}
Esempio n. 40
0
        public async Task <ISegwitPrivateWallet> CreateSegwitWallet()
        {
            var segwitPubKey = new PubKey(await _signatureApiProvider.GeneratePubKey());

            return(await CreateSegwitWallet(segwitPubKey));
        }
Esempio n. 41
0
		public static Script CreatePaymentScript(int sigCount, PubKey[] spendPubKeys, Key ephemKey, PubKey scanPubKey)
		{
			return CreatePaymentScript(sigCount, spendPubKeys.Select(p => p.Uncover(ephemKey, scanPubKey)).ToArray());
		}
        public static bool VerifySignature(uint256 message, UnblindedSignature signature, PubKey signerPubKey)
        {
            var P = signerPubKey.ECKey.GetPublicKeyParameters().Q;

            var sG = Secp256k1.G.Multiply(signature.S);
            var cP = P.Multiply(signature.C);
            var R  = cP.Add(sG).Normalize();
            var t  = R.AffineXCoord.ToBigInteger().Mod(Secp256k1.N);
            var c  = new BigInteger(1, Hashes.SHA256(message.ToBytes(false).Concat(Utils.BigIntegerToBytes(t, 32))));

            return(c.Equals(signature.C));
        }
Esempio n. 43
0
		public static Script CreatePaymentScript(BitcoinStealthAddress address, PubKey ephemKey, Key scan)
		{
			return CreatePaymentScript(address.SignatureCount, address.SpendPubKeys.Select(p => p.UncoverReceiver(scan, ephemKey)).ToArray());
		}
            public uint256 BlindMessage(byte[] message, PubKey rpubKey, PubKey signerPubKey)
            {
                var msg = new uint256(Hashes.SHA256(message));

                return(BlindMessage(msg, rpubKey, signerPubKey));
            }
Esempio n. 45
0
		private void AssertHasAsset(Transaction tx, ColoredTransaction colored, ColoredEntry entry, AssetId assetId, int quantity, PubKey destination)
		{
			var txout = tx.Outputs[entry.Index];
			Assert.True(entry.Asset.Id == assetId);
			Assert.True(entry.Asset.Quantity == quantity);
			if(destination != null)
				Assert.True(txout.ScriptPubKey == destination.ScriptPubKey);
		}
Esempio n. 46
0
 public bool CheckSignature(PubKey key)
 {
     return key.Verify(Hashes.Hash256(payload.GetString()), signature.GetString());
 }
Esempio n. 47
0
		private Key AssertKeys(string key, string pub)
		{
			if(key == null)
				return null;
			Key k = new Key(TestUtils.ParseHex(key));
			if(pub != null)
			{
				PubKey p = new PubKey(TestUtils.ParseHex(pub));
				AssertEx.Equal(k.PubKey.ToBytes(), p.ToBytes());
			}
			return k;
		}
Esempio n. 48
0
        public Transaction CreateColdStakingWithdrawalTransaction(Wallet.Types.Wallet wallet, string password, HdAddress spendingAddress, PubKey destinationPubKey, Script changeScript, Money amount, Money fee)
        {
            TransactionOutputData spendingTransaction = wallet.walletStore.GetForAddress(spendingAddress.Address).ElementAt(0);
            var coin = new Coin(spendingTransaction.Id, (uint)spendingTransaction.Index, spendingTransaction.Amount, spendingTransaction.ScriptPubKey);

            Key privateKey = Key.Parse(wallet.EncryptedSeed, password, wallet.Network);

            Script script = destinationPubKey.ScriptPubKey;

            var builder = new TransactionBuilder(wallet.Network);

            builder.Extensions.Add(new ColdStakingBuilderExtension(false));
            Transaction tx = builder
                             .AddCoins(new List <Coin> {
                coin
            })
                             .AddKeys(new ExtKey(privateKey, wallet.ChainCode).Derive(new KeyPath(spendingAddress.HdPath)).GetWif(wallet.Network))
                             .Send(script, amount)
                             .SetChange(changeScript)
                             .SendFees(fee)
                             .BuildTransaction(true);

            if (!builder.Verify(tx))
            {
                throw new WalletException("Could not build transaction, please make sure you entered the correct data.");
            }

            return(tx);
        }