/// <summary>
        /// Ask the user to open a revit family template and then add FamilyTypes and FamilyParameters
        /// to it. Say the user opens a Door template, he can then save the family as a new door family and load
        /// it into a new project for use.
        /// </summary>
        public void AddFamilyParameterAndType()
        {
            Document doc;

             OpenFileDialog openFileDialog = new OpenFileDialog();
             openFileDialog.Title = "Select family document";
             openFileDialog.Filter = "RFT Files (*.rft)|*.rft";

             if (openFileDialog.ShowDialog() == DialogResult.OK)
             {
            doc = m_revitApp.Application.NewFamilyDocument(openFileDialog.FileName);
             }
             else
            return;

             using( Transaction transaction = new Transaction( m_revitApp.ActiveUIDocument.Document ) )
             {
               transaction.Start( "AddFamilyParameterAndType" );

               if( doc.IsFamilyDocument )
               { // has to be a family document to be able to use the Family Manager.

             FamilyManager famMgr = doc.FamilyManager;

             //Add a family param.
             FamilyParameter famParam = famMgr.AddParameter( "RevitLookup_Param", BuiltInParameterGroup.PG_TITLE, ParameterType.Text, false );
             famMgr.Set( famParam, "Default text." );

             //Create a couple of new family types. Note that we can set different values for the param
             //in different family types.

             FamilyType newFamType = famMgr.NewType( "RevitLookup_Type1" );
             famMgr.CurrentType = newFamType;

             if( newFamType.HasValue( famParam ) )
             {
               famMgr.Set( famParam, "Text1." );
             }

             FamilyType newFamType1 = famMgr.NewType( "RevitLookup_Type2" );
             famMgr.CurrentType = newFamType;

             if( newFamType.HasValue( famParam ) )
             {
               famMgr.Set( famParam, "Text2." );
             }

             famMgr.MakeType( famParam );

             if( ( famParam != null ) && ( newFamType != null ) )
             {
               MessageBox.Show( "New family types/params added successfully.", "RevitLookup", MessageBoxButtons.OK, MessageBoxIcon.Information );
             }
             else
               MessageBox.Show( "Family types/params addition failed.", "RevitLookup", MessageBoxButtons.OK, MessageBoxIcon.Error );
               }

               transaction.Commit();
             }
        }
        /// <summary>
        /// Create a new dimension element using the given
        /// references and dimension line end points.
        /// This method opens and commits its own transaction,
        /// assuming that no transaction is open yet and manual
        /// transaction mode is being used.
        /// Note that this has only been tested so far using
        /// references to surfaces on planar walls in a plan
        /// view.
        /// </summary>
        public static void CreateDimensionElement(
            View view,
            XYZ p1,
            Reference r1,
            XYZ p2,
            Reference r2)
        {
            Document doc = view.Document;

              ReferenceArray ra = new ReferenceArray();

              ra.Append( r1 );
              ra.Append( r2 );

              Line line = Line.CreateBound( p1, p2 );

              using( Transaction t = new Transaction( doc ) )
              {
            t.Start( "Create New Dimension" );

            Dimension dim = doc.Create.NewDimension(
              view, line, ra );

            t.Commit();
              }
        }
Beispiel #3
0
 //kod för Labb3
 public void DepositMoney(double pengar)
 {
     Transaction transact = new Transaction("deposit", pengar, DateTime.Now);
     transactions.Add(transact);
     double tempMoney = GetCurrentMoney() + pengar;
     SetCurrentMoney(tempMoney);
 }
        public Task Traverse(Transaction tx,
            Func<JObject, bool> searchPredicate,
            Func<bool> shouldStopPredicate,
            Node rootNode = null,
            ushort? edgeTypeFilter = null,
            uint? traverseDepthLimit = null)
        {
	        if (State == AlgorithmState.Running)
                throw new InvalidOperationException("The search already running");

	        return Task.Run(() =>
	        {
		        OnStateChange(AlgorithmState.Running);

		        var visitedNodes = new HashSet<long>();
		        var processingQueue = new Queue<NodeVisitedEventArgs>();
		        rootNode = rootNode ?? GetDefaultRootNode(tx);
		        processingQueue.Enqueue(new NodeVisitedEventArgs(rootNode,null, 1, 0));

		        while (processingQueue.Count > 0)
		        {
			        if (shouldStopPredicate())
			        {
				        OnStateChange(AlgorithmState.Finished);
				        break;
			        }
    
			        AbortExecutionIfNeeded();
    
			        var currentVisitedEventInfo = processingQueue.Dequeue();
			        visitedNodes.Add(currentVisitedEventInfo.VisitedNode.Key);
			        OnNodeVisited(currentVisitedEventInfo);

			        if (searchPredicate(currentVisitedEventInfo.VisitedNode.Data))
			        {
				        OnNodeFound(currentVisitedEventInfo.VisitedNode);
				        if (shouldStopPredicate() ||
                            (traverseDepthLimit.HasValue && currentVisitedEventInfo.TraversedEdgeCount >= traverseDepthLimit.Value))
				        {
					        OnStateChange(AlgorithmState.Finished);
					        break;
				        }
			        }

			        foreach (var childNodeWithWeight in 
                        _graphStorage.Queries.GetAdjacentOf(tx, currentVisitedEventInfo.VisitedNode, edgeTypeFilter ?? 0)
				                             .Where(nodeWithWeight => !visitedNodes.Contains(nodeWithWeight.Node.Key)))
			        {
				        AbortExecutionIfNeeded();
                        processingQueue.Enqueue(new NodeVisitedEventArgs(childNodeWithWeight.Node,
                            currentVisitedEventInfo.VisitedNode, 
                            currentVisitedEventInfo.TraversedEdgeCount + 1,
                            childNodeWithWeight.WeightOfEdgeToNode));
			        }
    
		        }

		        OnStateChange(AlgorithmState.Finished);
	        });
        }
Beispiel #5
0
 public void WithdrawMoney(double pengar)
 {
     Transaction transact = new Transaction("withdraw", pengar, DateTime.Now);
     transactions.Add(transact);
     double tempMoney = GetCurrentMoney() - pengar;
     SetCurrentMoney(tempMoney);
 }
        public IEnumerable<Node> GetAdjacentOf(Transaction tx, Node node, ushort type = 0)
        {
	        if (tx == null) throw new ArgumentNullException("tx");
	        if (node == null) throw new ArgumentNullException("node");

	        var alreadyRetrievedKeys = new HashSet<long>();
            using (var edgeIterator = tx.EdgeTree.Iterate(tx.VoronTransaction))
            {
                var nodeKey = node.Key.ToSlice();
                edgeIterator.RequiredPrefix = nodeKey;
                if (!edgeIterator.Seek(nodeKey))
                    yield break;

                do
                {
                    var edgeKey = edgeIterator.CurrentKey.ToEdgeTreeKey();
                    if (edgeKey.Type != type)
                        continue;

                    if (!alreadyRetrievedKeys.Contains(edgeKey.NodeKeyTo))
                    {
                        alreadyRetrievedKeys.Add(edgeKey.NodeKeyTo);
                        var adjacentNode = LoadNode(tx, edgeKey.NodeKeyTo);
                        yield return adjacentNode;
                    }

                } while (edgeIterator.MoveNext());
            }
        }
 // Methods
 public void Execute(Customer customer)
 {
     if (customer.CustomerType.Equals("INACTIVE"))
     {
         throw new Exception("INACTIVE ID");
     }
     Boolean decrement = customer.PlanId.ToUpper().StartsWith("BLOCK");
     Transaction transaction = new Transaction();
     if (!decrement)
     {
         transaction.find(string.Concat(new object[] { "([PeopleID]='", customer.PeopleID, "') AND ([DateTime] > '", customer.MealCost.StartTime, "') AND [TTID] = 'MEALCHRG'" }));
         decrement = transaction.PeopleID == null;
     }
     if (decrement)
     {
         if (customer.CurrentMeals <= 0)
         {
             throw new Exception("Zero Meals Left");
         }
         transaction.PeopleID = customer.PeopleID;
         transaction.Amount = 0M;
         transaction.PlanID = customer.PlanId;
         transaction.LocationID = this.location;
         transaction.Ttid = this.ttid;
         transaction.currentMeals();
         customer.CurrentMeals--;
     }
 }
	    public bool ContainsEdge(Transaction tx, Edge edge)
        {
	        if (tx == null) throw new ArgumentNullException("tx");
	        if (edge == null) throw new ArgumentNullException("edge");

	        return tx.EdgeTree.ReadVersion(tx.VoronTransaction, edge.Key.ToSlice()) > 0;
        }
	    public bool ContainsNode(Transaction tx, Node node)
        {
	        if (tx == null) throw new ArgumentNullException("tx");
	        if (node == null) throw new ArgumentNullException("node");

	        return ContainsNode(tx, node.Key);
        }
        public static OperationResult Insert(DataFieldCollection pValues, ConnectionInfo pInfo)
        {
            Transaction lTransaction;

             lTransaction = new Transaction(Instance.CreateDatabase(pInfo));

             bool lLocalTransaction = (lTransaction != null);

             InsertCommand lInsert;

             OperationResult lReturn = new OperationResult(PORT_BANNERQD.TableName, PORT_BANNERQD.TableName);

             if (!lReturn.HasError){
             try{
             if (lLocalTransaction){
                 lReturn.Trace("Transação local, instanciando banco...");
             }

             lInsert = new InsertCommand(PORT_BANNERQD.TableName);

             lReturn.Trace("Adicionando campos ao objeto de insert");

             foreach (DataField lField in pValues.Keys){
                 lInsert.Fields.Add(lField.Name, pValues[lField], (ItemType)lField.DBType);
             }
             decimal lSequence;
             lSequence = DataBaseSequenceControl.GetNext(pInfo, "BAN_ID");
             lInsert.Fields.Add(PORT_BANNERQD._BAN_ID.Name, lSequence, (ItemType)PORT_BANNERQD._BAN_ID.DBType);

             lReturn.Trace("Executando o Insert");

             lInsert.Execute(lTransaction, false);

             if (!lReturn.HasError){
                 if (lLocalTransaction){
                     if (!lReturn.HasError){
                         lReturn.Trace("Insert finalizado, executando commit");

                         lTransaction.Commit();
                     }
                     else{
                         lTransaction.Rollback();
                     }
                 }
             }
             else{
                 if (lLocalTransaction)
                     lTransaction.Rollback();
             }
             }
             catch (Exception ex){
            lReturn.OperationException = new SerializableException(ex);

             if (lLocalTransaction)
                 lTransaction.Rollback();
             }
             }

             return lReturn;
        }
Beispiel #11
0
		public Transaction BroadcastTransaction(Transaction tx)
		{
			var h = tx.GetHash();
			Mempool.Add(h, tx);
			OnNewTransaction(tx);
			return tx;
		}
        public void Run()
        {
            var a = new Transaction[4];
            a[0] = new Transaction("Turing   6/17/1990  644.08");
            a[1] = new Transaction("Tarjan   3/26/2002 4121.85");
            a[2] = new Transaction("Knuth    6/14/1999  288.34");
            a[3] = new Transaction("Dijkstra 8/22/2007 2678.40");

            Console.WriteLine("Unsorted");
            foreach (var transaction in a)
                Console.WriteLine(transaction);
            Console.WriteLine();

            Console.WriteLine("Sort by date");
            Insertion<Transaction>.Sort(a, new WhenOrderComparer());
            Insertion<Transaction>.Show(a);
            Console.WriteLine();

            Console.WriteLine("Sort by customer");
            Insertion<Transaction>.Sort(a, new WhoOrderComparer());
            Insertion<Transaction>.Show(a);
            Console.WriteLine();

            Console.WriteLine("Sort by amount");
            Insertion<Transaction>.Sort(a, new HowMuchOrderComparer());
            Insertion<Transaction>.Show(a);
            Console.WriteLine();

            Console.ReadLine();
        }
Beispiel #13
0
		public bool HasDiscontinuousSpaceFor(Transaction tx, long size)
		{
			var sizesFromLargest = _freePagesBySize.Keys.OrderByDescending(x => x).ToList();

			var oldestTransaction = tx.Environment.OldestTransaction;
			long available = 0;

			foreach (var sizeKey in sizesFromLargest)
			{
				var item = _freePagesBySize[sizeKey].Last;

				while (item != null && (oldestTransaction == 0 || item.Value.ValidAfterTransactionId < oldestTransaction))
				{
					available += sizeKey;

					if(available >= size)
						break;

					item = item.Previous;
				}

				if(available >= size)
					break;
			}

			return available >= size;
		}
        public static async Task<Transaction> SendAsync(this TestServer server, string uri, string cookieHeader = null)
        {
            var request = new HttpRequestMessage(HttpMethod.Get, uri);
            if (!string.IsNullOrEmpty(cookieHeader))
            {
                request.Headers.Add("Cookie", cookieHeader);
            }
            var transaction = new Transaction
            {
                Request = request,
                Response = await server.CreateClient().SendAsync(request),
            };
            if (transaction.Response.Headers.Contains("Set-Cookie"))
            {
                transaction.SetCookie = transaction.Response.Headers.GetValues("Set-Cookie").ToList();
            }
            transaction.ResponseText = await transaction.Response.Content.ReadAsStringAsync();

            if (transaction.Response.Content != null &&
                transaction.Response.Content.Headers.ContentType != null &&
                transaction.Response.Content.Headers.ContentType.MediaType == "text/xml")
            {
                transaction.ResponseElement = XElement.Parse(transaction.ResponseText);
            }
            return transaction;
        }
Beispiel #15
0
        private static Transaction ToTransaction(ComsecTransactionCsv comsecTransactionCsv)
        {
            var transaction = new Transaction();

            // Detail field has format
            // <B or S> <quanity> <share code> @ <share price>
            // For example
            // B 269 VTS @ 148.620000

            string[] detailComponents = comsecTransactionCsv.Details.Split(new Char[] { ' ' });

            transaction.TransactionDate = comsecTransactionCsv.TransactionDate;
            transaction.ShareCode = detailComponents[2];
            transaction.Quantity = int.Parse(detailComponents[1]);

            if (detailComponents[0] == "S")
            {
                transaction.Amount = comsecTransactionCsv.Credit;
            }
            else
            {
                transaction.Amount = -1 * comsecTransactionCsv.Debit;
            }

            transaction.Reference = comsecTransactionCsv.Reference;

            return transaction;
        }
        public ServiceOperationResult AdjustBalance(OctoUser user, decimal amount, string reason)
        {
            if (string.IsNullOrWhiteSpace(reason))
                return ServiceOperationResult.Fail("A reason must be specified");

            if (amount == 0)
                return ServiceOperationResult.Fail("Cannot adjust a users balance by zero");

            if (user.Money + amount < 0)
                return ServiceOperationResult.Fail("Cannot award money that would push user into a negative balance");

            user.Money += amount;

            var trnx = new Transaction()
            {
                Amount = Math.Abs(amount),
                Code = TransactionCode.Adjustment,
                Reason = reason,
                CreatedAt = DateTimeOffset.Now,
            };

            if (amount < 0)
                trnx.DebitedUser = user;
            else
                trnx.CreditedUser = user;

            _repo.Insert(trnx);

            return ServiceOperationResult.Ok;
        }
Beispiel #17
0
 public override bool AppliesTo(Transaction transaction, BankOperation operation)
 {
     if (transaction.Type == TransactionType.Deposit)
     {
         return false;
     }
     var cardTransaction = transaction as CardTransaction;
     if (cardTransaction == null)
     {
         return false;
     }
     var userCard = _userCardRepository.Find(cardTransaction.Card.Id);
     if (userCard == null)
     {
         return false;
     }
     var query = DbQuery.For<CardTransaction>()
         .FilterBy(Specs.ForCardTransaction.Withdrawals && !Specs.ForCardTransaction.Failed && Specs.ForCardTransaction.ForToday(userCard.Id, _schedule.TimeZone));
     var transactionsForToday = _cardTransactionRepository.Query(query);
     var countForToday = transactionsForToday.Count;
     var amountForToday = transactionsForToday
         .Sum(x => -x.AccountAmount);
     var countLimit = _settings.IsLocalLocation(transaction.Location)
         ? userCard.Settings.Limits.OperationsPerDayLocal
         : userCard.Settings.Limits.OperationsPerDayAbroad;
     var amountLimit = _settings.IsLocalLocation(transaction.Location)
         ? userCard.Settings.Limits.AmountPerDayLocal
         : userCard.Settings.Limits.AmountPerDayAbroad;
     return countForToday > countLimit || amountForToday > amountLimit;
 }
		///<summary>Inserts one Transaction into the database.  Provides option to use the existing priKey.</summary>
		public static long Insert(Transaction transaction,bool useExistingPK){
			if(!useExistingPK && PrefC.RandomKeys) {
				transaction.TransactionNum=ReplicationServers.GetKey("transaction","TransactionNum");
			}
			string command="INSERT INTO transaction (";
			if(useExistingPK || PrefC.RandomKeys) {
				command+="TransactionNum,";
			}
			command+="DateTimeEntry,UserNum,DepositNum,PayNum) VALUES(";
			if(useExistingPK || PrefC.RandomKeys) {
				command+=POut.Long(transaction.TransactionNum)+",";
			}
			command+=
				     DbHelper.Now()+","
				+    POut.Long  (transaction.UserNum)+","
				+    POut.Long  (transaction.DepositNum)+","
				+    POut.Long  (transaction.PayNum)+")";
			if(useExistingPK || PrefC.RandomKeys) {
				Db.NonQ(command);
			}
			else {
				transaction.TransactionNum=Db.NonQ(command,true);
			}
			return transaction.TransactionNum;
		}
 /// <summary>
 /// Gets the attribute references.
 /// </summary>
 /// <param name="bref">The bref.</param>
 /// <param name="trx">The TRX.</param>
 /// <param name="mode">The mode.</param>
 /// <param name="includingErased">if set to <c>true</c> [including erased].</param>
 /// <param name="openObjectsOnLockedLayers">if set to <c>true</c> [open objects on locked layers].</param>
 /// <returns></returns>
 /// <exception cref="Autodesk.AutoCAD.Runtime.Exception"></exception>
 public static IEnumerable<AttributeReference> GetAttributeReferences(this BlockReference bref, Transaction trx,
     OpenMode mode = OpenMode.ForRead, bool includingErased = false, bool openObjectsOnLockedLayers = false)
 {
     if (trx == null)
     {
         throw new Exception(ErrorStatus.NoActiveTransactions);
     }
     if (includingErased)
     {
         foreach (ObjectId id in bref.AttributeCollection)
         {
             yield return (AttributeReference) trx.GetObject(id, mode, true, openObjectsOnLockedLayers);
         }
     }
     else
     {
         foreach (ObjectId id in bref.AttributeCollection)
         {
             if (!id.IsErased)
             {
                 yield return (AttributeReference) trx.GetObject(id, mode, false, openObjectsOnLockedLayers);
             }
         }
     }
 }
        public Result Execute(
          ExternalCommandData commandData,
          ref string message,
          ElementSet elements)
        {
            // Get application and document objects
            UIApplication uiApp = commandData.Application;
            Document doc = uiApp.ActiveUIDocument.Document;
            UIDocument uidoc = uiApp.ActiveUIDocument;

            try
            {
                if (!doc.IsWorkshared)
                {
                    TaskDialog.Show("Workset 3D View", "Project doesn't have any Worksets.");
                }
                else
                {
                    ViewFamilyType vft = new FilteredElementCollector(doc)
                    .OfClass(typeof(ViewFamilyType))
                    .Cast<ViewFamilyType>()
                    .FirstOrDefault(q => q.ViewFamily == ViewFamily.ThreeDimensional);

                    using (Transaction t = new Transaction(doc, "Workset View Creation"))
                    {
                        t.Start();
                        int i = 0;
                        // Loop through all User Worksets only
                        foreach (Workset wst in new FilteredWorksetCollector(doc)
                            .WherePasses(new WorksetKindFilter(WorksetKind.UserWorkset)))
                        {
                            // Create a 3D View
                            View3D view = View3D.CreateIsometric(doc, vft.Id);

                            // Set the name of the view to match workset
                            view.Name = "WORKSET - " + wst.Name;

                            // Isolate elements in the view using a filter to find elements only in this workset
                            view.IsolateElementsTemporary(new FilteredElementCollector(doc)
                                .WherePasses(new ElementWorksetFilter(wst.Id))
                                .Select(q => q.Id)
                                .ToList());
                            i++;
                        }
                        t.Commit();
                        TaskDialog.Show("Workset 3D View", i.ToString() + " Views Created Successfully!");
                    }
                }
                return Result.Succeeded;
            }
            catch (Autodesk.Revit.Exceptions.OperationCanceledException)
            {
                return Result.Cancelled;
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return Result.Failed;
            }
        }
Beispiel #21
0
 private PromptSelectionResult GetCircles(Transaction trans)
 {
     TypedValue[] types = new TypedValue[] { new TypedValue((int)DxfCode.Start, "Circle") };
     SelectionFilter selectionFilter = new SelectionFilter(types);
     PromptSelectionResult selectedObject = editor.GetSelection(selectionFilter);
     return selectedObject;
 }
 public static Common.Models.Assets.AssetTag Get(
     Transaction t,
     Guid assetId,
     int tagId)
 {
     return Get(assetId, tagId, t.Connection, false);
 }
        public override void AllocateMorePages(Transaction tx, long newLength)
        {
            if (newLength < _length)
                throw new ArgumentException("Cannot set the legnth to less than the current length");

            if (newLength == _length)
                return;

            // need to allocate memory again
            NativeFileMethods.SetFileLength(_handle, newLength);

            Debug.Assert(_fileStream.Length == newLength);

            _length = newLength;
            PagerState.Release(); // when the last transaction using this is over, will dispose it
            PagerState newPager = CreateNewPagerState();

            if (tx != null) // we only pass null during startup, and we don't need it there
            {
                newPager.AddRef(); // one for the current transaction
                tx.AddPagerState(newPager);
            }

            PagerState = newPager;
            NumberOfAllocatedPages = newLength/PageSize;
        }
 public static List<Common.Models.Billing.InvoiceExpense> ListForMatterAndInvoice(
     Transaction t,
     Guid invoiceId,
     Guid matterId)
 {
     return ListForMatterAndInvoice(invoiceId, matterId, t.Connection, false);
 }
 public static Common.Models.Billing.InvoiceExpense Get(
     Transaction t,
     Guid invoiceId,
     Guid expenseId)
 {
     return Get(invoiceId, expenseId, t.Connection, false);
 }
Beispiel #26
0
        /// <summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application 
        /// which contains data related to the command, 
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application 
        /// which will be displayed if a failure or cancellation is returned by 
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application 
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command. 
        /// A result of Succeeded means that the API external method functioned as expected. 
        /// Cancelled can be used to signify that the user cancelled the external operation 
        /// at some point. Failure should be returned if the application is unable to proceed with 
        /// the operation.</returns>
        public Autodesk.Revit.UI.Result Execute(Autodesk.Revit.UI.ExternalCommandData commandData,
            ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            Transaction newTran = null;
            try
            {
                if (null == commandData)
                {
                    throw new ArgumentNullException("commandData");
                }

                Document doc = commandData.Application.ActiveUIDocument.Document;
                ViewsMgr view = new ViewsMgr(doc);

                newTran = new Transaction(doc);
                newTran.Start("AllViews_Sample");

                AllViewsForm dlg = new AllViewsForm(view);

                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    view.GenerateSheet(doc);
                }
                newTran.Commit();

                return Autodesk.Revit.UI.Result.Succeeded;
            }
            catch (Exception e)
            {
                message = e.Message;
                if ((newTran != null) && newTran.HasStarted() && !newTran.HasEnded())
                    newTran.RollBack();
                return Autodesk.Revit.UI.Result.Failed;
            }
        }
Beispiel #27
0
        public static void GoofyCreateAndTansferCoin_SouldHaveValidCoin()
        {
            //Arrange
            var signature = new Signature(256);
            Global.GoofyPk = signature.PublicKey;

            var coin = new Coin(signature);

            //Act
            var trans = new Transaction(coin, new Signature(256).PublicKey);

            //Assert

            try
            {
                //trans.CheckTransaction();

                if (!coin.isGoofyCoin())
                    throw new Exception("This coin doenst belong to Goofy");
                if (!coin.isValidSignature())
                    throw new Exception("This coin signature is invalid");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Beispiel #28
0
 public void SetUp()
 {
     _connection = new Mock<Connection>(null);
     _commitCount = 0;
     _rollbackCount = 0;
     _target = new Transaction(_connection.Object, () => ++_commitCount, () => ++_rollbackCount);
 }
        public async Task<ByteString> PostTransaction(ByteString rawMutation, IReadOnlyList<SignatureEvidence> authentication)
        {
            Mutation mutation;
            try
            {
                // Verify that the mutation can be deserialized
                mutation = MessageSerializer.DeserializeMutation(rawMutation);
            }
            catch (InvalidProtocolBufferException)
            {
                throw new TransactionInvalidException("InvalidMutation");
            }

            if (!mutation.Namespace.Equals(this.ledgerId))
                throw new TransactionInvalidException("InvalidNamespace");

            if (mutation.Records.Count == 0)
                throw new TransactionInvalidException("InvalidMutation");

            if (mutation.Records.Any(record => record.Key.Value.Count > MaxKeySize))
                throw new TransactionInvalidException("InvalidMutation");

            ValidateAuthentication(authentication, MessageSerializer.ComputeHash(rawMutation.ToByteArray()));

            ParsedMutation parsedMutation = ParsedMutation.Parse(mutation);

            // All assets must have an overall zero balance

            IReadOnlyDictionary<AccountKey, AccountStatus> accounts =
                await this.store.GetAccounts(parsedMutation.AccountMutations.Select(entry => entry.AccountKey));

            var groups = parsedMutation.AccountMutations
                .GroupBy(account => account.AccountKey.Asset.FullPath)
                .Select(group => group.Sum(entry => entry.Balance - accounts[entry.AccountKey].Balance));

            if (groups.Any(group => group != 0))
                throw new TransactionInvalidException("UnbalancedTransaction");

            DateTime date = DateTime.UtcNow;

            await this.validator.Validate(parsedMutation, authentication, accounts);

            TransactionMetadata metadata = new TransactionMetadata(authentication);

            byte[] rawMetadata = SerializeMetadata(metadata);

            Transaction transaction = new Transaction(rawMutation, date, new ByteString(rawMetadata));
            byte[] serializedTransaction = MessageSerializer.SerializeTransaction(transaction);

            try
            {
                await this.store.AddTransactions(new[] { new ByteString(serializedTransaction) });
            }
            catch (ConcurrentMutationException)
            {
                throw new TransactionInvalidException("OptimisticConcurrency");
            }

            return new ByteString(MessageSerializer.ComputeHash(serializedTransaction));
        }
Beispiel #30
0
        private bool _drawing;     // Drawing mode active

        public KinectSwitchJig(
          Document doc, Transaction tr, double profSide, double factor
        )
        {
            // Initialise the various members

            _doc = doc;
            _tr = tr;
            _vertices = new Point3dCollection();
            _lastDrawnVertex = -1;
            _resizing = false;
            _drawing = false;
            _created = new DBObjectCollection();
            _profSide = profSide;
            _segFactor = factor;
            switchm = 0;

            Words.Add("red");
            Words.Add("green");
            Words.Add("blue");
            Words.Add("yellow");
            Words.Add("pink");
            Words.Add("magenta");
            Words.Add("cyan");
        }
Beispiel #31
0
        public static IEnumerable <TransactionMatch> GetMatches(this Repository repository, Transaction tx)
        {
            var matches = new Dictionary <DerivationStrategyBase, TransactionMatch>();
            HashSet <Script> scripts = new HashSet <Script>();

            foreach (var input in tx.Inputs)
            {
                var signer = input.ScriptSig.GetSigner() ?? input.WitScript.ToScript().GetSigner();
                if (signer != null)
                {
                    scripts.Add(signer.ScriptPubKey);
                }
            }

            int scriptPubKeyIndex = scripts.Count;

            foreach (var output in tx.Outputs)
            {
                scripts.Add(output.ScriptPubKey);
            }

            var keyInformations = repository.GetKeyInformations(scripts.ToArray());

            for (int scriptIndex = 0; scriptIndex < keyInformations.Length; scriptIndex++)
            {
                for (int i = 0; i < keyInformations[scriptIndex].Length; i++)
                {
                    var keyInfo = keyInformations[scriptIndex][i];
                    if (!matches.TryGetValue(keyInfo.DerivationStrategy, out TransactionMatch match))
                    {
                        match = new TransactionMatch();
                        matches.Add(keyInfo.DerivationStrategy, match);
                        match.DerivationStrategy = keyInfo.DerivationStrategy;
                        match.Transaction        = tx;
                    }
                    var isOutput = scriptIndex >= scriptPubKeyIndex;
                    if (isOutput)
                    {
                        match.Outputs.Add(keyInfo);
                    }
                    else
                    {
                        match.Inputs.Add(keyInfo);
                    }
                }
            }
            return(matches.Values);
        }
Beispiel #32
0
        private static void Main(string[] args)
        {
            // get internal litedb database filename from app settings
            var databaseFileName = ConfigurationManager.AppSettings["LiteDBFileName"];

            // init the database
            Database = new DatabaseConsumer(databaseFileName);
            // get saved subscriptions
            Subscriptions = Database.GetSubscriptions().ToList();

            // get RPC connection params from app settings
            var rpcURL      = ConfigurationManager.AppSettings["RPCURI"];
            var rpcUsername = ConfigurationManager.AppSettings["RPCUsername"];
            var rpcPassword = ConfigurationManager.AppSettings["RPCPassword"];

            // init RPC connection
            RPCClient = new RPCClient(new Uri(rpcURL), rpcUsername, rpcPassword);
            // get info for the last block that was processed
            var lastBlock  = Database.GetLastBlock();
            var blockCount = RPCClient.GetBlockCount();

            // write out of the current block height, and last processed block height
            Console.Write("Current block: " + blockCount + ". " + (lastBlock == null ? " No previous block data found." : " Last block processed: " + lastBlock.Height));
            // if we already have block data, fetch transactions since the last seen block
            if (lastBlock != null && lastBlock.Height < blockCount)
            {
                Console.WriteLine(". processing " + (blockCount - lastBlock.Height) + " blocks...");
                // record how long it takes to process the block data
                var stopWatch = new Stopwatch();
                stopWatch.Start();
                // look at all blocks from the last block that was processed until the current height
                for (var blockIndex = lastBlock.Height; blockIndex <= blockCount; blockIndex++)
                {
                    // fetch raw block data by height
                    var blockHash = RPCClient.GetBlockHash(blockIndex);
                    var blockData = RPCClient.GetBlockData(blockHash);
                    // decode the block
                    var block = new Block(ByteToHex.StringToByteArray(blockData))
                    {
                        FirstSeen = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
                    };
                    // add the block to the database
                    Database.EnqueueTask(new DatabaseWrite(block), 0);
                    // process all transactions that occured in the block
                    foreach (var transaction in block.Transactions)
                    {
                        // does this transaction contain an output we are watching?
                        SubscriptionCheck.CheckForSubscription(transaction);
                    }
                }

                stopWatch.Stop();
                var elapsed = stopWatch.Elapsed;
                Console.Write("Processed blocks in " + $"{elapsed.Hours:00}:{elapsed.Minutes:00}:{elapsed.Seconds:00}.{elapsed.Milliseconds / 10:00}");
            }
            Console.WriteLine();

            // get websocket listen address/port from app settings
            var websocketListen = ConfigurationManager.AppSettings["WebSocketListen"];

            // start websocket server
            WebSocketServer = new WebSocket.Server(websocketListen);

            // get ZMQ server address from app settings
            var zmqServerTX    = ConfigurationManager.AppSettings["ZMQPublisherRawTX"];
            var zmqServerBlock = ConfigurationManager.AppSettings["ZMQPublisherRawBlock"];

            // start ZMQ subscribers
            new ZMQ.Subscriber(zmqServerTX, "rawtx", new TXConsumer());
            new ZMQ.Subscriber(zmqServerBlock, "rawblock", new BlockConsumer());

            // skip scanning the mempool if there is no saved block data yet (TODO: maybe it should still scan?)
            if (lastBlock != null)
            {
                // fetch the mempool
                var memPool = RPCClient.GetMemPool();
                Console.WriteLine("Mempool contains " + memPool.Length + " transactions; processing...");

                // record how long it takes to process the mempool
                var stopWatch2 = new Stopwatch();
                stopWatch2.Start();
                // process all mempool transactions
                foreach (var txid in memPool)
                {
                    var rawTransaction = RPCClient.GetRawTransaction(txid);
                    var transaction    = new Transaction(rawTransaction)
                    {
                        FirstSeen   = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
                        LastUpdated = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
                    };

                    // does this transaction contain an output we are watching?
                    SubscriptionCheck.CheckForSubscription(transaction);
                }

                stopWatch2.Stop();
                var elapsed2 = stopWatch2.Elapsed;
                Console.WriteLine("Processed mempool in " +
                                  $"{elapsed2.Hours:00}:{elapsed2.Minutes:00}:{elapsed2.Seconds:00}.{elapsed2.Milliseconds / 10:00}");
            }
            else
            {
                Console.WriteLine("Skipping mempool scan on first run.");
            }
        }
Beispiel #33
0
        public async Task <FaucetResponse> TryRequestEthAsync(string node, Address address, UInt256 value)
        {
            if (!_enabled)
            {
                if (_logger.IsInfo)
                {
                    _logger.Info("NDM Faucet is disabled.");
                }
                return(FaucetResponse.FaucetDisabled);
            }

            if (!_initialized)
            {
                if (_logger.IsInfo)
                {
                    _logger.Info("NDM Faucet is not initialized.");
                }
                return(FaucetResponse.FaucetDisabled);
            }

            if (_today.Date != _timestamper.UtcNow.Date)
            {
                lock (_locker)
                {
                    _today = _timestamper.UtcNow;
                    _todayRequestsTotalValueWei = 0;
                }

                if (_logger.IsInfo)
                {
                    _logger.Info($"NDM Faucet has updated its today's date ({_today.Date:d}) and reset the total requests value.");
                }
            }

            if (_faucetAddress is null || _faucetAddress == Address.Zero)
            {
                if (_logger.IsWarn)
                {
                    _logger.Warn("NDM Faucet address is not set.");
                }
                return(FaucetResponse.FaucetAddressNotSet);
            }

            if (string.IsNullOrWhiteSpace(node) || address is null || address == Address.Zero)
            {
                if (_logger.IsInfo)
                {
                    _logger.Info("Invalid NDM Faucet request.");
                }
                return(FaucetResponse.InvalidNodeAddress);
            }

            if (_faucetAddress == address)
            {
                if (_logger.IsInfo)
                {
                    _logger.Info("NDM Faucet request cannot be processed for the same address as NDM Faucet.");
                }
                return(FaucetResponse.SameAddressAsFaucet);
            }

            if (value == 0)
            {
                if (_logger.IsInfo)
                {
                    _logger.Info("NDM Faucet request cannot be processed for the zero value.");
                }
                return(FaucetResponse.ZeroValue);
            }

            if (value > _maxValue)
            {
                if (_logger.IsInfo)
                {
                    _logger.Info($"NDM Faucet request from: {node} has too big value: {value} wei > {_maxValue} wei.");
                }
                return(FaucetResponse.TooBigValue);
            }

            if (_logger.IsInfo)
            {
                _logger.Info($"Received NDM Faucet request from: {node}, address: {address}, value: {value} wei.");
            }
            if (_pendingRequests.TryGetValue(node, out _))
            {
                if (_logger.IsInfo)
                {
                    _logger.Info($"NDM Faucet request from: {node} is already being processed.");
                }
                return(FaucetResponse.RequestAlreadyProcessing);
            }

            var latestRequest = await _requestRepository.GetLatestAsync(node);

            var requestedAt = _timestamper.UtcNow;

            if (!(latestRequest is null) && latestRequest.RequestedAt.Date >= requestedAt.Date)
            {
                if (_logger.IsInfo)
                {
                    _logger.Info($"NDM Faucet request from: {node} was already processed today at: {latestRequest.RequestedAt}.");
                }
                return(FaucetResponse.RequestAlreadyProcessedToday(FaucetRequestDetails.From(latestRequest)));
            }

            if (!_pendingRequests.TryAdd(node, true))
            {
                if (_logger.IsWarn)
                {
                    _logger.Warn($"Couldn't start processing NDM Faucet request from: {node}.");
                }
                return(FaucetResponse.RequestError);
            }

            lock (_locker)
            {
                _todayRequestsTotalValueWei += value;
                if (_logger.IsInfo)
                {
                    _logger.Info($"Increased NDM Faucet total value of today's ({_today.Date:d}) requests to {_todayRequestsTotalValueWei} wei.");
                }
            }

            if (_todayRequestsTotalValueWei > _dailyRequestsTotalValueWei)
            {
                if (_logger.IsInfo)
                {
                    _logger.Info($"Daily ({_today.Date:d}) requests value for NDM Faucet was reached ({_dailyRequestsTotalValueWei} wei).");
                }
                return(FaucetResponse.DailyRequestsTotalValueReached);
            }

            if (_logger.IsInfo)
            {
                _logger.Info($"NDM Faucet is processing request for: {node}, address: {address}, value: {value} wei.");
            }
            try
            {
                var faucetAccount = _blockchainBridge.GetAccount(_faucetAddress);
                var transaction   = new Transaction
                {
                    Value         = value,
                    GasLimit      = 21000,
                    GasPrice      = 20.GWei(),
                    To            = address,
                    SenderAddress = _faucetAddress,
                    Nonce         = faucetAccount?.Nonce ?? 0
                };
                _blockchainBridge.Sign(transaction);
                var transactionHash = _blockchainBridge.SendTransaction(transaction, true);
                if (latestRequest is null)
                {
                    var requestId = Keccak.Compute(Rlp.Encode(Rlp.Encode(node)));
                    latestRequest = new EthRequest(requestId, node, address, value, requestedAt, transactionHash);
                    await _requestRepository.AddAsync(latestRequest);
                }
                else
                {
                    latestRequest.UpdateRequestDetails(address, value, requestedAt, transactionHash);
                    await _requestRepository.UpdateAsync(latestRequest);
                }

                if (_logger.IsInfo)
                {
                    _logger.Info($"NDM Faucet has successfully processed request for: {node}, address: {address}, value: {value} wei.");
                }
                return(FaucetResponse.RequestCompleted(FaucetRequestDetails.From(latestRequest)));
            }
            catch (Exception ex)
            {
                if (_logger.IsError)
                {
                    _logger.Error(ex.Message, ex);
                }
                lock (_locker)
                {
                    _todayRequestsTotalValueWei -= value;
                    if (_logger.IsInfo)
                    {
                        _logger.Info($"Decreased NDM Faucet total value of today's ({_today.Date:d}) requests to {_todayRequestsTotalValueWei} wei.");
                    }
                }

                return(FaucetResponse.ProcessingRequestError);
            }
            finally
            {
                _pendingRequests.TryRemove(node, out _);
            }
        }
        public void CanCreatePayment()
        {
            var tests = new[]
            {
                new CanCreatePaymentData
                {
                    //sx stealth-newkey
                    StealthAddress = "vJmtjxSDxNPXL4RNapp9ARdqKz3uJyf1EDGjr1Fgqs9c8mYsVH82h8wvnA4i5rtJ57mr3kor1EVJrd4e5upACJd588xe52yXtzumxj",

                    ScanSecret = "3e49e7257cb31db997edb1cf8299af0f37e2663e2260e4b8033e49d39a6d02f2",
                    ScanPubKey = "025e58a31122b38c86abc119b9379fe247410aee87a533f9c07b189aef6c3c1f52",

                    SpendSecret = "aa3db0cfb3edc94de4d10f873f8190843f2a17484f6021a95a7742302c744748",
                    SpendPubKey = "03616562c98e7d7b74be409a787cec3a912122f3fb331a9bee9b0b73ce7b9f50af",

                    //sx newkey | sx wif-to-secret
                    EphemSecret = "9e63abaf8dcd5ea3919e6de0b6c544e00bf51bf92496113a01d6e369944dc091",
                    EphemPubKey = "03403d306ec35238384c7e340393335f9bc9bb4a2e574eb4e419452c4ea19f14b0",

                    //sx steatlh-uncover-secret [EphemPubKey] [ScanSecret] [SpendSecret]
                    StealthSecret = "4e422fb1e5e1db6c1f6ab32a7706d368ceb385e7fab098e633c5c5949c3b97cd",
                    //sx stealth-initiate [EphemSecret] [ScanPubKey] [SpendPubKey] (for sender)
                    //or
                    //sx stealth-uncover [EphemPubKey] [ScanSecret] [SpendPubKey]  (for receiver)
                    StealthPubKey = "02726112ad39cb6bf848b1b1ef30b88e35286bf99f746c2be575f96c0e02a9357c",
                },

                //Need padding for to find the stealth secret
                new CanCreatePaymentData {
                    StealthAddress = "vJmyTEybwCKz7W8y6vP62jo7RoyfLneiANcPLBBNYwn98EXzQRStMKqKGRiZhqscuQ6WKy2J3U3zfx72V3b2J6YvxxBcxUj4XMDsw7",
                    ScanSecret     = "2f517d81cf30e47dbf4809321275bbfd92192af81a6141a17aa53e40bd28fe36",
                    ScanPubKey     = "039d91ae0eebea6dc500fb57b704abce3d3fa700cc762a52bc5dcaee27770a8402",
                    SpendSecret    = "71e33219884fc27011f8da9adcc730f0c2e940759bdb1b615764492bce04fcea",
                    SpendPubKey    = "021a3d5b40ec83fc58b5a23207eb9c99b741d8f0e9f8b80f04f49cec915b540c40",
                    EphemSecret    = "578ffe42c0fbfb324a31f41dbbcd8b1f910ce2f4d803444a83b18ae9f8ccd97e",
                    EphemPubKey    = "03c190be0a1c6e50577b3dd637b1fff9344de31c2544ff3d815535c0515711150f",
                    StealthSecret  = "006d138b4bcef0f09c8784c0cc68f2be4497a1a822d8d7b0519c5c0378b5cb45",
                    StealthPubKey  = "0223a99278a5279ea93718503a42377067e72960eb808d8bff6defdd95d4feff76"
                }
            };

            foreach (var test in tests)
            {
                var scan    = AssertKeys(test.ScanSecret, test.ScanPubKey);
                var spend   = AssertKeys(test.SpendSecret, test.SpendPubKey);
                var ephem   = AssertKeys(test.EphemSecret, test.EphemPubKey);
                var stealth = AssertKeys(test.StealthSecret, test.StealthPubKey);

                var address = spend.PubKey.CreateStealthAddress(scan.PubKey, Network.Main);
                Assert.Equal(test.StealthAddress, address.ToString());
                //Try roundtrip
                address = new BitcoinStealthAddress(address.ToBytes(), Network.Main);
                Assert.Equal(test.StealthAddress, address.ToString());

                var payment      = address.CreatePayment(ephem);
                var generatedKey = spend.Uncover(scan, payment.Metadata.EphemKey);
                if (stealth != null)
                {
                    Assert.Equal(stealth.PubKey.Hash, payment.StealthKeys[0].ID);
                    Assert.Equal(stealth.ToBytes(), generatedKey.ToBytes());
                }
                var uncoveredSender    = spend.PubKey.UncoverSender(ephem, scan.PubKey);
                var uncovertedReceiver = spend.PubKey.UncoverReceiver(scan, ephem.PubKey);

                AssertEx.CollectionEquals(uncoveredSender.ToBytes(), uncovertedReceiver.ToBytes());
                AssertEx.CollectionEquals(generatedKey.PubKey.ToBytes(), uncovertedReceiver.ToBytes());

                var transaction = new Transaction();
                payment.AddToTransaction(transaction, 100);
            }
        }
Beispiel #35
0
        /// <summary>
        /// Inserts or updates multiple instances of FiscalYear class on the database table "core.fiscal_year";
        /// </summary>
        /// <param name="fiscalYears">List of "FiscalYear" class to import.</param>
        /// <returns></returns>
        public List<object> BulkImport(List<ExpandoObject> fiscalYears)
        {
            if (!this.SkipValidation)
            {
                if (!this.Validated)
                {
                    this.Validate(AccessTypeEnum.ImportData, this._LoginId, this._Catalog, false);
                }

                if (!this.HasAccess)
                {
                    Log.Information("Access to import entity \"FiscalYear\" was denied to the user with Login ID {LoginId}. {fiscalYears}", this._LoginId, fiscalYears);
                    throw new UnauthorizedException("Access is denied.");
                }
            }

            var result = new List<object>();
            int line = 0;
            try
            {
                using (Database db = new Database(Factory.GetConnectionString(this._Catalog), Factory.ProviderName))
                {
                    using (Transaction transaction = db.GetTransaction())
                    {
                        foreach (dynamic fiscalYear in fiscalYears)
                        {
                            line++;

                            fiscalYear.audit_user_id = this._UserId;
                            fiscalYear.audit_ts = System.DateTime.UtcNow;

                            object primaryKeyValue = fiscalYear.fiscal_year_code;

                            if (!string.IsNullOrWhiteSpace(fiscalYear.fiscal_year_code))
                            {
                                result.Add(fiscalYear.fiscal_year_code);
                                db.Update("core.fiscal_year", "fiscal_year_code", fiscalYear, fiscalYear.fiscal_year_code);
                            }
                            else
                            {
                                result.Add(db.Insert("core.fiscal_year", "fiscal_year_code", fiscalYear));
                            }
                        }

                        transaction.Complete();
                    }

                    return result;
                }
            }
            catch (NpgsqlException ex)
            {
                string errorMessage = $"Error on line {line} ";

                if (ex.Code.StartsWith("P"))
                {
                    errorMessage += Factory.GetDBErrorResource(ex);

                    throw new MixERPException(errorMessage, ex);
                }

                errorMessage += ex.Message;
                throw new MixERPException(errorMessage, ex);
            }
            catch (System.Exception ex)
            {
                string errorMessage = $"Error on line {line} ";
                throw new MixERPException(errorMessage, ex);
            }
        }
Beispiel #36
0
        /// <summary>
        /// Копирует все выбранные элементы в выбранные документы
        /// </summary>
        /// <param name="documentFrom">Документ из которого производится копирование</param>
        /// <param name="documentsTo">Список документов в которые осуществляется копирование</param>
        /// <param name="elements">Список элементов Revit</param>
        /// <param name="copyingOptions">Настройки копирования элементов</param>
        public async void CopyElements(
            RevitDocument documentFrom,
            IEnumerable <RevitDocument> documentsTo,
            List <BrowserItem> elements,
            CopyingOptions copyingOptions)
        {
            _uiApplication.Application.FailuresProcessing += Application_FailuresProcessing;

            var revitDocuments = documentsTo.ToList();

            Logger.Instance.Add(string.Format(
                                    ModPlusAPI.Language.GetItem(LangItem, "m5"),
                                    DateTime.Now.ToLocalTime(),
                                    documentFrom.Title,
                                    string.Join(", ", revitDocuments.Select(doc => doc.Title))));
            Logger.Instance.Add(string.Format(
                                    ModPlusAPI.Language.GetItem(LangItem, "m8"),
                                    GetCopyingOptionsName(copyingOptions)));

            var copyPasteOption = new CopyPasteOptions();

            switch (copyingOptions)
            {
            case CopyingOptions.AllowDuplicates:
                copyPasteOption.SetDuplicateTypeNamesHandler(new CustomCopyHandlerAllow());
                break;

            case CopyingOptions.RefuseDuplicate:
                copyPasteOption.SetDuplicateTypeNamesHandler(new CustomCopyHandlerAbort());
                break;
            }

            foreach (var documentTo in revitDocuments)
            {
                foreach (var element in elements)
                {
                    var succeed = true;
                    try
                    {
                        await Task.Delay(100).ConfigureAwait(true);

                        var elementId    = new ElementId(element.Id);
                        var revitElement = documentFrom.Document.GetElement(elementId);
                        ICollection <ElementId> elementIds = new List <ElementId> {
                            elementId
                        };

                        using (var transaction = new Transaction(
                                   documentTo.Document,
                                   ModPlusAPI.Language.GetItem(LangItem, "m27")))
                        {
                            transaction.Start();

                            try
                            {
                                if (revitElement.GetType() == typeof(Workset))
                                {
                                    if (documentTo.Document.IsWorkshared)
                                    {
                                        Workset.Create(documentTo.Document, revitElement.Name);
                                    }
                                    else
                                    {
                                        Logger.Instance.Add(string.Format(
                                                                ModPlusAPI.Language.GetItem(LangItem, "m9"),
                                                                DateTime.Now.ToLocalTime(),
                                                                documentTo.Title));
                                    }
                                }

                                if (_stopCopyingOperation)
                                {
                                    _stopCopyingOperation = false;
                                    OnPassedElementsCountChanged(true);
                                    return;
                                }

                                ElementTransformUtils.CopyElements(
                                    documentFrom.Document,
                                    elementIds,
                                    documentTo.Document,
                                    null,
                                    copyPasteOption);
                            }
                            catch (Exception e)
                            {
                                Logger.Instance.Add(string.Format(
                                                        ModPlusAPI.Language.GetItem(LangItem, "m7"),
                                                        DateTime.Now.ToLocalTime(),
                                                        element.Name,
                                                        element.Id,
                                                        element.CategoryName,
                                                        e.Message));

                                succeed = false;
                            }

                            transaction.Commit();
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.Instance.Add(string.Format(
                                                ModPlusAPI.Language.GetItem(LangItem, "m7"),
                                                DateTime.Now.ToLocalTime(),
                                                element.Name,
                                                element.Id,
                                                element.CategoryName,
                                                e.Message));

                        succeed = false;
                    }

                    if (!succeed)
                    {
                        OnBrokenElementsCountChanged();
                    }

                    _passedElements++;
                    if (_passedElements == elements.Count * revitDocuments.Count)
                    {
                        OnPassedElementsCountChanged(true);
                        _passedElements = 0;
                        _uiApplication.Application.FailuresProcessing -= Application_FailuresProcessing;
                    }
                    else
                    {
                        OnPassedElementsCountChanged(false);
                    }
                }
            }

            Logger.Instance.Add(string.Format(
                                    ModPlusAPI.Language.GetItem(LangItem, "m6"),
                                    DateTime.Now.ToLocalTime(),
                                    documentFrom.Title,
                                    string.Join(", ", revitDocuments.Select(doc => doc.Title))));
            Logger.Instance.Add("---------");
        }
Beispiel #37
0
        public TransactionPolicyError[] Check(Transaction transaction, ICoin[] spentCoins)
        {
            if (transaction == null)
            {
                throw new ArgumentNullException("transaction");
            }

            spentCoins = spentCoins ?? new ICoin[0];

            var errors = new List <TransactionPolicyError>();



            foreach (IndexedTxIn input in transaction.Inputs.AsIndexedInputs())
            {
                ICoin coin = spentCoins.FirstOrDefault(s => s.Outpoint == input.PrevOut);
                if (coin != null)
                {
                    if (this.ScriptVerify != null)
                    {
                        ScriptError error;
                        if (!VerifyScript(input, coin.TxOut.ScriptPubKey, coin.TxOut.Value, this.ScriptVerify.Value, out error))
                        {
                            errors.Add(new ScriptPolicyError(input, error, this.ScriptVerify.Value, coin.TxOut.ScriptPubKey));
                        }
                    }
                }

                TxIn txin = input.TxIn;
                if (txin.ScriptSig.Length > MaxScriptSigLength)
                {
                    errors.Add(new InputPolicyError("Max scriptSig length exceeded actual is " + txin.ScriptSig.Length + ", max is " + MaxScriptSigLength, input));
                }
                if (!txin.ScriptSig.IsPushOnly)
                {
                    errors.Add(new InputPolicyError("All operation should be push", input));
                }
                if (!txin.ScriptSig.HasCanonicalPushes)
                {
                    errors.Add(new InputPolicyError("All operation should be canonical push", input));
                }
            }

            if (this.CheckMalleabilitySafe)
            {
                foreach (IndexedTxIn input in transaction.Inputs.AsIndexedInputs())
                {
                    ICoin coin = spentCoins.FirstOrDefault(s => s.Outpoint == input.PrevOut);
                    if (coin != null && coin.GetHashVersion(this.network) != HashVersion.Witness)
                    {
                        errors.Add(new InputPolicyError("Malleable input detected", input));
                    }
                }
            }

            if (this.CheckScriptPubKey)
            {
                foreach (Coin txout in transaction.Outputs.AsCoins())
                {
                    ScriptTemplate template = StandardScripts.GetTemplateFromScriptPubKey(this.network, txout.ScriptPubKey);
                    if (template == null)
                    {
                        errors.Add(new OutputPolicyError("Non-Standard scriptPubKey", (int)txout.Outpoint.N));
                    }
                }
            }

            int txSize = transaction.GetSerializedSize();

            if (this.MaxTransactionSize != null)
            {
                if (txSize >= this.MaxTransactionSize.Value)
                {
                    errors.Add(new TransactionSizePolicyError(txSize, this.MaxTransactionSize.Value));
                }
            }

            Money fees = transaction.GetFee(spentCoins);

            if (fees != null)
            {
                if (this.CheckFee)
                {
                    if (this.MaxTxFee != null)
                    {
                        Money max = this.MaxTxFee.GetFee(txSize);
                        if (fees > max)
                        {
                            errors.Add(new FeeTooHighPolicyError(fees, max));
                        }
                    }

                    if (this.MinRelayTxFee != null)
                    {
                        if (this.MinRelayTxFee != null)
                        {
                            Money min = this.MinRelayTxFee.GetFee(txSize);
                            if (fees < min)
                            {
                                errors.Add(new FeeTooLowPolicyError(fees, min));
                            }
                        }
                    }
                }
            }
            if (this.MinRelayTxFee != null)
            {
                foreach (TxOut output in transaction.Outputs)
                {
                    byte[] bytes = output.ScriptPubKey.ToBytes(true);
                    if (output.IsDust(this.MinRelayTxFee) && !IsOpReturn(bytes))
                    {
                        errors.Add(new DustPolicyError(output.Value, output.GetDustThreshold(this.MinRelayTxFee)));
                    }
                }
            }
            int opReturnCount = transaction.Outputs.Select(o => o.ScriptPubKey.ToBytes(true)).Count(b => IsOpReturn(b));

            if (opReturnCount > 1)
            {
                errors.Add(new TransactionPolicyError("More than one op return detected"));
            }
            return(errors.ToArray());
        }
		public Money GetValueIn(Transaction tx)
		{
			return tx.Inputs.Select(txin => GetOutputFor(txin).Value).Sum();
		}
 private void RemoveTransaction(Transaction transaction)
 {
     _transactionRepository.DeleteTransaction(transaction.Id);
     UpdateViewModels();
 }
Beispiel #40
0
        public LayerStatesLocker OpenLayer(Transaction tr, ObjectId layerid)
        {
            LayerStatesLocker result = new LayerStatesLocker(tr, layerid);

            return(result);
        }
Beispiel #41
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;
            Selection     sel   = uidoc.Selection;

            // Retrieve all floors from the model

            var floors
                = new FilteredElementCollector(doc)
                  .OfClass(typeof(Floor))
                  .ToElements()
                  .Cast <Floor>()
                  .ToList();

            if (2 != floors.Count)
            {
                message = "Please create two intersected floors";
                return(Result.Failed);
            }

            // Retrieve the floor solids

            Options opt = new Options();

            var geometry1 = floors[0].get_Geometry(opt);
            var geometry2 = floors[1].get_Geometry(opt);

            var solid1 = geometry1.FirstOrDefault() as Solid;
            var solid2 = geometry2.FirstOrDefault() as Solid;

            // Calculate the intersection solid

            var intersectedSolid = BooleanOperationsUtils
                                   .ExecuteBooleanOperation(solid1, solid2,
                                                            BooleanOperationsType.Intersect);

            // Search for the metric mass family template file

            string template_path = DirSearch(
                app.FamilyTemplatePath,
                "Metric Mass.rft");

            // Create a new temporary family

            var family_doc = app.NewFamilyDocument(
                template_path);

            // Create a free form element
            // from the intersection solid

            using (var t = new Transaction(family_doc))
            {
                t.Start("Add Free Form Element");

                var freeFormElement = FreeFormElement.Create(
                    family_doc, intersectedSolid);

                t.Commit();
            }

            string dir = Path.GetTempPath();

            string filepath = Path.Combine(dir,
                                           "floor_intersection_family.rfa");

            SaveAsOptions sao = new SaveAsOptions()
            {
                OverwriteExistingFile = true
            };

            family_doc.SaveAs(filepath, sao);

            // Create 3D View

            var viewFamilyType
                = new FilteredElementCollector(family_doc)
                  .OfClass(typeof(ViewFamilyType))
                  .OfType <ViewFamilyType>()
                  .FirstOrDefault(x =>
                                  x.ViewFamily == ViewFamily.ThreeDimensional);

            View3D threeDView;

            using (var t = new Transaction(family_doc))
            {
                t.Start("Create 3D View");

                threeDView = View3D.CreateIsometric(
                    family_doc, viewFamilyType.Id);

                t.Commit();
            }

            // Export to SAT

            var viewSet = new List <ElementId>()
            {
                threeDView.Id
            };

            SATExportOptions exportOptions
                = new SATExportOptions();

            var res = family_doc.Export(dir,
                                        "SolidFile.sat", viewSet, exportOptions);

            return(Result.Succeeded);
        }
		public bool HaveInputs(Transaction tx)
		{
			return tx.Inputs.All(txin => GetOutputFor(txin) != null);
		}
        public static void GetProfile(ObjectId profileLine, string majorContLayer, string minorContLayer)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                List <ObjectId>                contoursId    = new List <ObjectId>();
                ObjectIdCollection             majorEnts     = SelectByLayer(majorContLayer);
                ObjectIdCollection             minorEnts     = SelectByLayer(minorContLayer);
                List <Tuple <double, double> > intersectDist = new List <Tuple <double, double> >();
                double maxElevation  = 0;
                double profileLength = 0;
                #region Combining two selection collection together into one single list
                if (majorEnts != null)
                {
                    foreach (ObjectId id in majorEnts)
                    {
                        contoursId.Add(id);
                    }
                    if (GlobalVars.majorOnly == false)
                    {
                        foreach (ObjectId id in minorEnts)
                        {
                            contoursId.Add(id);
                        }
                    }
                    #endregion
                    foreach (ObjectId id in contoursId)
                    {
                        using (DocumentLock doclock = doc.LockDocument())
                        {
                            BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForRead);
                            Polyline         ent = tr.GetObject(profileLine, OpenMode.ForRead) as Polyline;
                            //Label start and end of section
                            CreateLayer("PROFILEVIEWER.PROFILE LABEL", 10);
                            DrawText(new Point2d(ent.StartPoint.X, ent.StartPoint.Y), GlobalVars.textHeight * 2, 0, "A", "PROFILEVIEWER.PROFILE LABEL", 10);
                            DrawText(new Point2d(ent.EndPoint.X, ent.EndPoint.Y), GlobalVars.textHeight * 2, 0, "A'", "PROFILEVIEWER.PROFILE LABEL", 10);
                            Polyline ent2 = tr.GetObject(id, OpenMode.ForWrite) as Polyline;
                            double   elav = ent2.Elevation; //store elevation temporary
                            ent2.Elevation = 0;

                            if (maxElevation < elav)
                            {
                                maxElevation = elav;
                            }
                            profileLength = ent.Length;

                            /// SET ELEVATION TO ZERO TEMPORARY THEN PUT IT BACk
                            Point3dCollection intersectionPoints = new Point3dCollection();
                            ent.IntersectWith(ent2, Intersect.OnBothOperands, intersectionPoints, IntPtr.Zero, IntPtr.Zero);
                            foreach (Point3d pt in intersectionPoints)
                            {
                                Point3d ptOnProfile = ent.GetClosestPointTo(pt, true);
                                double  ptParameter = ent.GetParameterAtPoint(ptOnProfile);
                                double  a           = ent.GetDistanceAtParameter(ptParameter);
                                double  b           = ent.GetDistanceAtParameter(ent.StartParam);
                                double  distance    = a - b;
                                //double distance = ent.GetDistAtPoint(pt);
                                Tuple <double, double> xsectPt = new Tuple <double, double>(distance, elav);
                                intersectDist.Add(xsectPt);
                            }
                            ent2.Elevation = elav; //set it back
                        }
                    }
                    if (intersectDist.Count > 0)
                    {
                        intersectDist.Sort(); //sort to get the start and end points
                        double profileStartY = intersectDist[0].Item2;
                        double profileEndY   = intersectDist[intersectDist.Count - 1].Item2;
                        Tuple <double, double> xsectStart = new Tuple <double, double>(0, profileStartY);           //start of profile
                        Tuple <double, double> xsectEnd   = new Tuple <double, double>(profileLength, profileEndY); //end of profile
                        intersectDist.Add(xsectStart);
                        intersectDist.Add(xsectEnd);
                        intersectDist.Sort(); //have to resort after adding new points
                        Polyline profile = new Polyline();
                        for (int i = 0; i < intersectDist.Count; i++)
                        {
                            profile.AddVertexAt(i, new Point2d(intersectDist[i].Item1 + GlobalVars.insertionPt.X, intersectDist[i].Item2 + GlobalVars.insertionPt.Y), 0, 0, 0);
                            double  elevationGrid = DrawLine(new Point3d(intersectDist[i].Item1 + GlobalVars.insertionPt.X, intersectDist[i].Item2 + GlobalVars.insertionPt.Y, 0), new Point3d(intersectDist[i].Item1 + GlobalVars.insertionPt.X, GlobalVars.insertionPt.Y, 0), "PROFILEVIEWER.GRIDLINES", 252);
                            decimal elevLabel     = Convert.ToDecimal(intersectDist[i].Item2);
                            DrawText(new Point2d(intersectDist[i].Item1 + GlobalVars.insertionPt.X, GlobalVars.insertionPt.Y), GlobalVars.textHeight, 1.5708, elevLabel.ToString("#.##"), "PROFILEVIEWER.LABELS", 10);
                            if (i == intersectDist.Count - 1)
                            {
                                using (DocumentLock docLock = doc.LockDocument())
                                {
                                    CreateLayer("PROFILEVIEWER.PROFILE", 255);
                                    profile.Layer = "PROFILEVIEWER.PROFILE";
                                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                                    btr.AppendEntity(profile);
                                    tr.AddNewlyCreatedDBObject(profile, true);
                                }
                            }
                        }

                        double datumY = profileLength;
                        //Datum line
                        Polyline guides = new Polyline();
                        guides.AddVertexAt(0, new Point2d(GlobalVars.insertionPt.X, GlobalVars.insertionPt.Y + profileStartY), 0, 0, 0);
                        guides.AddVertexAt(1, new Point2d(GlobalVars.insertionPt.X, GlobalVars.insertionPt.Y), 0, 0, 0);
                        DrawText(new Point2d(GlobalVars.insertionPt.X, GlobalVars.insertionPt.Y), GlobalVars.textHeight * 2, 0, "A", "PROFILEVIEWER.DATUMLINE");
                        guides.AddVertexAt(2, new Point2d(GlobalVars.insertionPt.X + profileLength, GlobalVars.insertionPt.Y), 0, 0, 0);
                        DrawText(new Point2d(GlobalVars.insertionPt.X + profileLength, GlobalVars.insertionPt.Y), GlobalVars.textHeight * 2, 0, "A'", "PROFILEVIEWER.DATUMLINE");
                        guides.AddVertexAt(3, new Point2d(GlobalVars.insertionPt.X + profileLength, GlobalVars.insertionPt.Y + profileEndY), 0, 0, 0);
                        CreateLayer("PROFILEVIEWER.DATUMLINE", 251);
                        guides.Layer = "PROFILEVIEWER.DATUMLINE";

                        using (DocumentLock docLock = doc.LockDocument())
                        {
                            BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                            btr.AppendEntity(guides);
                            tr.AddNewlyCreatedDBObject(guides, true);
                        }
                    }
                    tr.Commit();
                    ed.WriteMessage("Successfully created profile.");
                }
                else
                {
                    ed.WriteMessage("No Polyline in selected layer");
                }
            }
        }
        private async Task DoWork(CancellationToken cancellationToken)
        {
            using var scope = _services.CreateScope();
            var context = scope.ServiceProvider.GetRequiredService <BankDbContext>();

            // Get all the data of the transfer date earlier than the next day
            List <BillPay> list = await context.BillPay.Where(a => a.ScheduleDate <= DateTime.Now && a.Status == BillPayStatus.Available).Include(a => a.Account).Include(a => a.Payee).ToListAsync(cancellationToken);

            var datenow = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));

            if (list.Count <= 0)
            {
                return;
            }
            foreach (var item in list)
            {
                if (item.Account.Balance > item.Amount)
                {
                    if (item.Period == Period.OnceOff)
                    {
                        if (datenow == item.ScheduleDate)
                        {
                            var count = context.Transaction.Where(x => x.AccountNumber == item.AccountNumber && x.TransactionType == TransactionType.BillPay && x.Amount == item.Amount && x.ModifyDate == datenow).Count();
                            if (count > 0)
                            {
                                //pay over
                            }
                            else
                            {
                                Transaction transaction = new Transaction()
                                {
                                    TransactionType   = TransactionType.BillPay,
                                    AccountNumber     = item.AccountNumber,
                                    Amount            = item.Amount,
                                    Comment           = "Bill pay",
                                    ModifyDate        = datenow,
                                    TransactionStatus = TransactionStatus.Idle
                                };
                                context.Transaction.Add(transaction);
                                await context.SaveChangesAsync();

                                item.Account.Balance = item.Account.Balance - item.Amount;
                                context.Account.Update(item.Account);
                                item.Status = BillPayStatus.Done;
                                context.BillPay.Update(item);
                                await context.SaveChangesAsync();
                            }
                        }
                    }
                    else if (item.Period == Period.Monthly)
                    {
                        var date = item.ScheduleDate;
                        while (true)
                        {
                            date = date.AddMonths(1);
                            if (date >= datenow)
                            {
                                break;
                            }
                        }
                        if (date == datenow)
                        {
                            var count = context.Transaction.Where(x => x.AccountNumber == item.AccountNumber && x.TransactionType == TransactionType.BillPay && x.Amount == item.Amount && x.ModifyDate == datenow).Count();
                            if (count > 0)
                            {
                                //pay over
                            }
                            else
                            {
                                Transaction transaction = new Transaction()
                                {
                                    TransactionType   = TransactionType.BillPay,
                                    AccountNumber     = item.AccountNumber,
                                    Amount            = item.Amount,
                                    Comment           = "Bill pay",
                                    ModifyDate        = datenow,
                                    TransactionStatus = TransactionStatus.Idle
                                };
                                context.Transaction.Add(transaction);
                                await context.SaveChangesAsync();

                                item.Account.Balance = item.Account.Balance - item.Amount;
                                context.Account.Update(item.Account);
                                await context.SaveChangesAsync();
                            }
                        }
                    }
                    else
                    {
                        var date = item.ScheduleDate;
                        while (true)
                        {
                            date = date.AddMonths(3);
                            if (date >= datenow)
                            {
                                break;
                            }
                        }
                        if (date == datenow)
                        {
                            var count = context.Transaction.Where(x => x.AccountNumber == item.AccountNumber && x.TransactionType == TransactionType.BillPay && x.Amount == item.Amount && x.ModifyDate == datenow).Count();
                            if (count > 0)
                            {
                                //pay over
                            }
                            else
                            {
                                Transaction transaction = new Transaction()
                                {
                                    TransactionType   = TransactionType.BillPay,
                                    AccountNumber     = item.AccountNumber,
                                    Amount            = item.Amount,
                                    Comment           = "Bill pay",
                                    ModifyDate        = datenow,
                                    TransactionStatus = TransactionStatus.Idle
                                };
                                context.Transaction.Add(transaction);
                                await context.SaveChangesAsync();

                                item.Account.Balance = item.Account.Balance - item.Amount;
                                context.Account.Update(item.Account);
                                await context.SaveChangesAsync();
                            }
                        }
                    }
                }
                else
                {
                    var count = context.Transaction.Where(x => x.AccountNumber == item.AccountNumber && x.TransactionType == TransactionType.BillPay && x.Amount == item.Amount && x.ModifyDate == datenow).Count();
                    if (count > 0)
                    {
                        //pay over
                    }
                    else
                    {
                    }
                }
            }

            await context.SaveChangesAsync();
        }
 private void TransactionOutcomeEnlist(Transaction transaction)
 {
     transaction.TransactionCompleted += new TransactionCompletedEventHandler(TransactionCompletedEvent);
 }
        public GetSenderResult GetSender(Transaction tx, MempoolCoinView coinView)
        {
            TxOut output = coinView.GetOutputFor(tx.Inputs[0]);

            return(GetAddressFromScript(output.ScriptPubKey));
        }
 abstract public void EnlistTransaction(Transaction transaction);
Beispiel #48
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            var doc = commandData.Application.ActiveUIDocument.Document;

            const string materialName = "Concrete";

            FilteredElementCollector collector =
                new FilteredElementCollector(doc);

            var sw            = Stopwatch.StartNew();
            var materialsLinq =
                doc
                .Settings
                .Materials
                .OfType <Material>()
                .ToList();

            sw.Stop();
            Debug.Print("LINQ: Elapsed time: {0}\tMaterials count: {1}", sw.Elapsed, materialsLinq.Count);

            sw = Stopwatch.StartNew();
            var materials = collector
                            .OfClass(typeof(Material))
                            .OfType <Material>()
                            .ToList();

            sw.Stop();
            Debug.Print("FilteredElementCollector: Elapsed time: {0}\tMaterials count: {1}", sw.Elapsed, materials.Count);

            Debug.Print("Document.Settings.Materials count: {0}", doc.Settings.Materials.Size);

            #region using extension methods

            var materialsInDocument = doc.GetMaterials();

            var concreteMaterial = doc.Settings.Materials
                                   .GetMaterialByName(materialName);

            #endregion

            var materialsRetrievingViaCollectorButNotInDocumentSettings =
                materials
                .Except(materialsLinq, new MaterialComparer())
                .ToList();

            // ******
            // Materials.get_Item required transaction
            // Why? I'm just read data
            // ******
            var tx = new Transaction(doc, "Get Material");
            tx.Start();

            // ******
            // NullReferencException throws here if
            // Materials collection contains null
            // ******
            var material = doc.Settings.Materials.get_Item(materialName);

            tx.RollBack();

            return(Result.Succeeded);
        }
        public Block[] GenerateStratis(int blockCount, List <Transaction> passedTransactions = null, bool broadcast = true)
        {
            var            fullNode = (this._Runner as StratisBitcoinPowRunner).FullNode;
            BitcoinSecret  dest     = this.MinerSecret;
            List <Block>   blocks   = new List <Block>();
            DateTimeOffset now      = this.MockTime == null ? DateTimeOffset.UtcNow : this.MockTime.Value;

#if !NOSOCKET
            for (int i = 0; i < blockCount; i++)
            {
                uint  nonce = 0;
                Block block = new Block();
                block.Header.HashPrevBlock = fullNode.Chain.Tip.HashBlock;
                block.Header.Bits          = block.Header.GetWorkRequired(fullNode.Network, fullNode.Chain.Tip);
                block.Header.UpdateTime(now, fullNode.Network, fullNode.Chain.Tip);
                var coinbase = new Transaction();
                coinbase.AddInput(TxIn.CreateCoinbase(fullNode.Chain.Height + 1));
                coinbase.AddOutput(new TxOut(fullNode.Network.GetReward(fullNode.Chain.Height + 1), dest.GetAddress()));
                block.AddTransaction(coinbase);
                if (passedTransactions?.Any() ?? false)
                {
                    passedTransactions = Reorder(passedTransactions);
                    block.Transactions.AddRange(passedTransactions);
                }
                block.UpdateMerkleRoot();
                while (!block.CheckProofOfWork())
                {
                    block.Header.Nonce = ++nonce;
                }
                blocks.Add(block);
                if (broadcast)
                {
                    uint256 blockHash = block.GetHash();
                    var     newChain  = new ChainedBlock(block.Header, blockHash, fullNode.Chain.Tip);
                    var     oldTip    = fullNode.Chain.SetTip(newChain);
                    fullNode.ConsensusLoop().Puller.InjectBlock(blockHash, new DownloadedBlock {
                        Length = block.GetSerializedSize(), Block = block
                    }, CancellationToken.None);

                    //try
                    //{


                    //	var blockResult = new BlockResult { Block = block };
                    //	fullNode.ConsensusLoop.AcceptBlock(blockResult);


                    //	// similar logic to what's in the full node code
                    //	if (blockResult.Error == null)
                    //	{
                    //		fullNode.ChainBehaviorState.HighestValidatedPoW = fullNode.ConsensusLoop.Tip;
                    //		//if (fullNode.Chain.Tip.HashBlock == blockResult.ChainedBlock.HashBlock)
                    //		//{
                    //		//	var unused = cache.FlushAsync();
                    //		//}
                    //		fullNode.Signals.Blocks.Broadcast(block);
                    //	}
                    //}
                    //catch (ConsensusErrorException)
                    //{
                    //	// set back the old tip
                    //	fullNode.Chain.SetTip(oldTip);
                    //}
                }
            }

            return(blocks.ToArray());
#endif
        }
 // Cleanup connection's transaction-specific structures (currently used by Delegated transaction).
 //  This is a separate method because cleanup can be triggered in multiple ways for a delegated
 //  transaction.
 virtual protected void CleanupTransactionOnCompletion(Transaction transaction)
 {
 }
 public TransactionNode(Transaction tx)
 {
     this.Transaction = tx;
     this.Hash        = tx.GetHash();
 }
 abstract protected void Activate(Transaction transaction);
Beispiel #53
0
 public override TransactionGridCellViewModel CreateCell(TransactionGridRowViewModel row, Transaction transaction, SubTransactionRowViewModel subTransactionRow, SubTransaction subTransaction)
 {
     return(new DecimalCellViewModel(this, row, transaction, subTransactionRow, subTransaction));
 }
        public void Broadcast(Transaction transaction)
        {
            var rpc = CreateRPCClient();

            rpc.SendRawTransaction(transaction);
        }
 public Task<TransactionResult> ExecuteWithExceptionAsync(Transaction transaction)
 {
     throw new NotImplementedException();
 }
Beispiel #56
0
        public async Task <IActionResult> Submit(string cryptoCode,
                                                 long?maxadditionalfeecontribution,
                                                 int?additionalfeeoutputindex,
                                                 decimal minfeerate             = -1.0m,
                                                 bool disableoutputsubstitution = false,
                                                 int v = 1)
        {
            var network = _btcPayNetworkProvider.GetNetwork <BTCPayNetwork>(cryptoCode);

            if (network == null)
            {
                return(NotFound());
            }

            if (v != 1)
            {
                return(BadRequest(new JObject
                {
                    new JProperty("errorCode", "version-unsupported"),
                    new JProperty("supported", new JArray(1)),
                    new JProperty("message", "This version of payjoin is not supported.")
                }));
            }

            await using var ctx = new PayjoinReceiverContext(_invoiceRepository, _explorerClientProvider.GetExplorerClient(network), _payJoinRepository);
            ObjectResult CreatePayjoinErrorAndLog(int httpCode, PayjoinReceiverWellknownErrors err, string debug)
            {
                ctx.Logs.Write($"Payjoin error: {debug}", InvoiceEventData.EventSeverity.Error);
                return(StatusCode(httpCode, CreatePayjoinError(err, debug)));
            }

            var explorer = _explorerClientProvider.GetExplorerClient(network);

            if (Request.ContentLength is long length)
            {
                if (length > 1_000_000)
                {
                    return(this.StatusCode(413,
                                           CreatePayjoinError("payload-too-large", "The transaction is too big to be processed")));
                }
            }
            else
            {
                return(StatusCode(411,
                                  CreatePayjoinError("missing-content-length",
                                                     "The http header Content-Length should be filled")));
            }

            string rawBody;

            using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
            {
                rawBody = (await reader.ReadToEndAsync()) ?? string.Empty;
            }

            FeeRate originalFeeRate = null;
            bool    psbtFormat      = true;

            if (PSBT.TryParse(rawBody, network.NBitcoinNetwork, out var psbt))
            {
                if (!psbt.IsAllFinalized())
                {
                    return(BadRequest(CreatePayjoinError("original-psbt-rejected", "The PSBT should be finalized")));
                }
                ctx.OriginalTransaction = psbt.ExtractTransaction();
            }
            // BTCPay Server implementation support a transaction instead of PSBT
            else
            {
                psbtFormat = false;
                if (!Transaction.TryParse(rawBody, network.NBitcoinNetwork, out var tx))
                {
                    return(BadRequest(CreatePayjoinError("original-psbt-rejected", "invalid transaction or psbt")));
                }
                ctx.OriginalTransaction = tx;
                psbt = PSBT.FromTransaction(tx, network.NBitcoinNetwork);
                psbt = (await explorer.UpdatePSBTAsync(new UpdatePSBTRequest()
                {
                    PSBT = psbt
                })).PSBT;
                for (int i = 0; i < tx.Inputs.Count; i++)
                {
                    psbt.Inputs[i].FinalScriptSig     = tx.Inputs[i].ScriptSig;
                    psbt.Inputs[i].FinalScriptWitness = tx.Inputs[i].WitScript;
                }
            }

            FeeRate senderMinFeeRate             = minfeerate >= 0.0m ? new FeeRate(minfeerate) : null;
            Money   allowedSenderFeeContribution = Money.Satoshis(maxadditionalfeecontribution is long t && t >= 0 ? t : 0);

            var sendersInputType = psbt.GetInputsScriptPubKeyType();

            if (psbt.CheckSanity() is var errors && errors.Count != 0)
            {
                return(BadRequest(CreatePayjoinError("original-psbt-rejected", $"This PSBT is insane ({errors[0]})")));
            }
            if (!psbt.TryGetEstimatedFeeRate(out originalFeeRate))
            {
                return(BadRequest(CreatePayjoinError("original-psbt-rejected",
                                                     "You need to provide Witness UTXO information to the PSBT.")));
            }

            // This is actually not a mandatory check, but we don't want implementers
            // to leak global xpubs
            if (psbt.GlobalXPubs.Any())
            {
                return(BadRequest(CreatePayjoinError("original-psbt-rejected",
                                                     "GlobalXPubs should not be included in the PSBT")));
            }

            if (psbt.Outputs.Any(o => o.HDKeyPaths.Count != 0) || psbt.Inputs.Any(o => o.HDKeyPaths.Count != 0))
            {
                return(BadRequest(CreatePayjoinError("original-psbt-rejected",
                                                     "Keypath information should not be included in the PSBT")));
            }

            if (psbt.Inputs.Any(o => !o.IsFinalized()))
            {
                return(BadRequest(CreatePayjoinError("original-psbt-rejected", "The PSBT Should be finalized")));
            }
            ////////////

            var mempool = await explorer.BroadcastAsync(ctx.OriginalTransaction, true);

            if (!mempool.Success)
            {
                ctx.DoNotBroadcast();
                return(BadRequest(CreatePayjoinError("original-psbt-rejected",
                                                     $"Provided transaction isn't mempool eligible {mempool.RPCCodeMessage}")));
            }
            var   enforcedLowR    = ctx.OriginalTransaction.Inputs.All(IsLowR);
            var   paymentMethodId = new PaymentMethodId(network.CryptoCode, PaymentTypes.BTCLike);
            bool  paidSomething   = false;
            Money due             = null;
            Dictionary <OutPoint, UTXO> selectedUTXOs      = new Dictionary <OutPoint, UTXO>();
            PSBTOutput               originalPaymentOutput = null;
            BitcoinAddress           paymentAddress        = null;
            KeyPath                  paymentAddressIndex   = null;
            InvoiceEntity            invoice = null;
            DerivationSchemeSettings derivationSchemeSettings = null;
            WalletId                 walletId = null;

            foreach (var output in psbt.Outputs)
            {
                var walletReceiveMatch =
                    _walletReceiveService.GetByScriptPubKey(network.CryptoCode, output.ScriptPubKey);
                if (walletReceiveMatch is null)
                {
                    var key = output.ScriptPubKey.Hash + "#" + network.CryptoCode.ToUpperInvariant();
                    invoice = (await _invoiceRepository.GetInvoicesFromAddresses(new[] { key })).FirstOrDefault();
                    if (invoice is null)
                    {
                        continue;
                    }
                    derivationSchemeSettings = invoice
                                               .GetSupportedPaymentMethod <DerivationSchemeSettings>(paymentMethodId)
                                               .SingleOrDefault();
                    walletId = new WalletId(invoice.StoreId, network.CryptoCode.ToUpperInvariant());
                }
                else
                {
                    var store = await _storeRepository.FindStore(walletReceiveMatch.Item1.StoreId);

                    derivationSchemeSettings = store.GetDerivationSchemeSettings(_btcPayNetworkProvider,
                                                                                 walletReceiveMatch.Item1.CryptoCode);

                    walletId = walletReceiveMatch.Item1;
                }

                if (derivationSchemeSettings is null)
                {
                    continue;
                }
                var receiverInputsType = derivationSchemeSettings.AccountDerivation.ScriptPubKeyType();
                if (receiverInputsType == ScriptPubKeyType.Legacy)
                {
                    //this should never happen, unless the store owner changed the wallet mid way through an invoice
                    return(CreatePayjoinErrorAndLog(503, PayjoinReceiverWellknownErrors.Unavailable, "Our wallet does not support payjoin"));
                }
                if (sendersInputType is ScriptPubKeyType t1 && t1 != receiverInputsType)
                {
                    return(CreatePayjoinErrorAndLog(503, PayjoinReceiverWellknownErrors.Unavailable, "We do not have any UTXO available for making a payjoin with the sender's inputs type"));
                }

                if (walletReceiveMatch is null)
                {
                    var paymentMethod  = invoice.GetPaymentMethod(paymentMethodId);
                    var paymentDetails =
                        paymentMethod.GetPaymentMethodDetails() as Payments.Bitcoin.BitcoinLikeOnChainPaymentMethod;
                    if (paymentDetails is null || !paymentDetails.PayjoinEnabled)
                    {
                        continue;
                    }
                    paidSomething = true;
                    due           = paymentMethod.Calculate().TotalDue - output.Value;
                    if (due > Money.Zero)
                    {
                        break;
                    }

                    paymentAddress      = paymentDetails.GetDepositAddress(network.NBitcoinNetwork);
                    paymentAddressIndex = paymentDetails.KeyPath;

                    if (invoice.GetAllBitcoinPaymentData(false).Any())
                    {
                        ctx.DoNotBroadcast();
                        return(UnprocessableEntity(CreatePayjoinError("already-paid",
                                                                      $"The invoice this PSBT is paying has already been partially or completely paid")));
                    }
                }
                else
                {
                    paidSomething       = true;
                    due                 = Money.Zero;
                    paymentAddress      = walletReceiveMatch.Item2.Address;
                    paymentAddressIndex = walletReceiveMatch.Item2.KeyPath;
                }


                if (!await _payJoinRepository.TryLockInputs(ctx.OriginalTransaction.Inputs.Select(i => i.PrevOut).ToArray()))
                {
                    // We do not broadcast, since we might double spend a delayed transaction of a previous payjoin
                    ctx.DoNotBroadcast();
                    return(CreatePayjoinErrorAndLog(503, PayjoinReceiverWellknownErrors.Unavailable, "Some of those inputs have already been used to make another payjoin transaction"));
                }

                var utxos = (await explorer.GetUTXOsAsync(derivationSchemeSettings.AccountDerivation))
                            .GetUnspentUTXOs(false);
                // In case we are paying ourselves, be need to make sure
                // we can't take spent outpoints.
                var prevOuts = ctx.OriginalTransaction.Inputs.Select(o => o.PrevOut).ToHashSet();
                utxos = utxos.Where(u => !prevOuts.Contains(u.Outpoint)).ToArray();
                Array.Sort(utxos, UTXODeterministicComparer.Instance);
                foreach (var utxo in (await SelectUTXO(network, utxos, psbt.Inputs.Select(input => input.WitnessUtxo.Value.ToDecimal(MoneyUnit.BTC)), output.Value.ToDecimal(MoneyUnit.BTC),
                                                       psbt.Outputs.Where(psbtOutput => psbtOutput.Index != output.Index).Select(psbtOutput => psbtOutput.Value.ToDecimal(MoneyUnit.BTC)))).selectedUTXO)
                {
                    selectedUTXOs.Add(utxo.Outpoint, utxo);
                }
                ctx.LockedUTXOs       = selectedUTXOs.Select(u => u.Key).ToArray();
                originalPaymentOutput = output;
                break;
            }

            if (!paidSomething)
            {
                return(BadRequest(CreatePayjoinError("invoice-not-found",
                                                     "This transaction does not pay any invoice with payjoin")));
            }

            if (due is null || due > Money.Zero)
            {
                return(BadRequest(CreatePayjoinError("invoice-not-fully-paid",
                                                     "The transaction must pay the whole invoice")));
            }

            if (selectedUTXOs.Count == 0)
            {
                return(CreatePayjoinErrorAndLog(503, PayjoinReceiverWellknownErrors.Unavailable, "We do not have any UTXO available for contributing to a payjoin"));
            }

            var originalPaymentValue = originalPaymentOutput.Value;
            await _broadcaster.Schedule(DateTimeOffset.UtcNow + TimeSpan.FromMinutes(2.0), ctx.OriginalTransaction, network);

            //check if wallet of store is configured to be hot wallet
            var extKeyStr = await explorer.GetMetadataAsync <string>(
                derivationSchemeSettings.AccountDerivation,
                WellknownMetadataKeys.AccountHDKey);

            if (extKeyStr == null)
            {
                // This should not happen, as we check the existance of private key before creating invoice with payjoin
                return(CreatePayjoinErrorAndLog(503, PayjoinReceiverWellknownErrors.Unavailable, "The HD Key of the store changed"));
            }

            Money           contributedAmount = Money.Zero;
            var             newTx             = ctx.OriginalTransaction.Clone();
            var             ourNewOutput      = newTx.Outputs[originalPaymentOutput.Index];
            HashSet <TxOut> isOurOutput       = new HashSet <TxOut>();

            isOurOutput.Add(ourNewOutput);
            TxOut feeOutput =
                additionalfeeoutputindex is int feeOutputIndex &&
                maxadditionalfeecontribution is long v3 &&
                v3 >= 0 &&
                feeOutputIndex >= 0 &&
                feeOutputIndex < newTx.Outputs.Count &&
                !isOurOutput.Contains(newTx.Outputs[feeOutputIndex])
                ? newTx.Outputs[feeOutputIndex] : null;
            int senderInputCount = newTx.Inputs.Count;

            foreach (var selectedUTXO in selectedUTXOs.Select(o => o.Value))
            {
                contributedAmount += (Money)selectedUTXO.Value;
                var newInput = newTx.Inputs.Add(selectedUTXO.Outpoint);
                newInput.Sequence = newTx.Inputs[(int)(RandomUtils.GetUInt32() % senderInputCount)].Sequence;
            }
            ourNewOutput.Value += contributedAmount;
            var minRelayTxFee = this._dashboard.Get(network.CryptoCode).Status.BitcoinStatus?.MinRelayTxFee ??
                                new FeeRate(1.0m);

            // Remove old signatures as they are not valid anymore
            foreach (var input in newTx.Inputs)
            {
                input.WitScript = WitScript.Empty;
            }

            Money ourFeeContribution = Money.Zero;
            // We need to adjust the fee to keep a constant fee rate
            var txBuilder = network.NBitcoinNetwork.CreateTransactionBuilder();
            var coins     = psbt.Inputs.Select(i => i.GetSignableCoin())
                            .Concat(selectedUTXOs.Select(o => o.Value.AsCoin(derivationSchemeSettings.AccountDerivation))).ToArray();

            txBuilder.AddCoins(coins);
            Money expectedFee   = txBuilder.EstimateFees(newTx, originalFeeRate);
            Money actualFee     = newTx.GetFee(txBuilder.FindSpentCoins(newTx));
            Money additionalFee = expectedFee - actualFee;

            if (additionalFee > Money.Zero)
            {
                // If the user overpaid, taking fee on our output (useful if sender dump a full UTXO for privacy)
                for (int i = 0; i < newTx.Outputs.Count && additionalFee > Money.Zero && due < Money.Zero && !invoice.IsUnsetTopUp(); i++)
                {
                    if (disableoutputsubstitution)
                    {
                        break;
                    }
                    if (isOurOutput.Contains(newTx.Outputs[i]))
                    {
                        var outputContribution = Money.Min(additionalFee, -due);
                        outputContribution = Money.Min(outputContribution,
                                                       newTx.Outputs[i].Value - newTx.Outputs[i].GetDustThreshold(minRelayTxFee));
                        newTx.Outputs[i].Value -= outputContribution;
                        additionalFee          -= outputContribution;
                        due += outputContribution;
                        ourFeeContribution += outputContribution;
                    }
                }

                // The rest, we take from user's change
                if (feeOutput != null)
                {
                    var outputContribution = Money.Min(additionalFee, feeOutput.Value);
                    outputContribution = Money.Min(outputContribution,
                                                   feeOutput.Value - feeOutput.GetDustThreshold(minRelayTxFee));
                    outputContribution            = Money.Min(outputContribution, allowedSenderFeeContribution);
                    feeOutput.Value              -= outputContribution;
                    additionalFee                -= outputContribution;
                    allowedSenderFeeContribution -= outputContribution;
                }

                if (additionalFee > Money.Zero)
                {
                    // We could not pay fully the additional fee, however, as long as
                    // we are not under the relay fee, it should be OK.
                    var newVSize   = txBuilder.EstimateSize(newTx, true);
                    var newFeePaid = newTx.GetFee(txBuilder.FindSpentCoins(newTx));
                    if (new FeeRate(newFeePaid, newVSize) < (senderMinFeeRate ?? minRelayTxFee))
                    {
                        return(CreatePayjoinErrorAndLog(422, PayjoinReceiverWellknownErrors.NotEnoughMoney, "Not enough money is sent to pay for the additional payjoin inputs"));
                    }
                }
            }

            var accountKey = ExtKey.Parse(extKeyStr, network.NBitcoinNetwork);
            var newPsbt    = PSBT.FromTransaction(newTx, network.NBitcoinNetwork);

            foreach (var selectedUtxo in selectedUTXOs.Select(o => o.Value))
            {
                var signedInput = newPsbt.Inputs.FindIndexedInput(selectedUtxo.Outpoint);
                var coin        = selectedUtxo.AsCoin(derivationSchemeSettings.AccountDerivation);
                signedInput.UpdateFromCoin(coin);
                var privateKey = accountKey.Derive(selectedUtxo.KeyPath).PrivateKey;
                signedInput.PSBT.Settings.SigningOptions = new SigningOptions()
                {
                    EnforceLowR = enforcedLowR
                };
                signedInput.Sign(privateKey);
                signedInput.FinalizeInput();
                newTx.Inputs[signedInput.Index].WitScript = newPsbt.Inputs[(int)signedInput.Index].FinalScriptWitness;
            }

            // Add the transaction to the payments with a confirmation of -1.
            // This will make the invoice paid even if the user do not
            // broadcast the payjoin.
            var originalPaymentData = new BitcoinLikePaymentData(paymentAddress,
                                                                 originalPaymentOutput.Value,
                                                                 new OutPoint(ctx.OriginalTransaction.GetHash(), originalPaymentOutput.Index),
                                                                 ctx.OriginalTransaction.RBF, paymentAddressIndex);

            originalPaymentData.ConfirmationCount  = -1;
            originalPaymentData.PayjoinInformation = new PayjoinInformation()
            {
                CoinjoinTransactionHash = GetExpectedHash(newPsbt, coins),
                CoinjoinValue           = originalPaymentValue - ourFeeContribution,
                ContributedOutPoints    = selectedUTXOs.Select(o => o.Key).ToArray()
            };
            if (invoice != null)
            {
                var payment = await _paymentService.AddPayment(invoice.Id, DateTimeOffset.UtcNow, originalPaymentData, network, true);

                if (payment is null)
                {
                    return(UnprocessableEntity(CreatePayjoinError("already-paid",
                                                                  $"The original transaction has already been accounted")));
                }
                _eventAggregator.Publish(new InvoiceEvent(invoice, InvoiceEvent.ReceivedPayment)
                {
                    Payment = payment
                });
            }


            await _btcPayWalletProvider.GetWallet(network).SaveOffchainTransactionAsync(ctx.OriginalTransaction);

            _eventAggregator.Publish(new UpdateTransactionLabel()
            {
                WalletId          = walletId,
                TransactionLabels = selectedUTXOs.GroupBy(pair => pair.Key.Hash).Select(utxo =>
                                                                                        new KeyValuePair <uint256, List <(string color, Label label)> >(utxo.Key,
                                                                                                                                                        new List <(string color, Label label)>()
                {
                    UpdateTransactionLabel.PayjoinExposedLabelTemplate(invoice?.Id)
                }))
                                    .ToDictionary(pair => pair.Key, pair => pair.Value)
            });
Beispiel #57
0
        public Transaction NewTransaction(TransactionFlags flags, TimeSpan?timeout = null)
        {
            bool txLockTaken = false;

            try
            {
                if (flags == (TransactionFlags.ReadWrite))
                {
                    var wait = timeout ?? (Debugger.IsAttached ? TimeSpan.FromMinutes(30) : TimeSpan.FromSeconds(30));
                    Monitor.TryEnter(_txWriter, wait, ref txLockTaken);
                    if (txLockTaken == false)
                    {
                        throw new TimeoutException("Waited for " + wait +
                                                   " for transaction write lock, but could not get it");
                    }

                    if (_endOfDiskSpace != null)
                    {
                        if (_endOfDiskSpace.CanContinueWriting)
                        {
                            var flushingTask = _flushingTask;
                            Debug.Assert(flushingTask != null && (flushingTask.Status == TaskStatus.Canceled || flushingTask.Status == TaskStatus.RanToCompletion));
                            _cancellationTokenSource = new CancellationTokenSource();
                            _flushingTask            = FlushWritesToDataFileAsync();
                            _endOfDiskSpace          = null;
                        }
                    }
                }

                Transaction tx;

                _txCommit.EnterReadLock();
                try
                {
                    long txId = flags == TransactionFlags.ReadWrite ? NextWriteTransactionId : CurrentReadTransactionId;
                    tx = new Transaction(this, txId, flags, _freeSpaceHandling);

                    if (IsDebugRecording)
                    {
                        RecordTransactionState(tx, DebugActionType.TransactionStart);
                        tx.RecordTransactionState = RecordTransactionState;
                    }

                    _activeTransactions.Add(tx);
                }
                finally
                {
                    _txCommit.ExitReadLock();
                }

                tx.EnsurePagerStateReference(_dataPager.PagerState);

                if (flags == TransactionFlags.ReadWrite)
                {
                    tx.AfterCommit = TransactionAfterCommit;
                }

                return(tx);
            }
            catch (Exception)
            {
                if (txLockTaken)
                {
                    Monitor.Exit(_txWriter);
                }
                throw;
            }
        }
 public Task<StringValue> ReadWithExceptionAsync(Transaction transaction)
 {
     throw new NotImplementedException();
 }
        /// <inheritdoc />
        public override async Task RunAsync(RuleContext context)
        {
            this.Logger.LogTrace("()");

            Block            block = context.ValidationContext.Block;
            ChainedHeader    index = context.ValidationContext.ChainedHeader;
            DeploymentFlags  flags = context.Flags;
            UnspentOutputSet view  = (context as UtxoRuleContext).UnspentOutputSet;

            this.Parent.PerformanceCounter.AddProcessedBlocks(1);

            long  sigOpsCost  = 0;
            Money fees        = Money.Zero;
            var   checkInputs = new List <Task <bool> >();

            for (int txIndex = 0; txIndex < block.Transactions.Count; txIndex++)
            {
                this.Parent.PerformanceCounter.AddProcessedTransactions(1);
                Transaction tx = block.Transactions[txIndex];
                if (!context.SkipValidation)
                {
                    if (!this.IsProtocolTransaction(tx))
                    {
                        if (!view.HaveInputs(tx))
                        {
                            this.Logger.LogTrace("(-)[BAD_TX_NO_INPUT]");
                            ConsensusErrors.BadTransactionMissingInput.Throw();
                        }

                        var prevheights = new int[tx.Inputs.Count];
                        // Check that transaction is BIP68 final.
                        // BIP68 lock checks (as opposed to nLockTime checks) must
                        // be in ConnectBlock because they require the UTXO set.
                        for (int j = 0; j < tx.Inputs.Count; j++)
                        {
                            prevheights[j] = (int)view.AccessCoins(tx.Inputs[j].PrevOut.Hash).Height;
                        }

                        if (!tx.CheckSequenceLocks(prevheights, index, flags.LockTimeFlags))
                        {
                            this.Logger.LogTrace("(-)[BAD_TX_NON_FINAL]");
                            ConsensusErrors.BadTransactionNonFinal.Throw();
                        }
                    }

                    // GetTransactionSignatureOperationCost counts 3 types of sigops:
                    // * legacy (always),
                    // * p2sh (when P2SH enabled in flags and excludes coinbase),
                    // * witness (when witness enabled in flags and excludes coinbase).
                    sigOpsCost += this.GetTransactionSignatureOperationCost(tx, view, flags);
                    if (sigOpsCost > this.ConsensusOptions.MaxBlockSigopsCost)
                    {
                        this.Logger.LogTrace("(-)[BAD_BLOCK_SIG_OPS]");
                        ConsensusErrors.BadBlockSigOps.Throw();
                    }

                    if (!this.IsProtocolTransaction(tx))
                    {
                        this.CheckInputs(tx, view, index.Height);
                        fees += view.GetValueIn(tx) - tx.TotalOut;
                        var txData = new PrecomputedTransactionData(tx);
                        for (int inputIndex = 0; inputIndex < tx.Inputs.Count; inputIndex++)
                        {
                            this.Parent.PerformanceCounter.AddProcessedInputs(1);
                            TxIn  input          = tx.Inputs[inputIndex];
                            int   inputIndexCopy = inputIndex;
                            TxOut txout          = view.GetOutputFor(input);
                            var   checkInput     = new Task <bool>(() =>
                            {
                                var checker             = new TransactionChecker(tx, inputIndexCopy, txout.Value, txData);
                                var ctx                 = new ScriptEvaluationContext(this.Parent.Network);
                                ctx.ScriptVerify        = flags.ScriptFlags;
                                bool verifyScriptResult = ctx.VerifyScript(input.ScriptSig, txout.ScriptPubKey, checker);

                                if (verifyScriptResult == false)
                                {
                                    this.Logger.LogTrace("Verify script for transaction '{0}' failed, ScriptSig = '{1}', ScriptPubKey = '{2}', script evaluation error = '{3}'", tx.GetHash(), input.ScriptSig, txout.ScriptPubKey, ctx.Error);
                                }

                                return(verifyScriptResult);
                            });
                            checkInput.Start();
                            checkInputs.Add(checkInput);
                        }
                    }
                }

                this.UpdateCoinView(context, tx);
            }

            if (!context.SkipValidation)
            {
                this.CheckBlockReward(context, fees, index.Height, block);

                foreach (Task <bool> checkInput in checkInputs)
                {
                    if (await checkInput.ConfigureAwait(false))
                    {
                        continue;
                    }

                    this.Logger.LogTrace("(-)[BAD_TX_SCRIPT]");
                    ConsensusErrors.BadTransactionScriptError.Throw();
                }
            }
            else
            {
                this.Logger.LogTrace("BIP68, SigOp cost, and block reward validation skipped for block at height {0}.", index.Height);
            }

            this.Logger.LogTrace("(-)");
        }
Beispiel #60
0
 private void RecordTransactionState(Transaction tx, DebugActionType state)
 {
     DebugJournal.RecordTransactionAction(tx, state);
 }