예제 #1
0
    public void Deserialize_ValidMessage_DeserializedMessage()
    {
        var serializer = CreateDeserializer();

        var message = serializer.Deserialize(ValidMessage);

        var expectedMessage = new InputMsg {
            Forename = "Foo", Surename = "Bar", Age = 42
        };

        Assert.Equal(expectedMessage, message);
    }
예제 #2
0
        public TransactionMsg CreateNewTransactionMsg(List <UtxoMsg> utxos, Dictionary <string, long> receiverIdAndValues)
        {
            var outputDac  = new OutputDac();
            var accountDac = new AccountDac();

            var transaction = new TransactionMsg();

            transaction.Timestamp = Time.EpochTime;
            transaction.Locktime  = 0;

            foreach (var utxo in utxos)
            {
                var account = accountDac.SelectById(utxo.AccountId);

                if (account == null || account.WatchedOnly)
                {
                    //TODO: throw exception;
                    return(null);
                }

                var privateKey = account.PrivateKey;
                var inputMsg   = new InputMsg();
                inputMsg.OutputTransactionHash = utxo.TransactionHash;
                inputMsg.OutputIndex           = utxo.OutputIndex;
                inputMsg.UnlockScript          = Script.BuildUnlockScript(utxo.TransactionHash, utxo.OutputIndex, Base16.Decode(privateKey), Base16.Decode(account.PublicKey));
                inputMsg.Size = inputMsg.UnlockScript.Length;

                transaction.Inputs.Add(inputMsg);
                outputDac.UpdateSpentStatus(utxo.TransactionHash, utxo.OutputIndex);
            }

            int index = 0;

            foreach (var key in receiverIdAndValues.Keys)
            {
                var value = receiverIdAndValues[key];

                var outputMsg = new OutputMsg();
                outputMsg.Index      = index;
                outputMsg.Amount     = value;
                outputMsg.LockScript = Script.BuildLockScipt(key);
                outputMsg.Size       = outputMsg.LockScript.Length;

                transaction.Outputs.Add(outputMsg);
                index++;
            }

            transaction.Hash = transaction.GetHash();
            return(transaction);
        }
예제 #3
0
        public static Input ConvertToEntiry(this InputMsg inputMsg, InputExtensionParams inputExtension)
        {
            Input input = new Input();

            input.AccountId             = inputExtension.InputAccountId;
            input.Amount                = inputExtension.InputAmount;
            input.BlockHash             = inputExtension.BlockHash;
            input.IsDiscarded           = false;
            input.OutputIndex           = inputMsg.OutputIndex;
            input.OutputTransactionHash = inputMsg.OutputTransactionHash;
            input.Size            = inputMsg.Size;
            input.TransactionHash = inputExtension.TransactionHash;
            input.UnlockScript    = inputMsg.UnlockScript;
            return(input);
        }
예제 #4
0
        private void cwDetectionStart_Click(object sender, EventArgs e)
        {
            bool isSLCRx     = false;
            int  mid         = 220;
            int  sid         = 1;
            byte channelType = 0;

            this.comm.CMC.TxCurrentTransmissionType = (CommonClass.TransmissionType) this.comm.TxCurrentTransmissionType;
            string protocol = "OSP";

            isSLCRx = this.comm.RxType == CommunicationManager.ReceiverType.SLC;
            ArrayList list = this.comm.m_Protocols.GetDefaultMsgFieldList(isSLCRx, mid, sid, "CW Controller Input_CONFIG", protocol);

            InputMsg[] fieldList = new InputMsg[list.Count];
            for (int i = 0; i < list.Count; i++)
            {
                fieldList[i].messageID    = ((InputMsg)list[i]).messageID;
                fieldList[i].subID        = ((InputMsg)list[i]).subID;
                fieldList[i].messageName  = ((InputMsg)list[i]).messageName;
                fieldList[i].fieldNumber  = ((InputMsg)list[i]).fieldNumber;
                fieldList[i].fieldName    = ((InputMsg)list[i]).fieldName;
                fieldList[i].bytes        = ((InputMsg)list[i]).bytes;
                fieldList[i].datatype     = ((InputMsg)list[i]).datatype;
                fieldList[i].units        = ((InputMsg)list[i]).units;
                fieldList[i].scale        = ((InputMsg)list[i]).scale;
                fieldList[i].defaultValue = ((InputMsg)list[i]).defaultValue;
                fieldList[i].savedValue   = ((InputMsg)list[i]).savedValue;
            }
            try
            {
                string text = this.cwConfigComboBox.Text;
                if (text == string.Empty)
                {
                    return;
                }
                if (text.StartsWith("2:"))
                {
                    fieldList[2].defaultValue = "2";
                    this.comm.CWInterferenceDetectModeIndex = 1;
                }
                else if (text.StartsWith("3:"))
                {
                    fieldList[2].defaultValue = "3";
                    this.comm.CWInterferenceDetectModeIndex = 2;
                }
                else if (text.StartsWith("4:"))
                {
                    fieldList[2].defaultValue = "4";
                    this.comm.CWInterferenceDetectModeIndex = 3;
                }
                else
                {
                    fieldList[2].defaultValue = "0";
                    this.comm.CWInterferenceDetectModeIndex = 0;
                }
                if (this.comm.CWInterferenceDetectModeIndex != 3)
                {
                    this.detectionOnCheckBox.BackgroundBrush = new SolidBrush(Color.Green);
                    this.detectionOnCheckBox.Checked         = true;
                    this.detectionOnCheckBox.Refresh();
                }
                else
                {
                    this.detectionOnCheckBox.BackgroundBrush = new SolidBrush(Color.Gray);
                    this.detectionOnCheckBox.Checked         = false;
                    this.detectionOnCheckBox.Refresh();
                }
            }
            catch (Exception exception)
            {
                string str3 = exception.ToString();
                string str4 = "### Interference Report GUI handler error -- " + str3;
                this.comm.WriteApp(str4);
            }
            string msg = this.comm.m_Protocols.FieldList_to_HexMsgStr(isSLCRx, fieldList, channelType);

            this.comm.WriteData(msg);
        }
예제 #5
0
        public IRpcMethodResult EstimateTxFeeForSendToAddress(string toAddress, long amount, string comment, string commentTo, bool deductFeeFromAmount)
        {
            try
            {
                EstimateTxFeeOM result               = new EstimateTxFeeOM();
                var             utxoComponent        = new UtxoComponent();
                var             txComponent          = new TransactionComponent();
                var             settingComponent     = new SettingComponent();
                var             addressBookComponent = new AddressBookComponent();
                var             accountComponent     = new AccountComponent();

                if (!AccountIdHelper.AddressVerify(toAddress))
                {
                    throw new CommonException(ErrorCode.Service.Transaction.TO_ADDRESS_INVALID);
                }

                var setting   = settingComponent.GetSetting();
                var utxos     = utxoComponent.GetAllConfirmedOutputs();
                var tx        = new TransactionMsg();
                var totalSize = tx.Serialize().Length;

                var output = new OutputMsg();
                output.Amount     = amount;
                output.Index      = 0;
                output.LockScript = Script.BuildLockScipt(toAddress);
                output.Size       = output.LockScript.Length;
                tx.Outputs.Add(output);
                totalSize += output.Serialize().Length;

                var blockComponent  = new BlockComponent();
                var lastBlockHeight = blockComponent.GetLatestHeight();

                var    totalInput  = 0L;
                var    index       = 0;
                double totalAmount = amount;
                double totalFee    = setting.FeePerKB * ((double)totalSize / 1024.0);

                while (index < utxos.Count)
                {
                    var account = accountComponent.GetAccountById(utxos[index].AccountId);

                    if (account != null && !string.IsNullOrWhiteSpace(account.PrivateKey))
                    {
                        var   utxoTX    = txComponent.GetTransactionMsgByHash(utxos[index].TransactionHash);
                        Block utxoBlock = blockComponent.GetBlockEntiytByHash(utxos[index].BlockHash);

                        if (utxoTX == null || utxoBlock == null)
                        {
                            index++;
                            continue;
                        }

                        if (!utxoBlock.IsVerified)
                        {
                            index++;
                            continue;
                        }

                        if (Time.EpochTime < utxoTX.Locktime)
                        {
                            index++;
                            continue;
                        }

                        if (utxoTX.InputCount == 1 && utxoTX.Inputs[0].OutputTransactionHash == Base16.Encode(HashHelper.EmptyHash()))
                        {
                            var blockHeight = utxoBlock.Height;

                            if (lastBlockHeight - blockHeight < 100L)
                            {
                                index++;
                                continue;
                            }
                        }

                        var input = new InputMsg();
                        input.OutputTransactionHash = utxos[index].TransactionHash;
                        input.OutputIndex           = utxos[index].OutputIndex;
                        input.UnlockScript          = Script.BuildUnlockScript(input.OutputTransactionHash, input.OutputIndex, Base16.Decode(decryptPrivateKey(account.PrivateKey)), Base16.Decode(account.PublicKey));
                        input.Size = input.UnlockScript.Length;
                        tx.Inputs.Add(input);

                        var size = input.Serialize().Length;
                        totalSize  += size;
                        totalFee   += setting.FeePerKB * ((double)size / 1024.0);
                        totalInput += utxos[index].Amount;
                    }
                    else
                    {
                        index++;
                        continue;
                    }

                    if (!deductFeeFromAmount)
                    {
                        totalAmount = amount + totalFee;
                    }

                    if (totalInput >= (long)Math.Ceiling(totalAmount))
                    {
                        var size = output.Serialize().Length;

                        if ((totalInput - (long)Math.Ceiling(totalAmount)) > (setting.FeePerKB * (double)size / 1024.0))
                        {
                            totalSize += size;
                            totalFee  += setting.FeePerKB * ((double)size / 1024.0);
                        }

                        break;
                    }

                    index++;
                }

                if (totalInput < totalAmount)
                {
                    throw new CommonException(ErrorCode.Service.Transaction.BALANCE_NOT_ENOUGH);
                }

                if (deductFeeFromAmount)
                {
                    output.Amount -= (long)Math.Ceiling(totalFee);

                    if (output.Amount <= 0)
                    {
                        throw new CommonException(ErrorCode.Service.Transaction.SEND_AMOUNT_LESS_THAN_FEE);
                    }
                }

                result.totalFee  = Convert.ToInt64(totalFee);
                result.totalSize = Convert.ToInt32(totalSize);

                return(Ok(result));
            }
            catch (CommonException ce)
            {
                return(Error(ce.ErrorCode, ce.Message, ce));
            }
            catch (Exception ex)
            {
                return(Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex));
            }
        }
예제 #6
0
        public IRpcMethodResult SendMany(string fromAccount, SendManyOutputIM[] receivers, string[] feeDeductAddresses)
        {
            try
            {
                string result                      = null;
                var    utxoComponent               = new UtxoComponent();
                var    txComponent                 = new TransactionComponent();
                var    settingComponent            = new SettingComponent();
                var    addressBookComponent        = new AddressBookComponent();
                var    accountComponent            = new AccountComponent();
                var    transactionCommentComponent = new TransactionCommentComponent();
                var    blockComponent              = new BlockComponent();
                var    lastBlockHeight             = blockComponent.GetLatestHeight();

                var    setting     = settingComponent.GetSetting();
                var    utxos       = utxoComponent.GetAllConfirmedOutputs();
                var    tx          = new TransactionMsg();
                double totalOutput = 0;
                var    totalSize   = tx.Serialize().Length;

                if (receivers == null || receivers.Length == 0)
                {
                    throw new CommonException(ErrorCode.Service.Transaction.TO_ADDRESS_INVALID);
                }

                foreach (var receiver in receivers)
                {
                    if (!AccountIdHelper.AddressVerify(receiver.address))
                    {
                        throw new CommonException(ErrorCode.Service.Transaction.TO_ADDRESS_INVALID);
                    }

                    var output = new OutputMsg();
                    output.Amount     = receiver.amount;
                    output.Index      = tx.Outputs.Count;
                    output.LockScript = Script.BuildLockScipt(receiver.address);
                    output.Size       = output.LockScript.Length;
                    tx.Outputs.Add(output);

                    totalSize   += output.Serialize().Length;
                    totalOutput += receiver.amount;
                }

                foreach (var address in feeDeductAddresses)
                {
                    if (receivers.Where(r => r.address == address).Count() == 0)
                    {
                        throw new CommonException(ErrorCode.Service.Transaction.FEE_DEDUCT_ADDRESS_INVALID);
                    }
                }

                var    totalInput  = 0L;
                var    index       = 0;
                double totalFee    = setting.FeePerKB * ((double)totalSize / 1024.0);
                double totalAmount = totalOutput;

                while (index < utxos.Count)
                {
                    var account = accountComponent.GetAccountById(utxos[index].AccountId);

                    if (account != null && !string.IsNullOrWhiteSpace(account.PrivateKey))
                    {
                        var   utxoTX    = txComponent.GetTransactionMsgByHash(utxos[index].TransactionHash);
                        Block utxoBlock = blockComponent.GetBlockEntiytByHash(utxos[index].BlockHash);

                        if (utxoTX == null || utxoBlock == null)
                        {
                            index++;
                            continue;
                        }

                        if (!utxoBlock.IsVerified)
                        {
                            index++;
                            continue;
                        }

                        if (Time.EpochTime < utxoTX.Locktime)
                        {
                            index++;
                            continue;
                        }

                        if (utxoTX.InputCount == 1 && utxoTX.Inputs[0].OutputTransactionHash == Base16.Encode(HashHelper.EmptyHash()))
                        {
                            var blockHeight = utxoBlock.Height;

                            if (lastBlockHeight - blockHeight < 100L)
                            {
                                index++;
                                continue;
                            }
                        }

                        var input = new InputMsg();
                        input.OutputTransactionHash = utxos[index].TransactionHash;
                        input.OutputIndex           = utxos[index].OutputIndex;
                        input.UnlockScript          = Script.BuildUnlockScript(input.OutputTransactionHash, input.OutputIndex, Base16.Decode(decryptPrivateKey(account.PrivateKey)), Base16.Decode(account.PublicKey));
                        input.Size = input.UnlockScript.Length;
                        tx.Inputs.Add(input);

                        var size = input.Serialize().Length;
                        totalSize  += size;
                        totalFee   += setting.FeePerKB * ((double)size / 1024.0);
                        totalInput += utxos[index].Amount;
                    }
                    else
                    {
                        index++;
                        continue;
                    }

                    if (feeDeductAddresses == null || feeDeductAddresses.Length == 0)
                    {
                        totalAmount = totalOutput + totalFee;
                    }

                    if (totalInput >= (long)Math.Ceiling(totalAmount))
                    {
                        var size = tx.Outputs[0].Serialize().Length;

                        if ((totalInput - (long)Math.Ceiling(totalAmount)) > (setting.FeePerKB * (double)size / 1024.0))
                        {
                            totalSize += size;
                            totalFee  += setting.FeePerKB * ((double)size / 1024.0);

                            if (feeDeductAddresses == null || feeDeductAddresses.Length == 0)
                            {
                                totalAmount = totalOutput + totalFee;
                            }


                            var newAccount = accountComponent.GenerateNewAccount();

                            if (setting.Encrypt)
                            {
                                if (!string.IsNullOrWhiteSpace(_cache.Get <string>("WalletPassphrase")))
                                {
                                    newAccount.PrivateKey = AES128.Encrypt(newAccount.PrivateKey, _cache.Get <string>("WalletPassphrase"));
                                    accountComponent.UpdatePrivateKeyAr(newAccount);
                                }
                                else
                                {
                                    throw new CommonException(ErrorCode.Service.Wallet.WALLET_HAS_BEEN_LOCKED);
                                }
                            }

                            var newOutput = new OutputMsg();
                            newOutput.Amount     = totalInput - (long)Math.Ceiling(totalAmount);
                            newOutput.Index      = tx.Outputs.Count;
                            newOutput.LockScript = Script.BuildLockScipt(newAccount.Id);
                            newOutput.Size       = newOutput.LockScript.Length;
                            tx.Outputs.Add(newOutput);
                        }

                        break;
                    }

                    index++;
                }

                if (totalInput < totalAmount)
                {
                    throw new CommonException(ErrorCode.Service.Transaction.BALANCE_NOT_ENOUGH);
                }

                if (feeDeductAddresses != null && feeDeductAddresses.Length > 0)
                {
                    var averageFee = totalFee / feeDeductAddresses.Length;

                    for (int i = 0; i < receivers.Length; i++)
                    {
                        if (feeDeductAddresses.Contains(receivers[i].address))
                        {
                            tx.Outputs[i].Amount -= (long)Math.Ceiling(averageFee);

                            if (tx.Outputs[i].Amount <= 0)
                            {
                                throw new CommonException(ErrorCode.Service.Transaction.SEND_AMOUNT_LESS_THAN_FEE);
                            }
                        }
                    }
                }

                tx.Timestamp = Time.EpochTime;
                tx.Hash      = tx.GetHash();
                txComponent.AddTransactionToPool(tx);
                Startup.P2PBroadcastTransactionAction(tx.Hash);
                result = tx.Hash;

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

                    if (!string.IsNullOrWhiteSpace(receiver.tag))
                    {
                        addressBookComponent.SetTag(receiver.address, receiver.tag);
                    }

                    if (!string.IsNullOrWhiteSpace(receiver.comment))
                    {
                        transactionCommentComponent.Add(tx.Hash, i, receiver.comment);
                    }
                }

                return(Ok(result));
            }
            catch (CommonException ce)
            {
                return(Error(ce.ErrorCode, ce.Message, ce));
            }
            catch (Exception ex)
            {
                return(Error(ErrorCode.UNKNOWN_ERROR, ex.Message, ex));
            }
        }
예제 #7
0
 protected void RecordInput(InputMsg recievedMsg)
 {
     Raise(new InputMsg(recievedMsg));
 }
예제 #8
0
        /// <summary>
        /// 创建新的区块
        /// </summary>
        /// <param name="minerName"></param>
        /// <param name="generatorId"></param>
        /// <param name="accountId"></param>
        /// <returns></returns>
        public BlockMsg CreateNewBlock(string minerName, string generatorId, string remark = null, string accountId = null)
        {
            var accountDac      = new AccountDac();
            var blockDac        = new BlockDac();
            var outputDac       = new OutputDac();
            var txDac           = new TransactionDac();
            var txPool          = TransactionPool.Instance;
            var transactionMsgs = new List <TransactionMsg>();

            long   lastBlockHeight    = -1;
            string lastBlockHash      = Base16.Encode(HashHelper.EmptyHash());
            long   lastBlockBits      = -1;
            string lastBlockGenerator = null;

            //获取最后一个区块
            var blockEntity = blockDac.SelectLast();

            if (blockEntity != null)
            {
                lastBlockHeight    = blockEntity.Height;
                lastBlockHash      = blockEntity.Hash;
                lastBlockBits      = blockEntity.Bits;
                lastBlockGenerator = blockEntity.GeneratorId;
            }

            long totalSize    = 0;
            long maxSize      = BlockSetting.MAX_BLOCK_SIZE - (1 * 1024);
            var  poolItemList = txPool.MainPool.OrderByDescending(t => t.FeeRate).ToList();
            var  index        = 0;

            while (totalSize < maxSize && index < poolItemList.Count)
            {
                var tx = poolItemList[index].Transaction;

                if (tx != null && transactionMsgs.Where(t => t.Hash == tx.Hash).Count() == 0)
                {
                    if (txDac.SelectByHash(tx.Hash) == null)
                    {
                        transactionMsgs.Add(tx);
                        totalSize += tx.Size;
                    }
                    else
                    {
                        txPool.RemoveTransaction(tx.Hash);
                    }
                }
                else
                {
                    break;
                }

                index++;
            }


            var minerAccount = accountDac.SelectDefaultAccount();

            if (accountId != null)
            {
                var account = accountDac.SelectById(accountId);

                if (account != null && !string.IsNullOrWhiteSpace(account.PrivateKey))
                {
                    minerAccount = account;
                }
            }

            var minerAccountId = minerAccount.Id;

            BlockMsg       newBlockMsg = new BlockMsg();
            BlockHeaderMsg headerMsg   = new BlockHeaderMsg();

            headerMsg.Hash              = Base16.Encode(HashHelper.EmptyHash());
            headerMsg.GeneratorId       = generatorId;
            newBlockMsg.Header          = headerMsg;
            headerMsg.Height            = lastBlockHeight + 1;
            headerMsg.PreviousBlockHash = lastBlockHash;

            if (headerMsg.Height == 0)
            {
                minerAccountId = BlockSetting.GenesisBlockReceiver;
                remark         = BlockSetting.GenesisBlockRemark;
            }

            long totalAmount = 0;
            long totalFee    = 0;

            foreach (var tx in transactionMsgs)
            {
                long totalInputsAmount = 0L;
                long totalOutputAmount = 0L;

                foreach (var input in tx.Inputs)
                {
                    var utxo = outputDac.SelectByHashAndIndex(input.OutputTransactionHash, input.OutputIndex);

                    if (utxo != null)
                    {
                        totalInputsAmount += utxo.Amount;
                    }
                }

                foreach (var output in tx.Outputs)
                {
                    totalOutputAmount += output.Amount;
                }

                totalAmount += totalOutputAmount;
                totalFee    += (totalInputsAmount - totalOutputAmount);
            }

            //var work = new POW(headerMsg.Height);
            BlockMsg prevBlockMsg     = null;
            BlockMsg prevStepBlockMsg = null;

            if (blockEntity != null)
            {
                prevBlockMsg = this.convertEntityToBlockMsg(blockEntity);
            }

            if (headerMsg.Height >= POC.DIFFIUCLTY_ADJUST_STEP)
            {
                prevStepBlockMsg = this.GetBlockMsgByHeight(headerMsg.Height - POC.DIFFIUCLTY_ADJUST_STEP - 1);
            }

            var newBlockReward = POC.GetNewBlockReward(headerMsg.Height);

            headerMsg.Bits             = POC.CalculateBaseTarget(headerMsg.Height, prevBlockMsg, prevStepBlockMsg);
            headerMsg.TotalTransaction = transactionMsgs.Count + 1;

            var coinbaseTxMsg = new TransactionMsg();

            coinbaseTxMsg.Timestamp = Time.EpochTime;
            coinbaseTxMsg.Locktime  = 0;

            var coinbaseInputMsg = new InputMsg();

            coinbaseTxMsg.Inputs.Add(coinbaseInputMsg);
            coinbaseInputMsg.OutputIndex           = 0;
            coinbaseInputMsg.OutputTransactionHash = Base16.Encode(HashHelper.EmptyHash());
            coinbaseInputMsg.UnlockScript          = Script.BuildMinerScript(minerName, remark);
            coinbaseInputMsg.Size = coinbaseInputMsg.UnlockScript.Length;

            var coinbaseOutputMsg = new OutputMsg();

            coinbaseTxMsg.Outputs.Add(coinbaseOutputMsg);
            coinbaseOutputMsg.Amount     = newBlockReward + totalFee;
            coinbaseOutputMsg.LockScript = Script.BuildLockScipt(minerAccountId);
            coinbaseOutputMsg.Size       = coinbaseOutputMsg.LockScript.Length;
            coinbaseOutputMsg.Index      = 0;

            coinbaseTxMsg.Hash = coinbaseTxMsg.GetHash();

            newBlockMsg.Transactions.Insert(0, coinbaseTxMsg);

            foreach (var tx in transactionMsgs)
            {
                newBlockMsg.Transactions.Add(tx);
            }

            headerMsg.PayloadHash = newBlockMsg.GetPayloadHash();
            var dsa        = ECDsa.ImportPrivateKey(Base16.Decode(minerAccount.PrivateKey));
            var signResult = dsa.SingnData(Base16.Decode(headerMsg.PayloadHash));

            headerMsg.BlockSignature   = Base16.Encode(signResult);
            headerMsg.BlockSigSize     = headerMsg.BlockSignature.Length;
            headerMsg.TotalTransaction = newBlockMsg.Transactions.Count;
            return(newBlockMsg);
        }
예제 #9
0
        private void OkButton_Click(object sender, EventArgs e)
        {
            bool isSLCRx     = false;
            int  mid         = 0xe4;
            int  sid         = 0;
            byte channelType = 0;

            try
            {
                this.comm.CMC.TxCurrentTransmissionType = (CommonClass.TransmissionType) this.comm.TxCurrentTransmissionType;
                string protocol = "OSP";
                isSLCRx = this.comm.RxType == CommunicationManager.ReceiverType.SLC;
                ArrayList  list = this.comm.m_Protocols.GetDefaultMsgFieldList(isSLCRx, mid, sid, "Encryption Control Settings", protocol);
                InputMsg[] ltc  = new InputMsg[list.Count];
                for (int i = 0; i < list.Count; i++)
                {
                    ltc[i].messageID    = ((InputMsg)list[i]).messageID;
                    ltc[i].subID        = ((InputMsg)list[i]).subID;
                    ltc[i].messageName  = ((InputMsg)list[i]).messageName;
                    ltc[i].fieldNumber  = ((InputMsg)list[i]).fieldNumber;
                    ltc[i].fieldName    = ((InputMsg)list[i]).fieldName;
                    ltc[i].bytes        = ((InputMsg)list[i]).bytes;
                    ltc[i].datatype     = ((InputMsg)list[i]).datatype;
                    ltc[i].units        = ((InputMsg)list[i]).units;
                    ltc[i].scale        = ((InputMsg)list[i]).scale;
                    ltc[i].defaultValue = ((InputMsg)list[i]).defaultValue;
                    ltc[i].savedValue   = ((InputMsg)list[i]).savedValue;
                }
                try
                {
                    this.ConvertCheckBoxesToEcryptCtrlMsgStruct(this.EncryCtrlDataGridView, ref EcryptCtrlMsg);
                    this.UpdateLocalMsgCopyWithEncCtrlSettings(ref ltc, EcryptCtrlMsg);
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.ToString());
                }
                string msg = this.comm.m_Protocols.FieldList_to_HexMsgStr(isSLCRx, ltc, channelType);
                if (clsGlobal.PerformOnAll)
                {
                    foreach (string str3 in clsGlobal.g_objfrmMDIMain.PortManagerHash.Keys)
                    {
                        PortManager manager = (PortManager)clsGlobal.g_objfrmMDIMain.PortManagerHash[str3];
                        if ((manager != null) && manager.comm.IsSourceDeviceOpen())
                        {
                            manager.comm.WriteData(msg);
                        }
                    }
                    clsGlobal.PerformOnAll = false;
                }
                else
                {
                    this.comm.WriteData(msg);
                }
            }
            catch (Exception exception2)
            {
                if (!this.comm.IsSourceDeviceOpen())
                {
                    MessageBox.Show("Source Device is not open", "frmEncryCtrl: OkButton_Click()");
                }
                else
                {
                    MessageBox.Show(exception2.ToString(), "frmEncryCtrl: OkButton_Click()");
                }
            }
        }
예제 #10
0
        public TransactionMsg CreateNewTransactionMsg(string senderAccountId, Dictionary <string, long> receiverIdAndValues, long fee)
        {
            var outputDac  = new OutputDac();
            var accountDac = new AccountDac();

            var account = accountDac.SelectById(senderAccountId);

            if (account == null || account.WatchedOnly)
            {
                //TODO: throw exception;
                return(null);
            }

            var  balance     = UtxoSet.Instance.GetAccountBlanace(senderAccountId, true);
            long totalOutput = fee;
            long totalInput  = 0;

            foreach (var key in receiverIdAndValues.Keys)
            {
                totalOutput += receiverIdAndValues[key];
            }

            if (totalOutput > balance)
            {
                //TODO: throw exception
                return(null);
            }

            var transaction = new TransactionMsg();

            transaction.Timestamp = Time.EpochTime;
            transaction.Locktime  = 0;

            var outputs = outputDac.SelectUnspentByReceiverId(senderAccountId);

            foreach (var output in outputs)
            {
                var inputMsg = new InputMsg();
                inputMsg.OutputTransactionHash = output.TransactionHash;
                inputMsg.OutputIndex           = output.Index;
                inputMsg.UnlockScript          = Script.BuildUnlockScript(output.TransactionHash, output.Index, Base16.Decode(account.PrivateKey), Base16.Decode(account.PublicKey));
                inputMsg.Size = inputMsg.UnlockScript.Length;

                transaction.Inputs.Add(inputMsg);
                outputDac.UpdateSpentStatus(output.TransactionHash, output.Index);

                totalInput += output.Amount;
                if (totalInput >= totalOutput)
                {
                    break;
                }
            }

            int index = 0;

            foreach (var key in receiverIdAndValues.Keys)
            {
                var value = receiverIdAndValues[key];

                var outputMsg = new OutputMsg();
                outputMsg.Index      = index;
                outputMsg.Amount     = value;
                outputMsg.LockScript = Script.BuildLockScipt(key);
                outputMsg.Size       = outputMsg.LockScript.Length;

                transaction.Outputs.Add(outputMsg);
                index++;
            }

            if (totalInput > totalOutput)
            {
                var value = totalInput - totalOutput;

                var outputMsg = new OutputMsg();
                outputMsg.Index      = index;
                outputMsg.Amount     = value;
                outputMsg.LockScript = Script.BuildLockScipt(senderAccountId);
                outputMsg.Size       = outputMsg.LockScript.Length;

                transaction.Outputs.Add(outputMsg);
                index++;
            }

            transaction.Hash = transaction.GetHash();

            return(transaction);
        }
예제 #11
0
        public BlockMsg CreateNewBlock(string minerName, string accountId = null)
        {
            var accountDac      = new AccountDac();
            var blockDac        = new BlockDac();
            var outputDac       = new OutputDac();
            var txDac           = new TransactionDac();
            var txPool          = TransactionPool.Instance;
            var transactionMsgs = new List <TransactionMsg>();

            long   lastBlockHeight = -1;
            string lastBlockHash   = Base16.Encode(HashHelper.EmptyHash());
            long   lastBlockBits   = -1;

            var blockEntity = blockDac.SelectLast();

            if (blockEntity != null)
            {
                lastBlockHeight = blockEntity.Height;
                lastBlockHash   = blockEntity.Hash;
                lastBlockBits   = blockEntity.Bits;
            }

            long totalSize    = 0;
            long maxSize      = BlockSetting.MAX_BLOCK_SIZE - (500 * 1024);
            var  poolItemList = txPool.MainPool.OrderByDescending(t => t.FeeRate).ToList();
            var  index        = 0;

            while (totalSize < maxSize && index < poolItemList.Count)
            {
                var tx = poolItemList[index].Transaction;

                if (tx != null && transactionMsgs.Where(t => t.Hash == tx.Hash).Count() == 0)
                {
                    if (txDac.SelectByHash(tx.Hash) == null)
                    {
                        transactionMsgs.Add(tx);
                        totalSize += tx.Size;
                    }
                    else
                    {
                        txPool.RemoveTransaction(tx.Hash);
                    }
                }
                else
                {
                    break;
                }

                index++;
            }


            var minerAccount = accountDac.SelectDefaultAccount();

            if (accountId != null)
            {
                var account = accountDac.SelectById(accountId);

                if (account != null && !string.IsNullOrWhiteSpace(account.PrivateKey))
                {
                    minerAccount = account;
                }
            }

            BlockMsg       newBlockMsg = new BlockMsg();
            BlockHeaderMsg headerMsg   = new BlockHeaderMsg();

            newBlockMsg.Header          = headerMsg;
            headerMsg.Height            = lastBlockHeight + 1;
            headerMsg.PreviousBlockHash = lastBlockHash;


            long totalAmount = 0;
            long totalFee    = 0;

            foreach (var tx in transactionMsgs)
            {
                long totalInputsAmount = 0L;
                long totalOutputAmount = 0L;

                foreach (var input in tx.Inputs)
                {
                    var utxo = outputDac.SelectByHashAndIndex(input.OutputTransactionHash, input.OutputIndex);

                    if (utxo != null)
                    {
                        totalInputsAmount += utxo.Amount;
                    }
                }

                foreach (var output in tx.Outputs)
                {
                    totalOutputAmount += output.Amount;
                }

                totalAmount += totalOutputAmount;
                totalFee    += (totalInputsAmount - totalOutputAmount);
            }

            var      work = new POW(headerMsg.Height);
            BlockMsg previous4032Block = null;

            if (headerMsg.Height > POW.DiffiucltyAdjustStep)
            {
                previous4032Block = this.GetBlockMsgByHeight(headerMsg.Height - POW.DiffiucltyAdjustStep);
            }

            var newBlockReward = work.GetNewBlockReward();

            headerMsg.Bits             = work.CalculateNextWorkTarget(lastBlockHeight, lastBlockBits, previous4032Block);
            headerMsg.TotalTransaction = transactionMsgs.Count + 1;

            var coinbaseTxMsg = new TransactionMsg();

            coinbaseTxMsg.Timestamp = Time.EpochTime;
            coinbaseTxMsg.Locktime  = 0;

            var coinbaseInputMsg = new InputMsg();

            coinbaseTxMsg.Inputs.Add(coinbaseInputMsg);
            coinbaseInputMsg.OutputIndex           = 0;
            coinbaseInputMsg.OutputTransactionHash = Base16.Encode(HashHelper.EmptyHash());
            coinbaseInputMsg.UnlockScript          = Script.BuildMinerScript(minerName);
            coinbaseInputMsg.Size = coinbaseInputMsg.UnlockScript.Length;

            var coinbaseOutputMsg = new OutputMsg();

            coinbaseTxMsg.Outputs.Add(coinbaseOutputMsg);
            coinbaseOutputMsg.Amount     = newBlockReward + totalFee;
            coinbaseOutputMsg.LockScript = Script.BuildLockScipt(minerAccount.Id);
            coinbaseOutputMsg.Size       = coinbaseOutputMsg.LockScript.Length;
            coinbaseOutputMsg.Index      = 0;

            coinbaseTxMsg.Hash = coinbaseTxMsg.GetHash();

            newBlockMsg.Transactions.Insert(0, coinbaseTxMsg);

            foreach (var tx in transactionMsgs)
            {
                newBlockMsg.Transactions.Add(tx);
            }

            return(newBlockMsg);
        }
예제 #12
0
        /// <summary>
        /// 创建新的区块
        /// </summary>
        /// <param name="minerName"></param>
        /// <param name="generatorId"></param>
        /// <param name="accountId"></param>
        /// <returns></returns>
        public BlockMsg CreateNewBlock(string minerName, string generatorId, string remark = null, string accountId = null)
        {
            var accountDac      = AccountDac.Default;
            var blockDac        = BlockDac.Default;
            var txDac           = TransactionDac.Default;
            var txPool          = TransactionPool.Instance;
            var txComponent     = new TransactionComponent();
            var transactionMsgs = new List <TransactionMsg>();

            long   lastBlockHeight    = -1;
            string lastBlockHash      = Base16.Encode(HashHelper.EmptyHash());
            long   lastBlockBits      = -1;
            string lastBlockGenerator = null;

            //获取最后一个区块
            var blockEntity = blockDac.SelectLast();

            if (blockEntity != null)
            {
                lastBlockHeight    = blockEntity.Header.Height;
                lastBlockHash      = blockEntity.Header.Hash;
                lastBlockBits      = blockEntity.Header.Bits;
                lastBlockGenerator = blockEntity.Header.GeneratorId;
            }

            long totalSize   = 0;
            long totalInput  = 0;
            long totalOutput = 0;
            long totalAmount = 0;
            long totalFee    = 0;

            long maxSize = Consensus.BlockSetting.MAX_BLOCK_SIZE - (1 * 1024);

            //获取待打包的交易
            var txs = txPool.GetTxsWithoutRepeatCost(10, maxSize);

            var hashIndexs = new List <string>();

            foreach (var tx in txs)
            {
                totalSize   += tx.Size;
                totalInput  += tx.InputCount;
                totalOutput += tx.OutputCount;
                hashIndexs.AddRange(tx.Inputs.Select(x => $"{x.OutputTransactionHash}_{x.OutputIndex}"));
                long totalOutputAmount = tx.Outputs.Sum(x => x.Amount);
                totalAmount += totalOutputAmount;
            }
            var utxos            = UtxoSetDac.Default.Get(hashIndexs);
            var totalInputAmount = utxos.Sum(x => x.Amount);

            totalFee = totalInputAmount - totalAmount;

            transactionMsgs.AddRange(txs);

            var accounts     = AccountDac.Default.SelectAll();
            var minerAccount = accounts.OrderBy(x => x.Timestamp).FirstOrDefault();

            if (accountId != null)
            {
                var account = accounts.FirstOrDefault(x => x.Id == accountId);

                if (account != null && !string.IsNullOrWhiteSpace(account.PrivateKey))
                {
                    minerAccount = account;
                }
            }

            var            minerAccountId = minerAccount.Id;
            BlockMsg       newBlockMsg    = new BlockMsg();
            BlockHeaderMsg headerMsg      = new BlockHeaderMsg();

            headerMsg.Hash              = Base16.Encode(HashHelper.EmptyHash());
            headerMsg.GeneratorId       = generatorId;
            newBlockMsg.Header          = headerMsg;
            headerMsg.Height            = lastBlockHeight + 1;
            headerMsg.PreviousBlockHash = lastBlockHash;

            if (headerMsg.Height == 0)
            {
                minerAccountId = Consensus.BlockSetting.GenesisBlockReceiver;
                remark         = Consensus.BlockSetting.GenesisBlockRemark;
            }

            BlockMsg prevBlockMsg     = null;
            BlockMsg prevStepBlockMsg = null;

            if (blockEntity != null)
            {
                prevBlockMsg = blockEntity;
            }

            if (headerMsg.Height >= POC.DIFFIUCLTY_ADJUST_STEP)
            {
                var prevStepHeight = 0L;
                if (!GlobalParameters.IsTestnet && headerMsg.Height <= POC.DIFFICULTY_CALCULATE_LOGIC_ADJUST_HEIGHT)
                {
                    prevStepHeight = headerMsg.Height - POC.DIFFIUCLTY_ADJUST_STEP - 1;
                }
                else
                {
                    prevStepHeight = headerMsg.Height - POC.DIFFIUCLTY_ADJUST_STEP;
                }
                prevStepBlockMsg = blockDac.SelectByHeight(prevStepHeight);
            }

            var newBlockReward = POC.GetNewBlockReward(headerMsg.Height);

            headerMsg.Bits             = POC.CalculateBaseTarget(headerMsg.Height, prevBlockMsg, prevStepBlockMsg);
            headerMsg.TotalTransaction = transactionMsgs.Count + 1;

            var coinbaseTxMsg = new TransactionMsg();

            coinbaseTxMsg.Timestamp = Time.EpochTime;
            coinbaseTxMsg.Locktime  = 0;

            var coinbaseInputMsg = new InputMsg();

            coinbaseTxMsg.Inputs.Add(coinbaseInputMsg);
            coinbaseInputMsg.OutputIndex           = 0;
            coinbaseInputMsg.OutputTransactionHash = Base16.Encode(HashHelper.EmptyHash());
            coinbaseInputMsg.UnlockScript          = Script.BuildMinerScript(minerName, remark);
            coinbaseInputMsg.Size = coinbaseInputMsg.UnlockScript.Length;

            var coinbaseOutputMsg = new OutputMsg();

            coinbaseTxMsg.Outputs.Add(coinbaseOutputMsg);
            coinbaseOutputMsg.Amount     = newBlockReward + totalFee;
            coinbaseOutputMsg.LockScript = Script.BuildLockScipt(minerAccountId);
            coinbaseOutputMsg.Size       = coinbaseOutputMsg.LockScript.Length;
            coinbaseOutputMsg.Index      = 0;

            if (newBlockReward < 0 || totalFee < 0 || coinbaseOutputMsg.Amount < 0)
            {
                LogHelper.Warn($"newBlockReward:{newBlockReward}");
                LogHelper.Warn($"totalFee:{totalFee}");
                LogHelper.Warn($"coinbaseOutputMsg.Amount:{coinbaseOutputMsg.Amount}");
                throw new CommonException(ErrorCode.Engine.Transaction.Verify.COINBASE_OUTPUT_AMOUNT_ERROR);
            }

            coinbaseTxMsg.Hash = coinbaseTxMsg.GetHash();

            newBlockMsg.Transactions.Insert(0, coinbaseTxMsg);


            foreach (var tx in transactionMsgs)
            {
                newBlockMsg.Transactions.Add(tx);
            }

            headerMsg.PayloadHash = newBlockMsg.GetPayloadHash();

            LogHelper.Warn($"{headerMsg.Height}::{headerMsg.PayloadHash}");
            LogHelper.Warn($"PayloadHash::{headerMsg.PayloadHash}");
            LogHelper.Warn($"BlockSignature::{headerMsg.BlockSignature}");
            LogHelper.Warn($"miner::{minerName}");

            headerMsg.BlockSignature   = Base16.Encode(HashHelper.EmptyHash());
            headerMsg.BlockSigSize     = headerMsg.BlockSignature.Length;
            headerMsg.TotalTransaction = newBlockMsg.Transactions.Count;
            return(newBlockMsg);
        }