コード例 #1
0
        public bool ValidateSignatures(string expectedAddress, string[] signatureFragments, string bundleHash)
        {
            //Bundle bundle = new Bundle();

            var normalizedBundleFragments = new int[3, 27];

            int[] normalizedBundleHash = TransactionExtensions.NormalizedBundle(bundleHash); //bundle.NormalizedBundle(bundleHash);

            // Split hash into 3 fragments
            for (int i = 0; i < 3; i++)
            {
                // normalizedBundleFragments[i] = Arrays.copyOfRange(normalizedBundleHash, i*27, (i + 1)*27);
                Array.Copy(normalizedBundleHash, i * 27, normalizedBundleFragments, 0, 27);
            }

            // Get digests
            int[] digests = new int[signatureFragments.Length * 243];

            for (int i = 0; i < signatureFragments.Length; i++)
            {
                int[] digestBuffer = Digest(ArrayUtils.SliceRow(normalizedBundleFragments, i % 3).ToArray(),
                                            Converter.ToTrits(signatureFragments[i]));

                for (int j = 0; j < 243; j++)
                {
                    Array.Copy(digestBuffer, j, digests, i * 243 + j, 1);
                }
            }
            string address = Converter.ToTrytes(Address(digests));

            return(expectedAddress.Equals(address));
        }
コード例 #2
0
ファイル: Signing.cs プロジェクト: Borlay/Borlay.Iota.Library
        public bool ValidateSignatures(string expectedAddress, sbyte[] signatureFragments, string bundleHash)
        {
            if (string.IsNullOrWhiteSpace(bundleHash))
            {
                throw new ArgumentNullException(nameof(bundleHash));
            }

            var bundle = new Bundle();

            var normalizedBundleFragments = new List <int[]>(3);
            var normalizedBundleHash      = TransactionExtensions.NormalizedBundle(bundleHash);

            // Split hash into 3 fragments
            for (var i = 0; i < 3; i++)
            {
                normalizedBundleFragments[i] = normalizedBundleHash.Slice(i * 27, (i + 1) * 27);
            }

            // Get digests
            var digests = new sbyte[signatureFragments.Length * 243];

            for (var i = 0; i < signatureFragments.Length; i++)
            {
                var digestBuffer = Digest(normalizedBundleFragments[i % 3], Converter.GetTrits(signatureFragments[i]));

                for (var j = 0; j < 243; j++)
                {
                    digests[i * 243 + j] = digestBuffer[j];
                }
            }

            var address = Converter.GetTrytes(Address(digests));

            return(expectedAddress == address);
        }
コード例 #3
0
ファイル: Signing.cs プロジェクト: BeeFrog/BeeFrog.Iota.Api
        public bool ValidateSignatures(string expectedAddress, string[] signatureFragments, string bundleHash)
        {
            var normalizedBundleFragments = new int[3, NUMBER_OF_ROUNDS];

            int[] normalizedBundleHash = TransactionExtensions.NormalizedBundle(bundleHash);

            // Split hash into 3 fragments
            for (int i = 0; i < 3; i++)
            {
                Array.Copy(normalizedBundleHash, i * NUMBER_OF_ROUNDS, normalizedBundleFragments, i * NUMBER_OF_ROUNDS, (i + 1) * NUMBER_OF_ROUNDS);
            }

            // Get digests
            int[] digests = new int[signatureFragments.Length * Curl.HashLength];

            for (int i = 0; i < signatureFragments.Length; i++)
            {
                int[] digestBuffer = this.Digest(ArrayUtils.SliceRow(normalizedBundleFragments, i % 3).ToArray(),
                                                 Converter.ToTrits(signatureFragments[i]));

                Array.Copy(digestBuffer, 0, digests, i * Curl.HashLength, Curl.HashLength);
            }
            string address = Converter.ToTrytes(this.Address(digests));

            return(expectedAddress.Equals(address));
        }
コード例 #4
0
        public void CanHashTransaction()
        {
            var payload = "01010000010000980d500f06200000007b1a93132b8c5b8001a07f973307bee2b37bcd6dc279a59ea98179b238d44e2da0860100000000001d5e0f062800000054414c49433337443242374b5246484758524a41514f363759574f5557574133364f55343648534700e40b54020000000a00000001000000020000006869";
            var hash    = TransactionExtensions.Hasher(payload.FromHex()).ToHexLower();

            Assert.AreEqual(hash, "7ae93e9f851f1916931295de6972cd8d96d8c8865720bc57442a718b3f11eb9d");
        }
コード例 #5
0
 public void CanRegisterSynchronizationInCustomTransaction()
 {
     using (var custom = new CustomTransaction())
     {
         TransactionExtensions.RegisterSynchronization(custom, new Synchronization());
         Assert.That(custom.HasRegisteredSynchronization, Is.True);
     }
 }
コード例 #6
0
ファイル: SmtpEmailService.cs プロジェクト: pwalke/Pourcast
        public void SendEmail(MailMessage email)
        {
            if (email == null)
            {
                return;
            }

            TransactionExtensions.WaitForTransactionCompleted(() => _client.SendMailAsync(email));
        }
コード例 #7
0
        public void Hasher()
        {
            var payloadString = "A6000000642AC34E5DD986B6CD3817F2CFAA5A5525447A010F1C08EE62109BCF515AE1F735484478216BEC3DD1B53FE3BCEBCDC3AC182EDC323F860F2736EF4C868EDB0610CC07742437C205D9A0BC0434DC5B4879E002114753DE70CDC4C4BD0D93A64A0390014100000000000000004378F8F40B0000009039404AFFA3D5BB337FE9FA21182210EE40CE08662CF93B77020001000029CF5FD941AD25D50010A5D4E8000000";

            var expected = "E7D31348244723DFDFF54A24BC48BA08623A3660F472EE231D8A93F9C082E360";

            var hash = TransactionExtensions.Hasher(payloadString.FromHex());

            Assert.AreEqual(expected, hash.ToHexLower().ToUpper());
        }
コード例 #8
0
        public void ShouldSignTransaction()
        {
            var privateKey = "6ea3fd5f2cf4fbeb54cd96a48d11cd2ff0b4106472c6a97c7e4e5736243cb2db";
            var data       = "0101000001000098d8f8f905200000007b1a93132b8c5b8001a07f973307bee2b37bcd6dc279a59ea98179b238d44e2da086010000000000e806fa0528000000544250414d4f50524941545054373654415a5a574552484f4b373246494b4e3459434434564a4d4a80969800000000000a00000001000000020000006869";
            var expected   = "2200B5B4BD3CA5589FA9C9AD2DE66C380E5EE31B329F6C186E8D21A57E55E335E8B3E4101C8647809F463AC2D25E9C9910564B241325135C8FFC4D7DD3276303";

            var sig = TransactionExtensions.SignTransaction(new KeyPair(privateKey), data.FromHex());

            Assert.AreEqual(sig.ToHexUpper(), expected);
        }
コード例 #9
0
 public List <AppointmentToTheDoctorTransaction> GetByDoctorId(string doctorId)
 {
     using (IDbConnection dbConnection = Connection)
     {
         dbConnection.Open();
         return(dbConnection
                .Query <TxInternal>("SELECT * FROM transactions where type == @Type and transaction->>'doctorId' = '@DoctorId';",
                                    new { DoctorId = doctorId, Type = TransactionType.VisitToTheDoctor })
                .Select(tx => TransactionExtensions.Deserialize <AppointmentToTheDoctorTransaction>(tx.Transaction)).ToList());
     }
 }
コード例 #10
0
 public List <AppointmentToTheDoctorTransaction> GetByUserId(string userId)
 {
     using (IDbConnection dbConnection = Connection)
     {
         dbConnection.Open();
         return(dbConnection
                .Query <TxInternal>("SELECT * FROM transactions where user_id=@UserId and type=@Type",
                                    new TxInternal {
             UserId = userId, Type = TransactionType.VisitToTheDoctor
         })
                .Select(tx => TransactionExtensions.Deserialize <AppointmentToTheDoctorTransaction>(tx.Transaction)).ToList());
     }
 }
コード例 #11
0
        public HttpStatusCode Post([FromBody] PurchaseOrder purchaseOrder)
        {
            // Grab current users information
            var currentUser = HttpContext.User;

            Transaction transaction = new Transaction();

            // Check to see if the user identity has been validated and snag UserId
            if (currentUser.Claims.Any(c => c.Type == "UserId"))
            {
                transaction.PurchaseOrder   = purchaseOrder;
                transaction.TransactionTime = DateTime.Now.ToUniversalTime();
                transaction.UserId          = int.Parse(currentUser.Claims.First(i => i.Type == "UserId").Value);
            }
            else
            {
                return(HttpStatusCode.Forbidden);
            }

            // Grab user that is associated with the transaction
            User transactionUser = _users.First(u => u.UserId == transaction.UserId);

            // Grab the item price that is associated with the purchase item
            int itemPrice = _inventory.First(i => i.ItemId == purchaseOrder.ItemId).Price;

            // Validate transaction
            bool isValidTransaction = TransactionExtensions.ValidateTransaction(transaction, transactionUser.AccountBalance, itemPrice);

            if (isValidTransaction)
            {
                // Decrement account balance in DB
                transactionUser.AccountBalance = (transactionUser.AccountBalance - (transaction.PurchaseOrder.Quantity * itemPrice));

                // Add transaction in DB | DB would increment the transactionID up
                _transactions.Add(transaction);

                // Return successful response
                return(HttpStatusCode.Accepted);
            }

            // Return failed response
            return(HttpStatusCode.Forbidden);
        }
コード例 #12
0
        public void BulkDelete(Expression <Func <T, bool> > expression)
        {
            try
            {
                if (expression == null)
                {
                    throw new ArgumentNullException(nameof(expression));
                }

                using (var tx = TransactionExtensions.CreateTransactionScope())
                {
                    _dbSet.Where(expression)
                    .DeleteFromQuery();
                    tx.Complete();
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
コード例 #13
0
        public static void SignSignature(this TransactionItem transactionItem, int[] addressPrivateKey, ICurl curl)
        {
            var value = Int64.Parse(transactionItem.Value);

            if (value > 0)
            {
                return;
            }
            //throw new IotaException($"Cannot sign transaction with value greater than 0. Current value '{value}'");

            int index = value < 0 ? 0 : 1;

            var normalizedBundleHash = TransactionExtensions.NormalizedBundle(transactionItem.Bundle);

            //  First 6561 trits for the firstFragment
            int[] firstFragment = ArrayUtils.SubArray2(addressPrivateKey, 6561 * index, 6561);
            //  First bundle fragment uses 27 trytes
            int[] firstBundleFragment = ArrayUtils.SubArray2(normalizedBundleHash, 27 * index, 27);
            //  Calculate the new signatureFragment with the first bundle fragment
            int[] firstSignedFragment = new Signing(curl).SignatureFragment(firstBundleFragment, firstFragment);

            //  Convert signature to trytes and assign the new signatureFragment
            transactionItem.SignatureFragment = Converter.ToTrytes(firstSignedFragment);
        }
コード例 #14
0
        public void Handle(KegRemovedFromTap domainEvent)
        {
            var context = _connectionManager.GetHubContext <EventsHub>();

            TransactionExtensions.WaitForTransactionCompleted(() => context.Clients.All.KegRemovedFromTap(domainEvent));
        }
コード例 #15
0
        private static void Main(string[] args)
        {
            #region Setup for Reactive ASCOM

            /*
             * First create our channel factory.
             * This is also the place where we can inject a logging service.
             * If you don't provide a logging service here, there will be no logging!
             * Note that logging is configured in NLog.config.
             * See also: TA.Utils.Core.Diagnostics
             *
             * The channel factory knows about serial ports by default, but we are going to
             * register a custom channel implementation that contains a hardware simulator.
             * (the simulator is abstracted from the Digital Domeworks dome driver).
             * If you make your own custom channels, you can register them the same way.
             */
            var log = new LoggingService(); // TA.Utils.Logging.NLog
            log.Info()
            .Message("Program start. Version {gitversion}", GitVersion.GitInformationalVersion)
            .Property("CommitSha", GitVersion.GitCommitSha)
            .Property("CommitDate", GitVersion.GitCommitDate)
            .Write();

            var channelFactory = new ChannelFactory(log);
            channelFactory.RegisterChannelType(
                SimulatorEndpoint.IsConnectionStringValid,
                SimulatorEndpoint.FromConnectionString,
                endpoint => new SimulatorCommunicationsChannel((SimulatorEndpoint)endpoint, log));

            /*
             * Now get our connection string from the AppSettings.json file.
             */

            var connectionString = Configuration["ConnectionString"];

            /*
             * Create the communications channel and connect it to the transaction observer.
             * The TransactionObserver is the beating heart of Rx Comms and is where everything is synchronized.
             */
            var channel             = channelFactory.FromConnectionString(connectionString);
            var transactionObserver = new TransactionObserver(channel);

            /*
             * TransactionObsever is an IObservable<DeviceTransaction>, so we need a sequence for it to observe.
             * The transaction sequence can be created by any convenient means, and Rx Comms provides
             * a handy helper class for doing this, called ReactiveTransactionProcessor.
             *
             * However the sequence is created, it must be fed into the transaction observer
             * by creating a subscription. ReactiveTransactionProcessor has a helper method for that.
             * The helper method also gives us a way to rate-limit commands to the hardware, if needed.
             */
            var transactionProcessor = new ReactiveTransactionProcessor();
            transactionProcessor.SubscribeTransactionObserver(transactionObserver, TimeSpan.FromSeconds(1));
            channel.Open();
            #endregion Setup for Reactive ASCOM

            // All set up and ready to go.
            try
            {
                // First we'll create a StatusTransaction and get the device's status.
                var statusTransaction = new StatusTransaction();
                transactionProcessor.CommitTransaction(statusTransaction);
                statusTransaction.WaitForCompletionOrTimeout(); // There is also an async version

                // If the transaction failed, log and throw TransactionException.
                TransactionExtensions.ThrowIfFailed(statusTransaction, log);

                // Now we can retrieve the results and use them.
                // If the transaction succeeded, we should be assured of a valid result.
                // When you write your own transactions, make sure this is so!
                var status = statusTransaction.HardwareStatus;
                log.Debug().Message("Got status: {deviceStatus}", status).Write();

                // Get the user GPIO pins and flip the value of pin 0.
                var gpioPins        = status.UserPins;
                var gpioPinsToWrite = gpioPins.WithBitSetTo(0, !gpioPins[0]);

                // Now we'll use another transaction to set the new GPIO pin state.
                var gpioTransaction = new SetUserPinTransaction(gpioPinsToWrite);
                transactionProcessor.CommitTransaction(gpioTransaction);
                gpioTransaction.WaitForCompletionOrTimeout();

                TransactionExtensions.ThrowIfFailed(gpioTransaction, log);
                var newPinState = gpioTransaction.UserPins;
                if (newPinState != gpioPinsToWrite)
                {
                    throw new ApplicationException("Failed to write GPIO pins");
                }
                log.Info()
                .Message("Successfully changed GPIO pins {oldState} => {newState}", gpioPins, newPinState)
                .Write();
            }
            catch (TransactionException exception)
            {
                log.Error().Exception(exception)
                .Message("Transaction failed {transaction}", exception.Transaction)
                .Write();
                Console.WriteLine(exception);
            }
            catch (ApplicationException exception)
            {
                log.Error().Message("Failed to set teh GPIO pins.").Exception(exception).Write();
            }
            finally
            {
                /*
                 * We just need to dispose the transaction processor. This terminates the
                 * sequence of transactions, which causes the TransactionObserver's OnCompleted method
                 * to be called, which unsubscribes the receive sequence, which closes the
                 * communications channel.
                 */
                transactionProcessor.Dispose();
                log.Info().Message("Cleanup complete").Write();

                /*
                 * It is best practice to explicitly shut down the logging service,
                 * otherwise any buffered log entries might not be written to the log.
                 * This may take a few seconds if you are using a slow log target.
                 */
                log.Shutdown();
            }
        }
コード例 #16
0
        public void Handle(PourStopped domainEvent)
        {
            var context = _connectionManager.GetHubContext <EventsHub>();

            TransactionExtensions.WaitForTransactionCompleted(() => context.Clients.All.PourStopped(domainEvent));
        }
コード例 #17
0
ファイル: MSSqlConnection.cs プロジェクト: Dziurson/WPO-ORM
        public void CreateSchema(List <TableSchema> schema)
        {
            ExecuteTask(() =>
            {
                List <TableSchema> alters = new List <TableSchema>();
                foreach (TableSchema table in schema)
                {
                    if (!IsTableExists(table.Name))
                    {
                        StringBuilder query = new StringBuilder();
                        query.Append("CREATE TABLE " + table.Name + " ( \n");
                        foreach (TableSchema.ColumnSchema column in table.Columns)
                        {
                            query.Append(column.Name);
                            query.Append(" " + DatatypeResolver.Resolve(column.ColType));
                            if ((column.Length != null) && (column.Length > 0))
                            {
                                query.Append("(" + column.Length);
                                if ((column.FractionalPartLength != null) && (column.FractionalPartLength > 0))
                                {
                                    query.Append(", " + column.FractionalPartLength);
                                }
                                query.Append(")");
                            }
                            else
                            {
                                query.Append(Converter.EnumToDefaultString(column.ColType));
                            }
                            if (!column.AllowNull)
                            {
                                query.Append(" NOT NULL");
                            }
                            if (column.IsPrimaryKey)
                            {
                                query.Append(" PRIMARY KEY");
                            }
                            query.Append(",\n");
                            if (column.HasForeignKey && !alters.Contains(table))
                            {
                                alters.Add(table);
                            }
                        }
                        query.Append(")\n");
                        TransactionExtensions.WriteDiagnostics(query.ToString());
                        SqlCommand command = new SqlCommand(query.ToString(), connection);
                        command.ExecuteNonQuery();
                    }
                }

                foreach (TableSchema table in alters)
                {
                    foreach (TableSchema.ColumnSchema column in table.Columns)
                    {
                        if (column.HasForeignKey)
                        {
                            string alterquery = "ALTER TABLE " + table.Name + " \nADD FOREIGN KEY (" + column.Name + ") \nREFERENCES " + column.ForeignTableName + "(" + column.ForeignKeyName + ")\n";
                            TransactionExtensions.WriteDiagnostics(alterquery);
                            SqlCommand command = new SqlCommand(alterquery, connection);
                            command.ExecuteNonQuery();
                        }
                    }
                }
                return(true);
            });
        }