• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# NBitcoin.Transaction类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中NBitcoin.Transaction的典型用法代码示例。如果您正苦于以下问题:C# Transaction类的具体用法?C# Transaction怎么用?C# Transaction使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Transaction类属于NBitcoin命名空间,在下文中一共展示了Transaction类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: GetPayments

        public static StealthPayment[] GetPayments(Transaction transaction, PubKey[] spendKeys, BitField bitField, Key scan)
        {
            List<StealthPayment> result = new List<StealthPayment>();
            for(int i = 0 ; i < transaction.Outputs.Count ; i++)
            {
                var metadata = StealthMetadata.TryParse(transaction.Outputs[i].ScriptPubKey);
                if(metadata != null && bitField.Match(metadata.BitField))
                {
                    var payment = new StealthPayment(transaction.Outputs[i + 1].ScriptPubKey, metadata);
                    if(scan != null && spendKeys != null)
                    {
                        if(payment.StealthKeys.Length != spendKeys.Length)
                            continue;

                        var expectedStealth = spendKeys.Select(s => s.UncoverReceiver(scan, metadata.EphemKey)).ToList();
                        foreach(var stealth in payment.StealthKeys)
                        {
                            var match = expectedStealth.FirstOrDefault(expected => expected.ID == stealth.ID);
                            if(match != null)
                                expectedStealth.Remove(match);
                        }
                        if(expectedStealth.Count != 0)
                            continue;
                    }
                    result.Add(payment);
                }
            }
            return result.ToArray();
        }
开发者ID:nikropht,项目名称:NBitcoin,代码行数:29,代码来源:StealthPayment.cs


示例2: Check

		public bool Check(PubKey pubKey, Script scriptPubKey, Transaction tx, uint nIndex, ScriptVerify verify = ScriptVerify.Standard)
		{
			return new ScriptEvaluationContext()
			{
				ScriptVerify = verify,
				SigHash = SigHash
			}.CheckSig(this, pubKey, scriptPubKey, tx, nIndex);
		}
开发者ID:hu53yin,项目名称:NBitcoin,代码行数:8,代码来源:TransactionSignature.cs


示例3: AddFromTransaction

 public void AddFromTransaction(Transaction transaction)
 {
     var hash = transaction.GetHash();
     for(int i = 0 ; i < transaction.Outputs.Count; i++)
     {
         AddTxOut(new OutPoint(hash, i), transaction.Outputs[i]);
     }
 }
开发者ID:royosherove,项目名称:NBitcoin,代码行数:8,代码来源:TxOutRepository.cs


示例4: Coins

 public Coins(Transaction tx, Func<TxOut, bool> belongsToCoins, int height)
 {
     if(belongsToCoins == null)
         belongsToCoins = o => !o.ScriptPubKey.IsUnspendable;
     fCoinBase = tx.IsCoinBase;
     vout = tx.Outputs.ToList();
     nVersion = tx.Version;
     nHeight = (uint)height;
     ClearUnused(belongsToCoins);
     UpdateValue();
 }
开发者ID:royosherove,项目名称:NBitcoin,代码行数:11,代码来源:Coins.cs


示例5: PutAsync

		public Task PutAsync(uint256 txId, Transaction tx)
		{
			using(@lock.LockWrite())
			{
				if(!_Transactions.ContainsKey(txId))
					_Transactions.AddOrReplace(txId, tx);
				else
					_Transactions[txId] = tx;
			}
			return _Inner.PutAsync(txId, tx);
		}
开发者ID:woutersmit,项目名称:NBitcoin,代码行数:11,代码来源:CachedTransactionRepository.cs


示例6: Put

		public static void Put(this ITransactionRepository repo, uint256 txId, Transaction tx)
		{
			try
			{
				repo.PutAsync(txId, tx).Wait();
			}
			catch(AggregateException aex)
			{
				ExceptionDispatchInfo.Capture(aex.InnerException).Throw();
			}
		}
开发者ID:crowar,项目名称:NBitcoin,代码行数:11,代码来源:ITransactionRepository.cs


示例7: SendTransaction

 public static void SendTransaction(Transaction tx)
 {
     AddressManager nodeParams = new AddressManager();
     IPEndPoint endPoint = TranslateHostNameToIP("http://btcnode.placefullcloud.com", 8333);
     nodeParams.Add(new NetworkAddress(endPoint), endPoint.Address);
     using (var node = Node.Connect(Network, nodeParams))
     {
         node.VersionHandshake();
         node.SendMessage(new InvPayload(InventoryType.MSG_TX, tx.GetHash()));
         node.SendMessage(new TxPayload(tx));
     }
 }
开发者ID:monkeysSuck,项目名称:BitcoinPlayground,代码行数:12,代码来源:Program.cs


示例8: OnBroadcastTransaction

		internal void OnBroadcastTransaction(Transaction transaction)
		{
			var hash = transaction.GetHash();
			var nodes = Nodes
						.Select(n => n.Key.Behaviors.Find<BroadcastHubBehavior>())
						.Where(n => n != null)
						.ToArray();
			foreach(var node in nodes)
			{
				node.BroadcastTransactionCore(transaction);
			}
		}
开发者ID:n1rvana,项目名称:NBitcoin,代码行数:12,代码来源:BroadcastTransactionBehavior.cs


示例9: CreateTransactionFeeCoin

 static Coin CreateTransactionFeeCoin(PubKey destination, NoSqlTransactionRepository txRepo)
 {
     var bitcoinProviderTransaction = new Transaction()
     {
         Outputs =
         {
             new TxOut("0.0001" , destination)
         }
     };
     txRepo.Put(bitcoinProviderTransaction.GetHash(), bitcoinProviderTransaction);
     return new Coin(new OutPoint(bitcoinProviderTransaction, 0),
         bitcoinProviderTransaction.Outputs[0]);
 }
开发者ID:LykkeCity,项目名称:Prototypes,代码行数:13,代码来源:Program.cs


示例10: AreInputsStandard

        //
        // Check transaction inputs, and make sure any
        // pay-to-script-hash transactions are evaluating IsStandard scripts
        //
        // Why bother? To avoid denial-of-service attacks; an attacker
        // can submit a standard HASH... OP_EQUAL transaction,
        // which will get accepted into blocks. The redemption
        // script can be anything; an attacker could use a very
        // expensive-to-check-upon-redemption script like:
        //   DUP CHECKSIG DROP ... repeated 100 times... OP_1
        //
        public static bool AreInputsStandard(Transaction tx, CoinsView coinsView)
        {
            if(tx.IsCoinBase)
                return true; // Coinbases don't use vin normally

            for(int i = 0 ; i < tx.Inputs.Count ; i++)
            {
                TxOut prev = coinsView.GetOutputFor(tx.Inputs[i]);
                if(prev == null)
                    return false;
                if(!IsStandardScriptSig(tx.Inputs[i].ScriptSig, prev.ScriptPubKey))
                    return false;
            }

            return true;
        }
开发者ID:nikropht,项目名称:NBitcoin,代码行数:27,代码来源:StandardScripts.cs


示例11: GetTrustedInput

 public TrustedInput GetTrustedInput(Transaction transaction, int outputIndex)
 {
     using(Transport.Lock())
     {
         if(outputIndex >= transaction.Outputs.Count)
             throw new ArgumentOutOfRangeException("outputIndex is bigger than the number of outputs in the transaction", "outputIndex");
         MemoryStream data = new MemoryStream();
         // Header
         BufferUtils.WriteUint32BE(data, outputIndex);
         BufferUtils.WriteBuffer(data, transaction.Version);
         VarintUtils.write(data, transaction.Inputs.Count);
         ExchangeApdu(LedgerWalletConstants.LedgerWallet_CLA, LedgerWalletConstants.LedgerWallet_INS_GET_TRUSTED_INPUT, (byte)0x00, (byte)0x00, data.ToArray(), OK);
         // Each input
         foreach(var input in transaction.Inputs)
         {
             data = new MemoryStream();
             BufferUtils.WriteBuffer(data, input.PrevOut);
             VarintUtils.write(data, input.ScriptSig.Length);
             ExchangeApdu(LedgerWalletConstants.LedgerWallet_CLA, LedgerWalletConstants.LedgerWallet_INS_GET_TRUSTED_INPUT, (byte)0x80, (byte)0x00, data.ToArray(), OK);
             data = new MemoryStream();
             BufferUtils.WriteBuffer(data, input.ScriptSig.ToBytes());
             ExchangeApduSplit2(LedgerWalletConstants.LedgerWallet_CLA, LedgerWalletConstants.LedgerWallet_INS_GET_TRUSTED_INPUT, (byte)0x80, (byte)0x00, data.ToArray(), Utils.ToBytes(input.Sequence, true), OK);
         }
         // Number of outputs
         data = new MemoryStream();
         VarintUtils.write(data, transaction.Outputs.Count);
         ExchangeApdu(LedgerWalletConstants.LedgerWallet_CLA, LedgerWalletConstants.LedgerWallet_INS_GET_TRUSTED_INPUT, (byte)0x80, (byte)0x00, data.ToArray(), OK);
         // Each output
         foreach(var output in transaction.Outputs)
         {
             data = new MemoryStream();
             BufferUtils.WriteBuffer(data, Utils.ToBytes((ulong)output.Value.Satoshi, true));
             VarintUtils.write(data, output.ScriptPubKey.Length);
             ExchangeApdu(LedgerWalletConstants.LedgerWallet_CLA, LedgerWalletConstants.LedgerWallet_INS_GET_TRUSTED_INPUT, (byte)0x80, (byte)0x00, data.ToArray(), OK);
             data = new MemoryStream();
             BufferUtils.WriteBuffer(data, output.ScriptPubKey.ToBytes());
             ExchangeApduSplit(LedgerWalletConstants.LedgerWallet_CLA, LedgerWalletConstants.LedgerWallet_INS_GET_TRUSTED_INPUT, (byte)0x80, (byte)0x00, data.ToArray(), OK);
         }
         // Locktime
         byte[] response = ExchangeApdu(LedgerWalletConstants.LedgerWallet_CLA, LedgerWalletConstants.LedgerWallet_INS_GET_TRUSTED_INPUT, (byte)0x80, (byte)0x00, transaction.LockTime.ToBytes(), OK);
         return new TrustedInput(response);
     }
 }
开发者ID:LedgerHQ,项目名称:ledger-dotnet-api,代码行数:43,代码来源:LedgerClient.cs


示例12: PutAsync

		public Task PutAsync(uint256 txId, Transaction tx)
		{
			if(WriteThrough)
			{
				using(@lock.LockWrite())
				{

					if(!_Transactions.ContainsKey(txId))
					{

						_Transactions.AddOrReplace(txId, tx);
						EvictIfNecessary(txId);
					}
					else
						_Transactions[txId] = tx;
				}
			}
			return _Inner.PutAsync(txId, tx);
		}
开发者ID:crowar,项目名称:NBitcoin,代码行数:19,代码来源:CachedTransactionRepository.cs


示例13: Submit

        public static void Submit(Transaction tx)
        {
            //SOME TEST NET NODES
            //54.149.133.4:18333
            //52.69.206.155:18333
            //93.114.160.222:18333
            string url = "93.114.160.222:18333";
            using(var node = NBitcoin.Protocol.Node.Connect(NBitcoin.Network.TestNet, url))
            {
                node.VersionHandshake();
                //System.Threading.Thread.Sleep(1000);

                NBitcoin.Transaction[] transactions = new Transaction[1];
                transactions[0] = tx;

                node.SendMessage(new NBitcoin.Protocol.InvPayload(transactions));
                node.SendMessage(new NBitcoin.Protocol.TxPayload(tx));
            }
        }
开发者ID:NicolasDorier,项目名称:colourcoinpoc,代码行数:19,代码来源:Program.cs


示例14: GetAsync

		public async Task<Transaction> GetAsync(uint256 txId)
		{
			while(true)
			{
				using(HttpClient client = new HttpClient())
				{
					var response = await client.GetAsync(BlockrAddress + "tx/raw/" + txId).ConfigureAwait(false);
					if(response.StatusCode == HttpStatusCode.NotFound)
						return null;
					var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
					var json = JObject.Parse(result);
					var status = json["status"];
					var code = json["code"];
					if(status != null && status.ToString() == "error")
					{
						throw new BlockrException(json);
					}
					var tx = new Transaction(json["data"]["tx"]["hex"].ToString());
					return tx;
				}
			}
		}
开发者ID:xcrash,项目名称:NBitcoin,代码行数:22,代码来源:BlockrTransactionRepository.cs


示例15: GetHexSignedTransaction

        public static string GetHexSignedTransaction(TransactionToSign txToSign)
        {
            var walletPrivateKey = ConfigurationManager.AppSettings[METACO_ENV_WALLET_PRIVATE_KEY_HEX_NAME];

            var key = new Key(Encoders.Hex.DecodeData(walletPrivateKey));

            var scriptPubKey = PayToPubkeyHashTemplate.Instance.GenerateScriptPubKey(key.PubKey);
            var tx = new Transaction(Encoders.Hex.DecodeData(txToSign.Raw));

            foreach(var inputsToSign in txToSign.InputsToSign)
            {
                var sigHash = tx.GetSignatureHash(scriptPubKey, inputsToSign.Index);
                var sig = key.Sign(sigHash);

                var txSign = new TransactionSignature(sig, SigHash.All);
                var inputScript = PayToPubkeyHashTemplate.Instance.GenerateScriptSig(txSign, key.PubKey);

                tx.Inputs[inputsToSign.Index].ScriptSig = inputScript;
                Assert.True(Script.VerifyScript(scriptPubKey, tx, inputsToSign.Index));
            }

            return tx.ToHex();
        }
开发者ID:MetacoSA,项目名称:metaco-net-client,代码行数:23,代码来源:MetacoClientTestBase.cs


示例16: IsStandardTransaction

		public static bool IsStandardTransaction(Transaction tx)
		{
			if(tx.Version > Transaction.CURRENT_VERSION || tx.Version < 1)
			{
				return false;
			}

			//// Treat non-final transactions as non-standard to prevent a specific type
			//// of double-spend attack, as well as DoS attacks. (if the transaction
			//// can't be mined, the attacker isn't expending resources broadcasting it)
			//// Basically we don't want to propagate transactions that can't included in
			//// the next block.
			////
			//// However, IsFinalTx() is confusing... Without arguments, it uses
			//// chainActive.Height() to evaluate nLockTime; when a block is accepted, chainActive.Height()
			//// is set to the value of nHeight in the block. However, when IsFinalTx()
			//// is called within CBlock::AcceptBlock(), the height of the block *being*
			//// evaluated is what is used. Thus if we want to know if a transaction can
			//// be part of the *next* block, we need to call IsFinalTx() with one more
			//// than chainActive.Height().
			////
			//// Timestamps on the other hand don't get any special treatment, because we
			//// can't know what timestamp the next block will have, and there aren't
			//// timestamp applications where it matters.
			//if (!IsFinalTx(tx, chainActive.Height() + 1)) {
			//	reason = "non-final";
			//	return false;
			//}

			// Extremely large transactions with lots of inputs can cost the network
			// almost as much to process as they cost the sender in fees, because
			// computing signature hashes is O(ninputs*txsize). Limiting transactions
			// to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks.
			int sz = tx.GetSerializedSize();
			if(sz >= Transaction.MAX_STANDARD_TX_SIZE)
				return false;


			foreach(TxIn txin in tx.Inputs)
			{
				// Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
				// keys. (remember the 520 byte limit on redeemScript size) That works
				// out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
				// bytes of scriptSig, which we round off to 1650 bytes for some minor
				// future-proofing. That's also enough to spend a 20-of-20
				// CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
				// considered standard)
				if (txin.ScriptSig.Length > 1650)
				{
					return false;
				}
				if(!txin.ScriptSig.IsPushOnly)
				{
					return false;
				}
				if(!txin.ScriptSig.HasCanonicalPushes)
				{
					return false;
				}
			}

			uint nDataOut = 0;
			foreach(TxOut txout in tx.Outputs)
			{
				var template = StandardScripts.GetTemplateFromScriptPubKey(txout.ScriptPubKey);
				if(template == null)
					return false;

				if(template.Type == TxOutType.TX_NULL_DATA)
					nDataOut++;
				else if(txout.IsDust)
					return false;
			}
			// only one OP_RETURN txout is permitted
			if(nDataOut > 1)
			{
				return false;
			}

			return true;
		}
开发者ID:xcrash,项目名称:NBitcoin,代码行数:81,代码来源:StandardScripts.cs


示例17: SignatureHash

		//https://en.bitcoin.it/wiki/OP_CHECKSIG
		public uint256 SignatureHash(Transaction txTo, int nIn, SigHash nHashType)
		{
			if(nIn >= txTo.Inputs.Count)
			{
				Utils.log("ERROR: SignatureHash() : nIn=" + nIn + " out of range\n");
				return uint256.One;
			}

			// Check for invalid use of SIGHASH_SINGLE
			if(nHashType == SigHash.Single)
			{
				if(nIn >= txTo.Outputs.Count)
				{
					Utils.log("ERROR: SignatureHash() : nOut=" + nIn + " out of range\n");
					return uint256.One;
				}
			}

			var scriptCopy = new Script(_Script);
			scriptCopy.FindAndDelete(OpcodeType.OP_CODESEPARATOR);

			var txCopy = new Transaction(txTo.ToBytes());

			//Set all TxIn script to empty string
			foreach(var txin in txCopy.Inputs)
			{
				txin.ScriptSig = new Script();
			}
			//Copy subscript into the txin script you are checking
			txCopy.Inputs[nIn].ScriptSig = scriptCopy;

			var hashType = nHashType & (SigHash)31;
			if(hashType == SigHash.None)
			{
				//The output of txCopy is set to a vector of zero size.
				txCopy.Outputs.Clear();

				//All other inputs aside from the current input in txCopy have their nSequence index set to zero
				foreach(var input in txCopy.Inputs.Where((x, i) => i != nIn))
					input.Sequence = 0;
			}
			else if(hashType == SigHash.Single)
			{
				//The output of txCopy is resized to the size of the current input index+1.
				txCopy.Outputs.RemoveRange(nIn + 1, txCopy.Outputs.Count - (nIn + 1));
				//All other txCopy outputs aside from the output that is the same as the current input index are set to a blank script and a value of (long) -1.
				for(var i = 0 ; i < txCopy.Outputs.Count ; i++)
				{
					if(i == nIn)
						continue;
					txCopy.Outputs[i] = new TxOut();
				}
				//All other txCopy inputs aside from the current input are set to have an nSequence index of zero.
				foreach(var input in txCopy.Inputs.Where((x, i) => i != nIn))
					input.Sequence = 0;
			}


			if((nHashType & SigHash.AnyoneCanPay) != 0)
			{
				//The txCopy input vector is resized to a length of one.
				var script = txCopy.Inputs[nIn];
				txCopy.Inputs.Clear();
				txCopy.Inputs.Add(script);
				//The subScript (lead in by its length as a var-integer encoded!) is set as the first and only member of this vector.
				txCopy.Inputs[0].ScriptSig = scriptCopy;
			}


			//Serialize TxCopy, append 4 byte hashtypecode
			var ms = new MemoryStream();
			var bitcoinStream = new BitcoinStream(ms, true);
			txCopy.ReadWrite(bitcoinStream);
			bitcoinStream.ReadWrite((uint)nHashType);

			var hashed = ms.ToArray();
			return Hashes.Hash256(hashed);
		}
开发者ID:woutersmit,项目名称:NBitcoin,代码行数:79,代码来源:Script.cs


示例18: AreOutputsStandard

		public static bool AreOutputsStandard(Transaction tx)
		{
			return tx.Outputs.All(vout => IsStandardScriptPubKey(vout.ScriptPubKey));
		}
开发者ID:xcrash,项目名称:NBitcoin,代码行数:4,代码来源:StandardScripts.cs


示例19: VerifyScript

		public static bool VerifyScript(Script scriptPubKey, Transaction tx, int i, ScriptVerify scriptVerify = ScriptVerify.Standard, SigHash sigHash = SigHash.Undefined)
		{
			ScriptError unused;
			var scriptSig = tx.Inputs[i].ScriptSig;
			return VerifyScript(scriptSig, scriptPubKey, tx, i, scriptVerify, sigHash, out unused);
		}
开发者ID:woutersmit,项目名称:NBitcoin,代码行数:6,代码来源:Script.cs


示例20: GetLegacySigOpCount

		private int GetLegacySigOpCount(Transaction tx)
		{
			uint nSigOps = 0;
			foreach(var txin in tx.Inputs)
			{
				nSigOps += txin.ScriptSig.GetSigOpCount(false);
			}
			foreach(var txout in tx.Outputs)
			{
				nSigOps += txout.ScriptPubKey.GetSigOpCount(false);
			}
			return (int)nSigOps;
		}
开发者ID:xcrash,项目名称:NBitcoin,代码行数:13,代码来源:ValidationState.cs



注:本文中的NBitcoin.Transaction类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# NBitcoin.uint256类代码示例发布时间:2022-05-26
下一篇:
C# NBitcoin.Op类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap