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); }
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)); }
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(); } }
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); }
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)); } }
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); }
private void OnTransactionInitiated(BaseTransaction transaction) { if (m_WaitAnimation == null && waitAnimationPrefab != null) { m_WaitAnimation = Instantiate(waitAnimationPrefab).transform; } }
/// <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); }
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 }); }
/// <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; } } } }
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); }
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))); }
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)); }
public void Remove(BaseTransaction transaction) { if (transaction == null) { throw new ArgumentNullException(nameof(transaction)); } Remove(new[] { transaction.GetTxId() }); }
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)); }
/// <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++; }
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()); }
public void Broadcast(BaseTransaction transaction) { if (transaction == null) { throw new ArgumentNullException(nameof(transaction)); } if (NewTransactionEvt != null) { NewTransactionEvt(this, new TransactionEventArgs(transaction)); } }
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); }
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) { } }); }
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(); }
/** <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(); }
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()); } }
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); }
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)); }
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); }
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); }
/// <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; }
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); } } } }