Esempio n. 1
0
        /// <summary>
        /// Undos a transaction without changing the undo stack.
        /// This method can cause inconsistencies in the undo system and should be used with care.
        /// </summary>
        public void UndoTransactionNoPush(Transaction.Transaction transaction)
        {
            switch (transaction)
            {
            case WireTransaction wt:
                Wires.RevertTransaction(wt);
                break;

            case GateTransaction gt:
                Gates.RevertTransaction(gt);
                break;

            case BundledTransaction bt:
            {
                foreach (var bundled in bt.BundledTransactions)
                {
                    UndoTransactionNoPush(bundled);
                }
                break;
            }

            default:
                throw new Exception($"Unknown transaction type! {transaction.GetType()}");
            }
        }
Esempio n. 2
0
        public Tuple <Transaction.Transaction, Contract> Deploy(DeployParams param, int attempts, int interval)
        {
            if (string.IsNullOrEmpty(code) || init == null || init.Count() <= 0)
            {
                throw new Exception("Cannot deploy without code or initialisation parameters.");
            }
            Transaction.Transaction transaction = new Transaction.Transaction();
            transaction.ID           = param.ID;
            transaction.Version      = param.Version;
            transaction.Nonce        = param.Nonce;
            transaction.GasPrice     = param.GasPrice;
            transaction.GasLimit     = param.GasLimit;
            transaction.SenderPubKey = param.SenderPubKey;
            transaction.ToAddr       = NIL_ADDRESS;
            transaction.Amount       = "0";
            transaction.Code         = this.code.Replace("/\\", "");
            transaction.Data         = JsonConvert.SerializeObject(this.init);
            transaction.Provider     = this.provider;
            transaction = this.prepareTx(transaction, attempts, interval);
            if (transaction.IsRejected())
            {
                this.contractStatus = ContractStatus.Rejected;
                return(Tuple.Create <Transaction.Transaction, Contract>(transaction, this));
            }

            this.contractStatus = ContractStatus.Deployed;
            this.address        = ContractFactory.GetAddressForContract(transaction);
            return(Tuple.Create <Transaction.Transaction, Contract>(transaction, this));
        }
Esempio n. 3
0
        public static string GetAddressForContract(Transaction.Transaction tx)
        {
            string senderAddress = KeyTools.GetAddressFromPublicKey(tx.SenderPubKey);

            SHA256Managed.Create().ComputeHash(ByteUtil.HexStringToByteArray(senderAddress));
            Sha256Digest sha = new Sha256Digest();

            byte[] senderAddressBytes = ByteUtil.HexStringToByteArray(senderAddress);
            sha.BlockUpdate(senderAddressBytes, 0, senderAddressBytes.Count());

            int nonce = 0;

            if (!string.IsNullOrEmpty(tx.Nonce))
            {
                nonce = int.Parse(tx.Nonce);
                nonce--;
            }
            string hexNonce = Validation.IntToHex(nonce, 16);

            byte[] hexNonceBytes = ByteUtil.HexStringToByteArray(hexNonce);
            sha.BlockUpdate(hexNonceBytes, 0, hexNonceBytes.Count());
            byte[] bytes = new byte[sha.GetByteLength()];
            sha.DoFinal(bytes, 0);

            return(ByteUtil.ByteArrayToHexString(bytes).Substring(24, 40));
        }
Esempio n. 4
0
        //---------------------------------------------------------------------------
        /// <summary>
        /// Конструктор
        /// </summary>
        public ComPort()
        {
            _SyncRoot = new Object();
            _СurrentTransaction = 
                new Modbus.OSIModel.Transaction.Transaction(TransactionType.Undefined, null);

            _TimerInterFrameDelay = new Timer(20);
            _TimerInterFrameDelay.AutoReset = false;
            _TimerInterFrameDelay.Elapsed +=
                new ElapsedEventHandler(EventHandler_TmrInterFrameDelay_Elapsed);
            _TimerInterFrameDelay.Stop();

            _TimerTimeoutCurrentTransaction = new Timer();
            _TimerTimeoutCurrentTransaction.AutoReset = false;
            _TimerTimeoutCurrentTransaction.Interval = 200;
            _TimerTimeoutCurrentTransaction.Elapsed +=
                new ElapsedEventHandler(EventHandler_TimerTimeoutCurrentTransaction_Elapsed);
            _TimerTimeoutCurrentTransaction.Stop();

            // Настраиваем последовательный порт
            _SerialPort =
                new System.IO.Ports.SerialPort("COM1", 19200, Parity.Even, 8, StopBits.One);
            
            _SerialPort.ErrorReceived += new
                SerialErrorReceivedEventHandler(EventHandler_SerialPort_ErrorReceived);
            _SerialPort.DataReceived +=
                new SerialDataReceivedEventHandler(EventHandler_SerialPort_DataReceived);
            _SerialPort.ReceivedBytesThreshold = 1;
        }
Esempio n. 5
0
        public Transaction.Transaction SignWith(Transaction.Transaction tx, Account signer)
        {
            BalanceResult result;

            if (signer == null)
            {
                throw new Exception("account not exists");
            }
            if (string.IsNullOrEmpty(tx.Nonce))
            {
                try
                {
                    result   = this.Provider.GetBalance(signer.Address).Result;
                    tx.Nonce = result.Nonce + 1;
                }
                catch (Exception e)
                {
                    throw new Exception("cannot get nonce", e);
                }
            }
            tx.SenderPubKey = signer.GetPublicKey();
            byte[]    message   = tx.Bytes();
            Signature signature = Schnorr.Sign(signer.Keys, message);

            tx.Signature = (signature.ToString().ToLower());
            return(tx);
        }
Esempio n. 6
0
        //---------------------------------------------------------------------------
        /// <summary>
        /// Конструктор
        /// </summary>
        public ComPort()
        {
            _SyncRoot           = new Object();
            _СurrentTransaction =
                new Modbus.OSIModel.Transaction.Transaction(TransactionType.Undefined, null);

            _TimerInterFrameDelay           = new Timer(20);
            _TimerInterFrameDelay.AutoReset = false;
            _TimerInterFrameDelay.Elapsed  +=
                new ElapsedEventHandler(EventHandler_TmrInterFrameDelay_Elapsed);
            _TimerInterFrameDelay.Stop();

            _TimerTimeoutCurrentTransaction           = new Timer();
            _TimerTimeoutCurrentTransaction.AutoReset = false;
            _TimerTimeoutCurrentTransaction.Interval  = 200;
            _TimerTimeoutCurrentTransaction.Elapsed  +=
                new ElapsedEventHandler(EventHandler_TimerTimeoutCurrentTransaction_Elapsed);
            _TimerTimeoutCurrentTransaction.Stop();

            // Настраиваем последовательный порт
            _SerialPort =
                new System.IO.Ports.SerialPort("COM1", 19200, Parity.Even, 8, StopBits.One);

            _SerialPort.ErrorReceived += new
                                         SerialErrorReceivedEventHandler(EventHandler_SerialPort_ErrorReceived);
            _SerialPort.DataReceived +=
                new SerialDataReceivedEventHandler(EventHandler_SerialPort_DataReceived);
            _SerialPort.ReceivedBytesThreshold = 1;
        }
        public void TestHaveUnused()
        {
            var txbody = new Body
            {
                ChainTag     = 74,
                BlockRef     = "0x005d64da8e7321bd",
                Expiration   = 18,
                GasPriceCoef = 0,
                Gas          = 21000,
                DependsOn    = "",
                Nonce        = "0xd6846cde87878603",
                Reserved     = new Reserved
                {
                    Features = 1,
                    Unused   = new System.Collections.Generic.List <byte[]>
                    {
                        "0xa4aDAfAef9Ec07BC4Dc6De146934C7119341eE25".ToBytes()
                    }
                }
            };

            byte[] encode  = new Transaction.Transaction(txbody).Encode();
            var    encode2 = "0xf04a875d64da8e7321bd12c0808252088088d6846cde87878603d60194a4adafaef9ec07bc4dc6de146934c7119341ee25".ToBytes();

            Assert.True(encode.SequenceEqual(encode2));
        }
Esempio n. 8
0
 internal SqlQueryable(Expression exp, Transaction.Transaction repository)
 {
     _repository = repository;
     if (exp != null)
     {
         _matches.Add(exp);
     }
 }
 public Task <TransactionProduct> CreateAsync(Product.Product product, Transaction.Transaction transaction)
 {
     return(Task.Factory.StartNew(() =>
     {
         var transactionProduct = new TransactionProduct(product, transaction);
         return transactionProduct;
     }));
 }
Esempio n. 10
0
        /// <summary>
        /// Обработчик события срабатывания межкадрового таймера
        /// </summary>
        /// <param name="sender">Отправитель события</param>
        /// <param name="e">Аргументы события</param>
        private void EventHandler_TmrInterFrameDelay_Elapsed(
            object sender, ElapsedEventArgs e)
        {
            Byte[]          message;
            Message.Message request;
            Timer           tmr = (Timer)sender;

            tmr.Stop();

            // Таймер сработал, значит сообщение (запрос)
            // принят полностью считаем CRC16
            message = new byte[_SerialPort.BytesToRead];
            _SerialPort.Read(message, 0, _SerialPort.BytesToRead);

            if (true == Modbus.OSIModel.DataLinkLayer.CRC16.VerefyCRC16(message))
            {
                // Запрос принят корректно
                Byte[] array = new byte[(message.Length - 4)];  //Данные в сообщениии
                Array.Copy(message, 2, array, 0, array.Length); // Выделили данные из сообщения

                request = new Message.Message(message[0], message[1], array);

                if (request.Address == 0)
                {
                    // Формируем событие приёма широковещаетельного запроса
                    _СurrentTransaction = new Transaction.Transaction(
                        TransactionType.BroadcastMode, request);
                    _СurrentTransaction.TransactionWasEnded +=
                        new EventHandler(EventHandler_СurrentTransaction_TransactionWasEnded);
                    _СurrentTransaction.Start(); // Стартуем транзакцию
                    OnRequestWasRecived(new MessageEventArgs(request));
                    // ??? Можно было бы запустить таймер задержки при широковещаетльном запросе
                    // Сейчас не реализовано. По этому, завершам транзакцию сразу.
                    _СurrentTransaction.Stop(null); // Завершает транзакцию
                }
                else
                {
                    _СurrentTransaction = new Transaction.Transaction(
                        TransactionType.UnicastMode, request);
                    _СurrentTransaction.TransactionWasEnded +=
                        new EventHandler(EventHandler_СurrentTransaction_TransactionWasEnded);
                    _СurrentTransaction.Start();
                    // Запускаем таймер таймаута ответа подчинённого устройства
                    _TimerTimeoutCurrentTransaction.Start();
                    // Формируем событие приёма адресованного запроса.
                    // Транзакция здесь продолжается до тех пор, покак не будет
                    // отправлен ответ.
                    OnRequestWasRecived(new MessageEventArgs(request));
                }
            }
            else
            {
                // Принят запрос с неверным CRC16
                OnErrorOccurred(new ErrorOccurredEventArgs
                                    (PortError.CheckSumError, "Принят запрос с неверным CRC16"));
            }
            return;
        }
Esempio n. 11
0
        public void TestRlpEncode()
        {
            var txbody = this.TestTxBody();

            byte[] encode  = new Transaction.Transaction(txbody).Encode();
            var    encode2 = "f8844a875d64da8e7321bd12f869e294a4adafaef9ec07bc4dc6de146934c7119341ee25830186a0882398479812734981e294a4adafaef9ec07bc4dc6de146934c7119341ee25830186a0882398479812734981e294a4adafaef9ec07bc4dc6de146934c7119341ee25830186a0882398479812734981808252088088d6846cde87878603c0".ToBytes();

            Assert.True(encode.SequenceEqual(encode2));
        }
Esempio n. 12
0
 internal SqlQueryable(Expression exp, Transaction.Transaction repository)
 {
     _repository = repository;
     _expression = new LinqToSql(typeof(T), _repository);
     if (exp != null)
     {
         _matches.Add(exp);
     }
 }
Esempio n. 13
0
        /// <summary>
        /// Обработчик события окончания текущей транзакции
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void EventHandler_СurrentTransaction_TransactionWasEnded(
            object sender, EventArgs e)
        {
            String msg;

            Transaction.Transaction transaction =
                (Transaction.Transaction)sender;

            // Анализируем причины завершения транзакции
            // !!! Здесь можно реализовать стек отработавший транзакций и поместить транзакцию туда
            switch (transaction.Status)
            {
            case TransactionStatus.Aborted:
            {
                msg = String.Format("Transaction ID: {0}; Статус: {1}; Описание ошибки: {2}; " +
                                    "Начало транзакции: {3} мсек; Конец транзакции: {4} мсек; Время транзакции: {5} мсек",
                                    transaction.Identifier.ToString(), transaction.Status, transaction.DescriptionError,
                                    transaction.TimeOfStart, transaction.TimeOfEnd, transaction.TimeOfTransaction);
                Trace.TraceInformation(msg);
                break;
            }

            case TransactionStatus.Completed:
            {
                msg = String.Format("Transaction ID: {0}; Статус: {1}; Описание ошибки: {2}; " +
                                    "Начало транзакции: {3} мсек; Конец транзакции: {4} мсек; Время транзакции: {5} мсек",
                                    transaction.Identifier.ToString(), transaction.Status, transaction.DescriptionError,
                                    transaction.TimeOfStart, transaction.TimeOfEnd, transaction.TimeOfTransaction);
                Trace.TraceInformation(msg);
                break;
            }

            case TransactionStatus.NotInitialized:
            {
                throw new Exception(String.Format(
                                        "Обнаружен неверный статус завершённой транзакции - {0}", transaction.Status));
            }

            case TransactionStatus.Running:
            {
                throw new Exception(String.Format(
                                        "Обнаружен неверный статус завершённой транзакции - {0}", transaction.Status));
            }

            default:
            {
                throw new Exception(
                          "Полученное состояние транзакции не поддерживается в текущей версии ПО");
            }
            }

            //_SerialPort.DiscardOutBuffer();
            //_SerialPort.DiscardInBuffer();

            return;
        }
Esempio n. 14
0
 internal SqlQueryable(Transaction.Transaction repository, List <T> items)
 {
     _repository = repository;
     if (items == null)
     {
         return;
     }
     _partExecuted = true;
     items.RemoveAll(x => x == null);
     base.AddRange(items);
 }
Esempio n. 15
0
 internal SqlQueryable(Transaction.Transaction repository, List <T> items)
 {
     _repository = repository;
     _expression = new LinqToSql(typeof(T), _repository);
     if (items == null)
     {
         return;
     }
     PartExecuted = true;
     items.RemoveAll(x => x == null);
     base.AddRange(items);
 }
Esempio n. 16
0
        public void TestSign()
        {
            var txbody      = this.TestTxBody();
            var transaction = new Transaction.Transaction(txbody);

            transaction.Signature = Cry.Secp256k1.Sign(transaction.SigningHash(), "0xdce1443bd2ef0c2631adc1c67e5c93f13dc23a41c18b536effbbdcbcdb96fb65".ToBytes());

            (Transaction.Transaction.UnsignedRlpDefinition() as RlpStructKind)?.EncodeToRlp(transaction.Body);

            Assert.True(transaction.Signature.SequenceEqual("0x5ca73236f37c9d7b29f32af81e4812a33cfbfac573544684e374e2fb90c637740d406198252371fa3e64341e4bd0226268a774e4112913429750b3fb3fad56bf00".ToBytes()));
            Assert.True(transaction.Origin == "0x7567d83b7b8d80addcb281a71d54fc7b3364ffed");
            Assert.True(transaction.Id == "0xd3ad13b5db7be0a3ecc64ff537442047baa5d1df9593237e173fa097be2e7182");
        }
 public LightDataLinqToNoSql(Type type, Transaction.Transaction transaction)
 {
     _transaction = transaction;
     _obType      = type.GetActualType();
     if (!CachedColumns.ContainsKey(_obType))
     {
         _columns = CachedColumns.GetOrAdd(_obType, _transaction.GetColumnSchema(_obType).Select(x => $"[{_obType.TableName()}].[{x.Key}]").ToList());
     }
     else
     {
         _columns = CachedColumns[_obType];
     }
     _primaryId = _obType.GetPrimaryKey()?.GetPropertyName();
 }
Esempio n. 18
0
 public LightDataLinqToNoSql(Type type, Transaction.Transaction transaction)
 {
     _transaction = transaction;
     _obType      = type.GetActualType();
     if (!CachedColumns.ContainsKey(_obType))
     {
         _columns = CachedColumns.GetOrAdd(_obType, _transaction._dbSchema.ObjectColumns(_obType).Rows.Select(x => $"[{_obType.TableName()}].[{x.Value<string>("column_name")}]").ToList());
     }
     else
     {
         _columns = CachedColumns[_obType];
     }
     _primaryId = OrderBy = _obType.GetPrimaryKey()?.GetPropertyName();
 }
Esempio n. 19
0
        public LinqToSql(Type type, Transaction.Transaction transaction)
        {
            _transaction  = transaction;
            _obType       = type.GetActualType();
            DataBaseTypes = transaction.DataBaseTypes;
            var key = _obType.FullName + DataBaseTypes;

            if (!CachedColumns.ContainsKey(key))
            {
                _columns = CachedColumns.GetOrAdd(key, _transaction.GetColumnSchema(_obType).Select(x => $"{_obType.TableName().GetName(DataBaseTypes)}.[{x.Key}]").ToList());
            }
            else
            {
                _columns = CachedColumns[key];
            }
            _primaryId = _obType.GetPrimaryKey()?.GetPropertyName();
        }
Esempio n. 20
0
 public Transaction.Transaction prepareTx(Transaction.Transaction tx, int attempts, int interval)
 {
     tx = signer.Sign(tx);
     try
     {
         CreateTxResult createTxResult = provider.CreateTransaction(tx.ToTransactionPayload()).Result;
         tx.Confirm(createTxResult.TranID, attempts, interval);
     }
     catch (IOException e)
     {
         tx.Status = TxStatus.Rejected;
     }
     catch (Exception e)
     {
     }
     return(tx);
 }
Esempio n. 21
0
        /// <summary>
        /// Applies a transaction without pushing it to the undo stack.
        /// This method can cause inconsistencies in the undo system and should be used with care.
        /// </summary>
        public void DoTransactionNoPush(Transaction.Transaction transaction)
        {
            switch (transaction)
            {
            case WireTransaction wt:
                Wires.ApplyTransaction(wt);
                // Update the subnets
                UpdateSubnets(wt.Created, wt.Deleted);
                break;

            case GateTransaction gt:
                Gates.ApplyTransaction(gt);
                if (gt.ConnectionPointWireEdits != null)
                {
                    Wires.ApplyTransaction(gt.ConnectionPointWireEdits);
                }
                // FIXME: Clean this up, this is just so that we can get something simulating
                if (gt.RemoveComponent)
                {
                    this.RemoveComponent(gt.Gate);
                }
                else
                {
                    this.AddComponent(gt.Gate);
                }
                // Update the subnets
                UpdateSubnets(
                    gt.ConnectionPointWireEdits?.CreatedWires ?? new List <Wire>(),
                    gt.ConnectionPointWireEdits?.DeletedWires ?? new List <Wire>());
                break;

            case BundledTransaction bt:
            {
                foreach (var bundled in bt.BundledTransactions)
                {
                    DoTransactionNoPush(bundled);
                }
                break;
            }

            default:
                throw new Exception($"Unknown transaction type! {transaction.GetType()}");
            }
        }
Esempio n. 22
0
        public void TestDelegate()
        {
            var delegatedBody = new Body
            {
                ChainTag     = 74,
                BlockRef     = "0x005d64da8e7321bd",
                Expiration   = 18,
                GasPriceCoef = 0,
                Gas          = 21000,
                DependsOn    = "",
                Nonce        = "0xd6846cde87878603",
                Reserved     = new Reserved {
                    Features = 1
                }
            };

            delegatedBody.Clauses.Add(new Clause("0xa4aDAfAef9Ec07BC4Dc6De146934C7119341eE25", new BigInteger(100000), "0x2398479812734981"));
            delegatedBody.Clauses.Add(new Clause("0xa4aDAfAef9Ec07BC4Dc6De146934C7119341eE25", new BigInteger(100000), "0x2398479812734981"));
            delegatedBody.Clauses.Add(new Clause("0xa4aDAfAef9Ec07BC4Dc6De146934C7119341eE25", new BigInteger(100000), "0x2398479812734981"));

            var transaction = new Transaction.Transaction(delegatedBody);

            Assert.True(transaction.IsDelegated);

            var senderPrikey = "0xdce1443bd2ef0c2631adc1c67e5c93f13dc23a41c18b536effbbdcbcdb96fb65";
            var senderAddr   = "0x7567d83b7b8d80addcb281a71d54fc7b3364ffed";

            var gasPayerPrikey = "0x321d6443bc6177273b5abf54210fe806d451d6b7973bccc2384ef78bbcd0bf51";
            var geaPayerAddr   = "0xd3ae78222beadb038203be21ed5ce7c9b1bff602";

            Assert.True(transaction.SigningHash().SequenceEqual("0xb07661afea87bf07d3a76742950b1607174090bc2241a32e40f8d35e3747e0ad".ToBytes()));

            var senderSigningHash   = transaction.SigningHash();
            var gasPayerSigningHash = transaction.SigningHash(senderAddr);

            var senderSignature   = Cry.Secp256k1.Sign(senderSigningHash, senderPrikey.ToBytes());
            var gasPayerSignature = Cry.Secp256k1.Sign(gasPayerSigningHash, gasPayerPrikey.ToBytes());

            transaction.AddVIP191Signature(senderSignature, gasPayerSignature);

            Assert.True(transaction.Id == "0xf6a2eab557187af50e4a3abb8a65894eb3be4d58a557b31e8f878ca91c0d9f4e");
            Assert.True(transaction.Origin == senderAddr);
            Assert.True(transaction.Delegator == geaPayerAddr);
        }
Esempio n. 23
0
        private void Parse(string value, FormattingOptions options)
        {
            FormattingOptions = options;
            var segmentStringValueCollection = value.Split(options.SegmentTerminator.AsSplitDelimiter(), StringSplitOptions.None);
            var transactionStringArray       = new List <System.Text.StringBuilder>();

            foreach (var segment in segmentStringValueCollection)
            {
                if (segment.Length < 2)
                {
                    continue;
                }
                switch (segment.Substring(0, 2))
                {
                case FunctionalGroupHeader.ElementName:
                    Header = new FunctionalGroupHeader(segment, FormattingOptions);
                    break;

                case FunctionalGroupTrailer.ElementName:
                    Trailer = new FunctionalGroupTrailer(segment, FormattingOptions);
                    break;

                case TransactionSetHeader.ElementName:
                    transactionStringArray.Add(new System.Text.StringBuilder());
                    transactionStringArray[transactionStringArray.Count - 1].Append(segment);
                    transactionStringArray[transactionStringArray.Count - 1].Append(options.SegmentTerminator);
                    break;

                default:
                    transactionStringArray[transactionStringArray.Count - 1].Append(segment);
                    transactionStringArray[transactionStringArray.Count - 1].Append(options.SegmentTerminator);
                    break;
                }
            }

            foreach (var transactionString in transactionStringArray)
            {
                var tx = new Transaction.Transaction(transactionString.ToString(), FormattingOptions);
                TransactionSets.Add(tx);
            }

            TransactionSets.TrimExcess();
        }
Esempio n. 24
0
        public void TestNoClauses()
        {
            var txbody = new Body
            {
                ChainTag     = 74,
                BlockRef     = "0x005d64da8e7321bd",
                Expiration   = 18,
                GasPriceCoef = 0,
                Gas          = 21000,
                DependsOn    = "",
                Nonce        = "0xd6846cde87878603",
                Reserved     = null
            };

            byte[] encode  = new Transaction.Transaction(txbody).Encode();
            var    encode2 = "0xda4a875d64da8e7321bd12c0808252088088d6846cde87878603c0".ToBytes();

            Assert.True(encode.SequenceEqual(encode2));
        }
Esempio n. 25
0
        public Transaction.Transaction Sign(Transaction.Transaction transaction)
        {
            if (transaction.ToAddr.ToUpper().StartsWith("0X"))
            {
                transaction.ToAddr = transaction.ToAddr.Substring(2);
            }

            if (!Validation.IsBech32(transaction.ToAddr) && !Validation.IsValidChecksumAddress("0x" + transaction.ToAddr))
            {
                throw new Exception("not checksum address or bech32");
            }

            if (Validation.IsBech32(transaction.ToAddr))
            {
                transaction.ToAddr = Bech32.FromBech32Address(transaction.ToAddr);
            }

            if (Validation.IsValidChecksumAddress("0x" + transaction.ToAddr))
            {
                transaction.ToAddr = "0x" + transaction.ToAddr;
            }

            TxParams txParams = transaction.ToTransactionParam();

            if (txParams != null && !string.IsNullOrEmpty(txParams.SenderPubKey))
            {
                string  address = KeyTools.GetAddressFromPublicKey(txParams.SenderPubKey).ToUpper();
                Account account = accounts[address];
                if (account == null)
                {
                    throw new Exception("Could not sign the transaction with" + address + "  as it does not exist");
                }
                return(SignWith(transaction, account));
            }

            if (defaultAccount == null)
            {
                throw new Exception("This wallet has no default account.");
            }

            return(this.SignWith(transaction, this.defaultAccount));
        }
Esempio n. 26
0
        /// <summary>
        ///     Decode - Decodes a raw bitcoin block
        /// </summary>
        private void Decode()
        {
            BlockSize = (uint)ByteData.Length;

            // header is 80bytes
            Header = new BlockHeader(ReadSlice(80));

            // get the number of transactions
            Transactions = new Transaction.Transaction[ReadVarLenInt()];

            // read all the transactions
            for (var i = 0; i < Transactions.Length; ++i)
            {
                // decode the transaction
                Transactions[i] = DecodeTX();
            }

            // validate length - should be at the end of the block
            LengthMatch = Offset == ByteData.Length;
        }
Esempio n. 27
0
        public Transaction.Transaction Call(Transition transition, Values[] args, CallParams param, int attempts, int interval)
        {
            if (string.IsNullOrEmpty(address))
            {
                throw new Exception("Contract has not been deployed!");
            }

            Transaction.Transaction transaction = new Transaction.Transaction();
            transaction.ID           = param.ID;
            transaction.Version      = param.Version;
            transaction.Nonce        = param.Nonce;
            transaction.GasPrice     = param.GasPrice;
            transaction.GasLimit     = param.GasLimit;
            transaction.SenderPubKey = param.SenderPubKey;
            transaction.ToAddr       = NIL_ADDRESS;
            transaction.Amount       = "0";
            transaction.Code         = this.code.Replace("/\\", "");
            transaction.Data         = JsonConvert.SerializeObject(new Data()
            {
                Tag = transition, Params = args
            });
            transaction.Provider = this.provider;
            return(this.prepareTx(transaction, attempts, interval));
        }
Esempio n. 28
0
 public TransactionProduct(Product.Product product, Transaction.Transaction transaction)
 {
     Product     = product;
     Transaction = transaction;
 }
Esempio n. 29
0
        internal static IList DataReaderConverter(Transaction.Transaction repository, IDataReader reader, DbCommandExtended command, Type type)
        {
            var tType        = type.GetActualType();
            var baseListType = typeof(List <>);
            var listType     = baseListType.MakeGenericType(tType);
            var iList        = DeepCloner.CreateInstance(listType) as IList;
            //#if (NETSTANDARD2_0 || NETSTANDARD1_3 || NETSTANDARD1_5)
            var props = DeepCloner.GetFastDeepClonerProperties(tType);

            //#endif
            try
            {
                while (reader.Read())
                {
                    object item   = null;
                    object clItem = null;
                    //#if (NETSTANDARD2_0 || NETSTANDARD1_3 || NETSTANDARD1_5)

                    item   = DeepCloner.CreateInstance(tType);
                    clItem = DeepCloner.CreateInstance(tType);
                    var col = 0;

                    while (col < reader.FieldCount)
                    {
                        var columnName = reader.GetName(col);
                        var value      = reader[columnName];

                        var prop = DeepCloner.GetProperty(tType, columnName);

                        if (prop == null)
                        {
                            prop = props.FirstOrDefault(x => string.Equals(x.GetPropertyName(), columnName, StringComparison.CurrentCultureIgnoreCase) || x.GetPropertyName().ToLower() == columnName);
                        }

                        if (value != DBNull.Value && value != null && prop != null && prop.CanRead)
                        {
                            if (value as byte[] != null && prop.PropertyType.FullName.Contains("Guid"))
                            {
                                value = new Guid(value as byte[]);
                            }

                            var dataEncode     = prop.GetCustomAttribute <DataEncode>();
                            var toBase64String = prop.GetCustomAttribute <ToBase64String>();

                            if (toBase64String != null)
                            {
                                if (value.ConvertValue <string>().IsBase64String())
                                {
                                    value = MethodHelper.DecodeStringFromBase64(value.ConvertValue <string>());
                                }
                                else
                                {
                                    value = MethodHelper.ConvertValue(value, prop.PropertyType);
                                }
                            }
                            else if (dataEncode != null)
                            {
                                value = new DataCipher(dataEncode.Key, dataEncode.KeySize).Decrypt(value.ConvertValue <string>());
                            }
                            else if (prop.ContainAttribute <JsonDocument>())
                            {
                                value = value?.ToString().FromJson(prop.PropertyType);
                            }
                            else
                            {
                                value = MethodHelper.ConvertValue(value, prop.PropertyType);
                            }

                            prop.SetValue(item, value);
                            prop.SetValue(clItem, value);
                        }
                        col++;
                    }
                    //#else
                    //                    var cmReader = new DataRecordExtended(reader);
                    //                    if (!CachedDataRecord.ContainsKey(tType))
                    //                        CachedDataRecord.GetOrAdd(tType, DynamicBuilder.CreateBuilder(cmReader, tType));
                    //                    var x = CachedDataRecord[tType];
                    //                    item = x.Build(cmReader);
                    //                    clItem = !(repository?.IsAttached(item) ?? true) ? x.Build(cmReader) : null;
                    //#endif

                    if (clItem != null && !(repository?.IsAttached(clItem) ?? true))
                    {
                        repository?.AttachNew(clItem);
                    }
                    iList.Add(item);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                reader.Close();
                reader.Dispose();
                if (repository.OpenedDataReaders.ContainsKey(reader))
                {
                    repository.OpenedDataReaders.Remove(reader);
                }
            }

            return(iList);
        }
Esempio n. 30
0
 internal static List <T> DataReaderConverter <T>(Transaction.Transaction repository, IDataReader reader, DbCommandExtended command)
 {
     return((List <T>)DataReaderConverter(repository, reader, command, typeof(T)));
 }
Esempio n. 31
0
        /// <summary>
        /// Обработчик события срабатывания межкадрового таймера 
        /// </summary>
        /// <param name="sender">Отправитель события</param>
        /// <param name="e">Аргументы события</param>
        private void EventHandler_TmrInterFrameDelay_Elapsed(
            object sender, ElapsedEventArgs e)
        {
            Byte[] message;
            Message.Message request;
            Timer tmr = (Timer)sender;
            tmr.Stop();

            // Таймер сработал, значит сообщение (запрос) 
            // принят полностью считаем CRC16            
            message = new byte[_SerialPort.BytesToRead];
            _SerialPort.Read(message, 0, _SerialPort.BytesToRead);

            if (true == Modbus.OSIModel.DataLinkLayer.CRC16.VerefyCRC16(message))
            {
                // Запрос принят корректно
                Byte[] array = new byte[(message.Length - 4)]; //Данные в сообщениии
                Array.Copy(message, 2, array, 0, array.Length); // Выделили данные из сообщения
                
                request = new Message.Message(message[0], message[1], array);
                
                if (request.Address == 0)
                {
                    // Формируем событие приёма широковещаетельного запроса
                    _СurrentTransaction = new Transaction.Transaction(
                        TransactionType.BroadcastMode, request);
                    _СurrentTransaction.TransactionWasEnded += 
                        new EventHandler(EventHandler_СurrentTransaction_TransactionWasEnded);
                    _СurrentTransaction.Start(); // Стартуем транзакцию
                    OnRequestWasRecived(new MessageEventArgs(request));
                    // ??? Можно было бы запустить таймер задержки при широковещаетльном запросе
                    // Сейчас не реализовано. По этому, завершам транзакцию сразу.
                    _СurrentTransaction.Stop(null); // Завершает транзакцию 
                }
                else
                {
                    _СurrentTransaction = new Transaction.Transaction(
                        TransactionType.UnicastMode, request);
                    _СurrentTransaction.TransactionWasEnded +=
                        new EventHandler(EventHandler_СurrentTransaction_TransactionWasEnded);
                    _СurrentTransaction.Start();
                    // Запускаем таймер таймаута ответа подчинённого устройства
                    _TimerTimeoutCurrentTransaction.Start();
                    // Формируем событие приёма адресованного запроса. 
                    // Транзакция здесь продолжается до тех пор, покак не будет
                    // отправлен ответ.
                    OnRequestWasRecived(new MessageEventArgs(request));
                }
            }
            else
            {
                // Принят запрос с неверным CRC16
                OnErrorOccurred(new ErrorOccurredEventArgs
                    (PortError.CheckSumError, "Принят запрос с неверным CRC16"));
            }
            return;
        }
Esempio n. 32
0
 public CodeToDataBaseMergeCollection(Transaction.Transaction provider)
 {
     _provider = provider;
 }