コード例 #1
0
ファイル: BaseTransactionTests.cs プロジェクト: EYHN/Anything
    public void SideEffectRollbackTest()
    {
        var a = 0;

        using var transaction = new BaseTransaction(ITransaction.TransactionMode.Create);

        transaction.RunSideEffect(
            () =>
        {
            Assert.AreEqual(0, a);
            a++;
        },
            () =>
        {
            Assert.AreEqual(1, a);
            a--;
        });

        transaction.RunSideEffect(
            () =>
        {
            Assert.AreEqual(1, a);
            a++;
        },
            () =>
        {
            Assert.AreEqual(2, a);
            a--;
        });

        transaction.Rollback();

        Assert.AreEqual(0, a);
    }
コード例 #2
0
        private static async Task Output(BaseTransaction tx, bool copyToClipboard, string party)
        {
            tx.TransactionTime = DateTime.Now;
            var jsonString       = JsonConvert.SerializeObject(tx, new TransactionSerializerSettings());
            var byteArray        = Encoding.UTF8.GetBytes(jsonString);
            var transactionToken = new TransactionToken(byteArray);

            var currentDirectory = Directory.GetCurrentDirectory();

            if (!currentDirectory.Contains("netcoreapp"))
            {
                throw new Exception("Please execute the request creator within netcoreapp2.0 folder.");
            }

            var basePath    = Path.Combine(currentDirectory, "..", "..", "..", "..", "..", "certificates");
            var certificate = new X509Certificate2(Path.Combine(basePath, $"{party}.p12"), "thinktecture");

            transactionToken.Sign(certificate);

            var tokenString = transactionToken.ToTokenString();

            Console.WriteLine("Sending the following tokenstring...");
            Console.WriteLine(tokenString);

            if (copyToClipboard)
            {
                CopyToClipboard(tokenString);
            }

            Console.WriteLine(await MakeRequest(tokenString));
        }
コード例 #3
0
ファイル: ShopStore.cs プロジェクト: gkmk/Dungeons2D
    IEnumerator InitiateTransaction(BaseTransaction transaction)
    {
        // Gets the handle of the transaction.
        var deferredResult = TransactionManager.BeginTransaction(transaction);

        try
        {
            // Waits for the process to finish
            while (!deferredResult.isDone)
            {
                yield return(null);
            }

            // The process failed
            if (!deferredResult.isFulfilled)
            {
                Debug.LogException(deferredResult.error);
            }

            // The process succeeded
            else
            {
                var result = deferredResult.result;

                DisplayResult(result);
            }
        }
        finally
        {
            // A process handle can be released.
            deferredResult.Release();
        }
    }
コード例 #4
0
        public BaseTransaction GetTransaction(IEnumerable <byte> txId)
        {
            if (txId == null)
            {
                throw new ArgumentNullException(nameof(txId));
            }

            var callback = new Func <BaseTransaction>(() =>
            {
                string result;
                if (!_db.TryGet(string.Format(TRANSACTION_ELT, txId.ToHexString()), ReadOptions.Default, out result))
                {
                    return(null);
                }

                var payload = result.FromHexString();
                var kvp     = BaseTransaction.Deserialize(payload);
                if (kvp.Equals(default(KeyValuePair <BaseTransaction, int>)) && kvp.Key != null)
                {
                    return(null);
                }

                return(kvp.Key);
            });

            var res = callback();

            return(res);
        }
コード例 #5
0
        private JObject SendRawTransaction(IEnumerable <string> parameters, JObject response, string id)
        {
            var blockChain = _blockChainStore.GetBlockChain();

            if (parameters == null || !parameters.Any())
            {
                return(CreateErrorResponse(id, (int)RpcErrorCodes.RPC_INVALID_PARAMS, "The transaction is missing"));
            }

            var txPayload     = parameters.First().FromHexString();
            var allowHighFees = false;

            if (parameters.Count() >= 2)
            {
                if (bool.TryParse(parameters.ElementAt(1), out allowHighFees))
                {
                }
            }

            var kvp = BaseTransaction.Deserialize(txPayload);

            try
            {
                var tx = kvp.Key;
                _transactionValidator.Check(tx);
                MemoryPool.Instance().AddTransaction(tx, blockChain.GetCurrentBlockHeight());
                P2PConnectorEventStore.Instance().Broadcast(tx);
                response["result"] = tx.GetTxId().ToHexString();
                return(response);
            }
            catch (ValidationException ex)
            {
                return(CreateErrorResponse(id, (int)RpcErrorCodes.RPC_VERIFY_ERROR, ex.Message));
            }
        }
コード例 #6
0
        public static Block Deserialize(IEnumerable <byte> payload)
        {
            if (payload == null)
            {
                throw new ArgumentNullException(nameof(payload));
            }

            var header         = DeserializeBlockHeader(payload);
            int currentIndex   = 80;
            var transactionLst = new List <BaseTransaction>();
            var kvp            = CompactSize.Deserialize(payload.Skip(80).ToArray());

            currentIndex += kvp.Value;
            if (kvp.Key.Size > 0)
            {
                for (var i = 0; i < (int)kvp.Key.Size; i++)
                {
                    var skvp = BaseTransaction.Deserialize(payload.Skip(currentIndex));
                    transactionLst.Add(skvp.Key);
                    currentIndex += skvp.Value;
                }
            }

            var result = new Block(header.PreviousBlockHeader, header.NBits, header.Nonce);

            result.BlockHeader  = header;
            result.Transactions = transactionLst;
            return(result);
        }
コード例 #7
0
 private void OnTransactionInitiated(BaseTransaction transaction)
 {
     if (m_WaitAnimation == null && waitAnimationPrefab != null)
     {
         m_WaitAnimation = Instantiate(waitAnimationPrefab).transform;
     }
 }
コード例 #8
0
        /// <summary>
        /// Dequeues the next unlocked message information with the highest priority from the queue.
        /// </summary>
        /// <param name="transaction">The current <see cref="BaseTransaction" /> (or <c>null</c>).</param>
        /// <returns>The message information or <c>null</c> if no suitable messages can be returned.</returns>
        public QueuedMsgInfo Dequeue(BaseTransaction transaction)
        {
            Guid lockID = transaction != null ? transaction.ID : Guid.Empty;

            for (int i = queuesByPriority.Length - 1; i >= 0; i--)
            {
                var           queue = queuesByPriority[i];
                QueuedMsgInfo msgInfo;

                for (int j = 0; j < queue.Count; j++)
                {
                    msgInfo = queue[j];
                    if (msgInfo.LockID == Guid.Empty || msgInfo.LockID == lockID)
                    {
                        msgInfo.LockID = lockID;
                        queue.RemoveAt(j);
                        count--;

                        messages.Remove(msgInfo.ID);
                        return(msgInfo);
                    }
                }
            }

            return(null);
        }
コード例 #9
0
        private Transaction GenerateTransaction(bool extended = false)
        {
            var baseTransaction = new BaseTransaction
            {
                ExecutingEntityCode        = GenerateString(),
                TransactionReferenceNumber = GenerateString()
            };

            if (!extended)
            {
                return new Transaction {
                           BaseTransaction = baseTransaction
                }
            }
            ;

            var extendedTransaction = new ExtendedTransaction
            {
                BaseTransaction = baseTransaction,
                Comments        = GenerateString(),
                Extra           = GenerateString()
            };

            return(new Transaction {
                ExtendedTransaction = extendedTransaction
            });
        }
コード例 #10
0
        /// <summary>
        /// Clears all locks held by a transaction.
        /// </summary>
        /// <param name="transaction">The completed <see cref="BaseTransaction" />.</param>
        public void Unlock(BaseTransaction transaction)
        {
            if (transaction == null)
            {
                throw new ArgumentNullException("transaction");
            }

            Guid lockID = transaction.ID;

            // $todo(jeff.lill):
            //
            // This will be slow if there are a lot of queued messages
            // since I'm going to walk the entire queue.  A faster but more
            // complex approach would be to maintain a separate table of
            // locked messages, indexed by transaction ID.
            //
            // I don't have the time to mess with this right now but I
            // will want to come back to this at some point.

            for (int i = 0; i < queuesByPriority.Length; i++)
            {
                var queue = queuesByPriority[i];

                foreach (QueuedMsgInfo msgInfo in queue)
                {
                    if (lockID == msgInfo.LockID)
                    {
                        msgInfo.LockID = Guid.Empty;
                    }
                }
            }
        }
コード例 #11
0
        public async Task <BaseTransaction> GetRawTransaction(IEnumerable <byte> txId)
        {
            if (txId == null)
            {
                throw new ArgumentOutOfRangeException(nameof(txId));
            }

            var httpClient = _httpClientFactory.BuildClient();
            var jParams    = new JArray();

            jParams.Add(txId.ToHexString());
            var jObj = new JObject();

            jObj.Add("id", Guid.NewGuid().ToString());
            jObj.Add("method", Constants.RpcOperations.GetRawTransaction);
            jObj.Add("params", jParams);
            var content = new StringContent(jObj.ToString(), System.Text.Encoding.UTF8, ContentType);
            var request = new HttpRequestMessage
            {
                Method     = HttpMethod.Post,
                Content    = content,
                RequestUri = GetUri()
            };

            var response = await httpClient.SendAsync(request).ConfigureAwait(false);

            var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            string errorCode = null;
            var    jsonObj   = JObject.Parse(json);

            if (TryGetError(jsonObj, out errorCode))
            {
                throw new RpcException(errorCode);
            }

            var r = jsonObj.Value <string>("result");

            if (string.IsNullOrWhiteSpace(r))
            {
                return(null);
            }

            if (string.IsNullOrWhiteSpace(r))
            {
                return(null);
            }

            var             payload     = r.FromHexString();
            BaseTransaction transaction = null;

            try
            {
                transaction = BaseTransaction.Deserialize(payload).Key;
            }
            catch (Exception) { }
            return(transaction);
        }
コード例 #12
0
        public long GetReward(BaseTransaction transaction)
        {
            if (transaction == null)
            {
                throw new ArgumentNullException(nameof(transaction));
            }

            return((long)Math.Ceiling(((transaction.Serialize().Count() / (double)1000) * Constants.DEFAULT_MIN_TX_FEE)));
        }
コード例 #13
0
ファイル: BaseTransactionTests.cs プロジェクト: EYHN/Anything
    public void QueryTest()
    {
        var a = 0;

        using var transaction = new BaseTransaction(ITransaction.TransactionMode.Query);

        Assert.Catch <InvalidOperationException>(() => transaction.RunSideEffect(() => ++ a, () => a--));
        Assert.Catch <InvalidOperationException>(() => transaction.RunSideEffect(Assert.Fail, Assert.Fail));
    }
コード例 #14
0
        public void Remove(BaseTransaction transaction)
        {
            if (transaction == null)
            {
                throw new ArgumentNullException(nameof(transaction));
            }

            Remove(new[] { transaction.GetTxId() });
        }
コード例 #15
0
        public static TransactionMessage Deserialize(IEnumerable <byte> payload, Networks network, TransactionTypes transactionType)
        {
            if (payload == null)
            {
                throw new ArgumentNullException(nameof(payload));
            }

            return(new TransactionMessage(BaseTransaction.Deserialize(payload).Key, network));
        }
コード例 #16
0
        /// <summary>
        /// Adds the message information to the end other queued messages with the same priority.
        /// </summary>
        /// <param name="transaction">The current <see cref="BaseTransaction" /> (or <c>null</c>).</param>
        /// <param name="msgInfo">The message information.</param>
        public void Enqueue(BaseTransaction transaction, QueuedMsgInfo msgInfo)
        {
            var queue  = queuesByPriority[(int)msgInfo.Priority];
            var lockID = transaction != null ? transaction.ID : Guid.Empty;

            msgInfo.LockID = lockID;
            queue.Enqueue(msgInfo);
            messages.Add(msgInfo.ID, msgInfo);
            count++;
        }
コード例 #17
0
ファイル: BaseTransactionTests.cs プロジェクト: EYHN/Anything
    public void CompletedTest()
    {
        using var transaction = new BaseTransaction(ITransaction.TransactionMode.Create);

        Assert.AreEqual(false, transaction.Completed);

        transaction.Commit();

        Assert.AreEqual(true, transaction.Completed);

        Assert.Catch <InvalidOperationException>(() => transaction.Commit());
    }
コード例 #18
0
        public void Broadcast(BaseTransaction transaction)
        {
            if (transaction == null)
            {
                throw new ArgumentNullException(nameof(transaction));
            }

            if (NewTransactionEvt != null)
            {
                NewTransactionEvt(this, new TransactionEventArgs(transaction));
            }
        }
コード例 #19
0
        private Task <T> Handle <T>(ITransactionHandler handler, BaseTransaction payload, Func <ITransactionHandler, BaseTransaction, Task <T> > handlerAction)
            where T : class, new()
        {
            if (handler == null)
            {
                _logger.LogWarning($"No handler found");
                return(Task.FromResult(new T()));
            }

            _logger.LogInformation($"Handling {payload.GetType()} with handler {handler.GetType()}");
            return(handlerAction(handler, payload));
        }
        private TransactionToken CreateSignedToken(BaseTransaction tx)
        {
            tx.TransactionTime = DateTime.Now;
            var jsonString       = JsonConvert.SerializeObject(tx, new TransactionSerializerSettings());
            var byteArray        = Encoding.UTF8.GetBytes(jsonString);
            var transactionToken = new TransactionToken(byteArray);

            var basePath    = Path.Combine(_environment.WebRootPath);
            var certificate = new X509Certificate2(Path.Combine(basePath, $"{GetParty()}.p12"), "thinktecture");

            transactionToken.Sign(certificate);

            return(transactionToken);
        }
コード例 #21
0
        private void Init()
        {
            var rpcClient = new RpcClient(_network);

            rpcClient.GetRawTransaction(_txId).ContinueWith((r) =>
            {
                try
                {
                    BaseTransaction transaction = r.Result;
                    if (transaction == null)
                    {
                        return;
                    }

                    var monetaryTransaction = transaction as BcBaseTransaction;
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        _viewModel.TxId    = transaction.GetTxId().ToHexString();
                        _viewModel.Version = transaction.Version;
                        _viewModel.Size    = transaction.Serialize().Count();
                        var nonceCoinBase  = transaction as NoneCoinbaseTransaction;
                        if (nonceCoinBase != null && nonceCoinBase.TransactionIn != null && nonceCoinBase.TransactionIn.Any())
                        {
                            var firstTransactionIn = nonceCoinBase.TransactionIn.First() as TransactionInNoneCoinbase;
                            if (firstTransactionIn != null && firstTransactionIn.Outpoint != null)
                            {
                                _viewModel.PreviousTxId = firstTransactionIn.Outpoint.Hash.ToHexString();
                            }
                        }

                        if (monetaryTransaction != null && monetaryTransaction.TransactionOut != null && monetaryTransaction.TransactionOut.Any())
                        {
                            foreach (var txOut in monetaryTransaction.TransactionOut)
                            {
                                _viewModel.TxOuts.Add(new TxOutViewModel
                                {
                                    Index  = monetaryTransaction.TransactionOut.IndexOf(txOut),
                                    Value  = txOut.Value,
                                    Script = txOut.Script.Serialize().ToHexString()
                                });
                            }
                        }
                    });
                }
                catch (AggregateException ex)
                {
                }
            });
        }
コード例 #22
0
        public void ChargeAmount(UGUI agentID, BaseTransaction transactionData, int amount, Action processOperation)
        {
            IActiveTransaction transaction = BeginChargeTransaction(agentID, transactionData, amount);

            try
            {
                processOperation();
            }
            catch (Exception e)
            {
                transaction.Rollback(e);
                throw;
            }
            transaction.Commit();
        }
コード例 #23
0
        /** <summary> Process a transaction for paying a user by a group</summary>
         * <exception cref="InsufficientFundsException">this exception is thrown when not enough funds are available</exception>
         * <exception cref="NotSupportedException">this exception is thrown when the economy service does not support group accounts</exception>
         */
        public void TransferMoney(UGI sourceID, UGUI destinationID, BaseTransaction transactionData, int amount, Action processOperation)
        {
            IActiveTransaction transaction = BeginTransferTransaction(sourceID, destinationID, transactionData, amount);

            try
            {
                processOperation();
            }
            catch (Exception e)
            {
                transaction.Rollback(e);
                throw;
            }
            transaction.Commit();
        }
コード例 #24
0
        public void Broadcast(BaseTransaction transaction, IEnumerable <byte> excludedIp = null)
        {
            if (transaction == null)
            {
                throw new ArgumentNullException(nameof(transaction));
            }

            var inventory        = new Inventory(InventoryTypes.MSG_TX, transaction.GetTxId());
            var inventoryMessage = new InventoryMessage(new[] { inventory }, _network);

            foreach (var activePeer in _peers.Where(p => excludedIp != null && !p.GetCurrentIpAddress().Ipv6.SequenceEqual(excludedIp)))
            {
                activePeer.Execute(inventoryMessage.Serialize());
            }
        }
コード例 #25
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (transactionCase_ == TransactionOneofCase.BaseTransaction)
            {
                hash ^= BaseTransaction.GetHashCode();
            }
            if (transactionCase_ == TransactionOneofCase.ExtendedTransaction)
            {
                hash ^= ExtendedTransaction.GetHashCode();
            }
            hash ^= (int)transactionCase_;
            return(hash);
        }
コード例 #26
0
        public long GetFee(BaseTransaction transaction, Networks network)
        {
            if (transaction == null)
            {
                throw new ArgumentNullException(nameof(transaction));
            }

            var tx = transaction as BcBaseTransaction;

            if (tx != null)
            {
                return(GetFee(tx, network));
            }

            return(GetFee(transaction as SmartContractTransaction, network));
        }
コード例 #27
0
        public void Check(BaseTransaction transaction)
        {
            if (transaction == null)
            {
                throw new ArgumentNullException(nameof(transaction));
            }

            var bcTx = transaction as BcBaseTransaction;

            if (bcTx != null)
            {
                Check(bcTx);
                return;
            }

            Check(transaction as SmartContractTransaction);
        }
コード例 #28
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (baseTransaction_ != null)
            {
                hash ^= BaseTransaction.GetHashCode();
            }
            if (Comments.Length != 0)
            {
                hash ^= Comments.GetHashCode();
            }
            if (Extra.Length != 0)
            {
                hash ^= Extra.GetHashCode();
            }
            return(hash);
        }
コード例 #29
0
 /// <summary>
 /// Class constructor.
 /// </summary>
 /// <param name="transactionNumber">Transaction Number.</param>
 /// <param name="fromActorName">Name of Actor sending Transaction.</param>
 /// <param name="toActorName">Name of Actor receiving Transaction.</param>
 /// <param name="transaction">Transaction itself.</param>
 /// <param name="resultsFilename">Results filename.</param>
 /// <param name="resultsPathname">Full Results filename - including directory.</param>
 /// <param name="nrErrors">Number of Errors in Transaction.</param>
 /// <param name="nrWarnings">Number of Warnings in Transaction.</param>
 public ActorsTransaction(int transactionNumber,
                          ActorName fromActorName,
                          ActorName toActorName,
                          BaseTransaction transaction,
                          System.String resultsFilename,
                          System.String resultsPathname,
                          uint nrErrors,
                          uint nrWarnings)
 {
     _transactionNumber = transactionNumber;
     _fromActorName     = fromActorName;
     _toActorName       = toActorName;
     _transaction       = transaction;
     _resultsFilename   = resultsFilename;
     _resultsPathname   = resultsPathname;
     _nrErrors          = nrErrors;
     _nrWarnings        = nrWarnings;
 }
コード例 #30
0
        private void InitializeModalityProcedureStepCompletedDiscontinued()
        {
            // Get the C-STORE-RSPs returned
            foreach (ActorsTransaction actorsTransaction in ActorsTransactionLog)
            {
                if (actorsTransaction.FromActorName.Type == ActorTypeEnum.ImageArchive)
                {
                    BaseTransaction baseTransaction = actorsTransaction.Transaction;
                    if (baseTransaction is DicomTransaction)
                    {
                        DicomTransaction dicomTransaction = (DicomTransaction)baseTransaction;

                        DicomMessageCollection cStoreResponses = dicomTransaction.DicomMessages.CStoreResponses;
                        GenerateTriggers.HandleCStoreResponses(_storageCommitItems, cStoreResponses);
                    }
                }
            }
        }