Exemple #1
0
        public IssueTransaction MakeTransaction(IssueTransaction transaction, UInt160 changeAddress = null,
                                                Fixed8 fee = default(Fixed8))
        {
            this.ThrowIfWalletIsNotOpen();

            return(this.currentWallet.MakeTransaction(transaction, changeAddress, fee));
        }
Exemple #2
0
        public void SystemFee_Get_Version_0_Coin()
        {
            uut         = TestUtils.GetIssueTransaction(false, 10, Blockchain.UtilityToken.Hash);
            uut.Version = 0;

            uut.SystemFee.Should().Be(Fixed8.Zero);
        }
Exemple #3
0
 private void 资产分发IToolStripMenuItem_Click(object sender, EventArgs e)
 {
     using (IssueDialog dialog = new IssueDialog())
     {
         if (dialog.ShowDialog() != DialogResult.OK)
         {
             return;
         }
         IssueTransaction tx = dialog.GetTransaction();
         if (tx == null)
         {
             return;
         }
         //TODO: 检查是否符合规则,如是否超过总量、分发方式是否符合约定等;
         SignatureContext context = new SignatureContext(tx);
         Program.CurrentWallet.Sign(context);
         if (context.Completed)
         {
             context.Signable.Scripts = context.GetScripts();
             InformationBox.Show(context.Signable.ToArray().ToHexString(), "分发交易构造完成,并已完整签名,可以广播。");
         }
         else
         {
             InformationBox.Show(context.ToString(), "分发交易构造完成,但签名信息还不完整。");
         }
     }
 }
Exemple #4
0
        public void SystemFee_Get_Version_0_OtherAsset()
        {
            uut         = TestUtils.GetIssueTransaction(false, 10, new UInt256(TestUtils.GetByteArray(32, 0x42)));
            uut.Version = 0;

            uut.SystemFee.Should().Be(Fixed8.FromDecimal(500));
        }
Exemple #5
0
 public void GetScriptHashesForVerifying()
 {
     TestUtils.SetupTestBlockchain(UInt256.Zero);
     uut = TestUtils.GetIssueTransaction(false, 10, Blockchain.UtilityToken.Hash);
     UInt160[] res = uut.GetScriptHashesForVerifying();
     res.Length.Should().Be(1);
     res[0].Should().Be(new UInt160(TestUtils.GetByteArray(20, 0xe7)));
 }
Exemple #6
0
        public void GetScriptHashesForVerifying_ThrowsException_NullAsset()
        {
            TestUtils.SetupTestBlockchain(UInt256.Zero);
            uut = TestUtils.GetIssueTransaction(false, 10, UInt256.Zero);
            Action test = () => uut.GetScriptHashesForVerifying();

            test.ShouldThrow <InvalidOperationException>();
        }
Exemple #7
0
        /// <summary>
        /// 分发资产
        /// </summary>
        /// <param name="_params[0]">资产 ID</param>
        /// <param name="_params[1]">数组{"address": \<收款地址>,"value": \<转账金额>}</param>
        /// <returns>交易</returns>
        private JObject SendIssueTransaction(JArray _params)
        {
            if (wallet == null || walletTimeLock.IsLocked())
            {
                throw new RpcException(-400, "Access denied");
            }
            else
            {
                UInt256 asset_id = UInt256.Parse(_params[0].AsString());
                JArray  to       = (JArray)_params[1];
                if (to.Count == 0)
                {
                    throw new RpcException(-32602, "Invalid params");
                }
                TransactionOutput[] outputs = new TransactionOutput[to.Count];
                for (int i = 0; i < to.Count; i++)
                {
                    outputs[i] = new TransactionOutput
                    {
                        AssetId    = asset_id,
                        Value      = Fixed8.Parse(to[i]["value"].AsString()),
                        ScriptHash = to[i]["address"].AsString().ToScriptHash()
                    };
                }
                IssueTransaction tx = wallet.MakeTransaction(new IssueTransaction
                {
                    Version = 1,
                    Outputs = outputs
                }, fee: Fixed8.One);
                if (tx == null)
                {
                    throw new RpcException(-300, "Insufficient funds");
                }
                ContractParametersContext context = new ContractParametersContext(tx);
                wallet.Sign(context);
                if (context.Completed)
                {
                    tx.Witnesses = context.GetWitnesses();

                    if (tx.Size > Transaction.MaxTransactionSize)
                    {
                        throw new RpcException(-301, "The size of the free transaction must be less than 102400 bytes");
                    }

                    wallet.ApplyTransaction(tx);
                    system.LocalNode.Tell(new LocalNode.Relay {
                        Inventory = tx
                    });
                    return(tx.ToJson());
                }
                else
                {
                    return(context.ToJson());
                }
            }
        }
Exemple #8
0
        public async Task Persist_IssueTx_CallsIssueTxPersister()
        {
            var input = new IssueTransaction();
            var issueTxPersisterMock = AutoMockContainer.GetMock <ITransactionPersister <IssueTransaction> >();
            var testee = AutoMockContainer.Create <TransactionPersister>();

            await testee.Persist(input);

            issueTxPersisterMock.Verify(m => m.Persist(input));
        }
Exemple #9
0
        public async Task Process_IssueTx_CallsIssueTxProcessor()
        {
            var input = new IssueTransaction();
            var issueTxProcessorMock = AutoMockContainer.GetMock <IProcessor <IssueTransaction> >();
            var testee = AutoMockContainer.Create <TransactionProcessor>();

            await testee.Process(input);

            issueTxProcessorMock.Verify(m => m.Process(input));
        }
Exemple #10
0
        public Asset IssueAsset(PrivateKeyAccount account,
                                string name, string description, decimal quantity, byte decimals, bool reissuable, byte[] script = null, decimal fee = 1m)
        {
            var tx = new IssueTransaction(account.PublicKey, name, description, quantity, decimals, reissuable, ChainId, fee, script);

            tx.Sign(account);
            var response = Broadcast(tx);
            var assetId  = response.ParseJsonObject().GetString("id");

            return(new Asset(assetId, name, decimals, script));
        }
Exemple #11
0
        public void SerializeDeserialize_IssueTransaction()
        {
            var original = new IssueTransaction()
            {
                Version = 0x00,
            };

            FillRandomTx(original);

            var ret   = _serializer.Serialize(original);
            var copy  = _deserializer.Deserialize <Transaction>(ret);
            var copy2 = _deserializer.Deserialize <IssueTransaction>(ret);

            // Check base data

            EqualTx(original, copy, copy2);
        }
Exemple #12
0
        /// <summary>
        /// This transaction sends the initial NEO Amount to a contract that
        /// controlled by the seed validators.
        /// </summary>
        /// <returns>The genesis issue transaction.</returns>
        public static IssueTransaction GenesisIssueTransaction()
        {
            var transactionOutput = GenesisGoverningTokenTransactionOutput();
            var genesisWitness    = GenesisWitness();
            var issueTransaction  = new IssueTransaction
            {
                Attributes = new TransactionAttribute[0],
                Inputs     = new CoinReference[0],
                Outputs    = new[] {
                    transactionOutput
                },
                Witness = new[] {
                    genesisWitness
                }
            };

            return(issueTransaction);
        }
Exemple #13
0
 private bool AddTransaction(Transaction tx)
 {
     if (Blockchain.Default == null)
     {
         return(false);
     }
     lock (MemoryPool)
     {
         if (MemoryPool.ContainsKey(tx.Hash))
         {
             return(false);
         }
         if (MemoryPool.Values.SelectMany(p => p.GetAllInputs()).Intersect(tx.GetAllInputs()).Count() > 0)
         {
             return(false);
         }
         if (Blockchain.Default.ContainsTransaction(tx.Hash))
         {
             return(false);
         }
         if (tx is IssueTransaction)
         {
             IssueTransaction issue = (IssueTransaction)tx;
             if (!issue.Verify(true))
             {
                 return(false);
             }
         }
         else
         {
             if (!tx.Verify())
             {
                 return(false);
             }
         }
         AddingTransactionEventArgs args = new AddingTransactionEventArgs(tx);
         AddingTransaction?.Invoke(this, args);
         if (!args.Cancel)
         {
             MemoryPool.Add(tx.Hash, tx);
         }
         return(!args.Cancel);
     }
 }
        private void button2_Click(object sender, EventArgs e)
        {
            RegisterTransaction antshare = textBox3.Text.HexToBytes().AsSerializable <RegisterTransaction>();

            using (IssueDialog dialog = new IssueDialog(antshare))
            {
                if (dialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                IssueTransaction tx = dialog.GetTransaction();
                if (tx.Outputs.Sum(p => p.Value) != antshare.Amount)
                {
                    MessageBox.Show("发行量不等于总量!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                SignatureContext context = new SignatureContext(tx);
                InformationBox.Show(context.ToString(), "小蚁股发行签名上下文:");
            }
        }
        public async Task Persist_IssueAssets_IncreaseAvailable()
        {
            var assetId               = new UInt256(RandomByteArray(32));
            var oldAvailability       = RandomInt(10000);
            var changeInAvailability1 = RandomInt(10000);
            var changeInAvailability2 = RandomInt(10000);
            var input = new IssueTransaction
            {
                Outputs = new[]
                {
                    new TransactionOutput
                    {
                        AssetId    = assetId,
                        ScriptHash = new UInt160(RandomByteArray(20)),
                        Value      = new Fixed8(changeInAvailability1)
                    },
                    new TransactionOutput
                    {
                        AssetId    = assetId,
                        ScriptHash = new UInt160(RandomByteArray(20)),
                        Value      = new Fixed8(changeInAvailability2)
                    }
                }
            };
            var asset = new Asset
            {
                Available = new Fixed8(oldAvailability)
            };
            var repositoryMock = AutoMockContainer.GetMock <IRepository>();

            repositoryMock.Setup(m => m.GetAsset(It.Is <UInt256>(u => u.Equals(assetId)))).ReturnsAsync(asset);
            var testee = AutoMockContainer.Create <IssueTransactionPersister>();

            await testee.Persist(input);

            repositoryMock.Verify(m => m.AddAsset(It.Is <Asset>(a =>
                                                                a == asset &&
                                                                a.Available.Equals(new Fixed8(oldAvailability + changeInAvailability1 + changeInAvailability2)))));
        }
Exemple #16
0
        /// <inheritdoc />
        public IssueTransaction BuildGenesisIssueTransaction()
        {
            if (this._governingTokenRegisterTransaction == null)
            {
                this.BuildGoverningTokenRegisterTransaction();
            }
            if (this._utilityTokenRegisterTransaction == null)
            {
                this.BuildUtilityTokenRegisterTransaction();
            }

            var transactionOutput = this.GenesisGoverningTokenTransactionOutput();
            var genesisWitness    = this.BuildGenesisWitness();
            var issueTransaction  = new IssueTransaction
            {
                Attributes = new TransactionAttribute[0],
                Inputs     = new CoinReference[0],
                Outputs    = new[] { transactionOutput },
                Witness    = new[] { genesisWitness }
            };

            return(issueTransaction);
        }
Exemple #17
0
        private void BtnMakeOutput_Click(object sender, RoutedEventArgs e)
        {
            using (TxOutPutDialog dlg = new TxOutPutDialog(Application.Current.MainWindow, assetState))
            {
                if ((bool)dlg.ShowDialog() == true)
                {
                    issueTx = dlg.GetTransaction();
                    TxbIssueTxResult.Text = issueTx.Hash.ToString();
                    txbIssueFee.Text      = String.Format(StringTable.GetInstance().GetString("STR_SMART_CONTRACT_FEE", iLang), (issueTx.NetworkFee + issueTx.SystemFee).ToString());

                    BtnIssueLaunch.IsEnabled = true;
                    BtnIssueLaunch.Style     = FindResource("QurasAddAssetButtonStyle") as Style;
                }
                else
                {
                    TxbIssueTxResult.Text = "";
                    txbIssueFee.Text      = String.Format(StringTable.GetInstance().GetString("STR_SMART_CONTRACT_FEE", iLang), "0");

                    BtnIssueLaunch.IsEnabled = false;
                    BtnIssueLaunch.Style     = FindResource("QurasDisableAddAssetButtonStyle") as Style;
                }
            }
        }
Exemple #18
0
 public void GetScriptHashesForVerifying_Ordered()
 {
     TestUtils.SetupTestBlockchain(UInt256.Zero);
     uut = new IssueTransaction
     {
         Attributes = new TransactionAttribute[0],
         Inputs     = new CoinReference[0],
         Outputs    = new[]
         {
             new TransactionOutput
             {
                 AssetId    = Blockchain.UtilityToken.Hash,
                 Value      = Fixed8.FromDecimal(10),
                 ScriptHash = Contract.CreateMultiSigRedeemScript(1, TestUtils.StandbyValidators).ToScriptHash()
             },
             new TransactionOutput
             {
                 AssetId    = Blockchain.GoverningToken.Hash,
                 Value      = Fixed8.FromDecimal(10),
                 ScriptHash = Contract.CreateMultiSigRedeemScript(1, TestUtils.StandbyValidators).ToScriptHash()
             },
         },
         Scripts = new[]
         {
             new Witness
             {
                 InvocationScript   = new byte[0],
                 VerificationScript = new[] { (byte)OpCode.PUSHT }
             }
         }
     };
     UInt160[] res = uut.GetScriptHashesForVerifying();
     res.Length.Should().Be(2);
     res[0].Should().Be(new UInt160(TestUtils.GetByteArray(20, 0x9b)));
     res[1].Should().Be(new UInt160(TestUtils.GetByteArray(20, 0xe7)));
 }
Exemple #19
0
        public IssueTransaction GetTransaction()
        {
            RegisterTransaction asset = comboBox1.SelectedItem as RegisterTransaction;

            if (asset == null)
            {
                return(null);
            }
            IssueTransaction tx = Program.CurrentWallet.MakeTransaction <IssueTransaction>(listBox1.Items.OfType <TxOutListBoxItem>().GroupBy(p => p.Account).Select(g => new TransactionOutput
            {
                AssetId    = asset.Hash,
                Value      = g.Sum(p => p.Amount),
                ScriptHash = g.Key
            }).ToArray(), Fixed8.Zero);

            if (tx == null)
            {
                return(null);
            }
            Random rand = new Random();

            tx.Nonce = (uint)rand.Next();
            return(tx);
        }
        private static JArray GetMempoolTransaction(UInt160 ScriptHash)
        {
            JArray result = new JArray();

            foreach (Transaction tx in LocalNode.GetMemoryPool())
            {
                UInt160 from_script = null;
                UInt160 to_script   = null;
                JObject obj         = new JObject();

                if (tx is ContractTransaction)
                {
                    try
                    {
                        foreach (CoinReference input in tx.Inputs)
                        {
                            Transaction inputTx = Blockchain.Default.GetTransaction(input.PrevHash);
                            if (inputTx != null)
                            {
                                from_script = inputTx.Outputs[input.PrevIndex].ScriptHash;
                            }
                            else
                            {
                                foreach (Transaction inTx in LocalNode.GetMemoryPool())
                                {
                                    if (inTx.Hash.Equals(input.PrevHash))
                                    {
                                        from_script = inTx.Outputs[input.PrevIndex].ScriptHash;
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex) { }

                    if (tx.Outputs.Length > 0)
                    {
                        to_script = tx.Outputs[0].ScriptHash;
                    }

                    Dictionary <UInt256, Fixed8> balance = new Dictionary <UInt256, Fixed8>();
                    Dictionary <UInt256, Fixed8> fee     = new Dictionary <UInt256, Fixed8>();
                    for (int i = 0; i < tx.Outputs.Length; i++)
                    {
                        AssetState state = Blockchain.Default.GetAssetState(tx.Outputs[i].AssetId);
                        if (tx.Outputs[i].ScriptHash.Equals(to_script))
                        {
                            if (balance.ContainsKey(tx.Outputs[i].AssetId))
                            {
                                balance[tx.Outputs[i].AssetId] += tx.Outputs[i].Value;
                            }
                            else
                            {
                                balance[tx.Outputs[i].AssetId] = tx.Outputs[i].Value;
                            }
                        }

                        if (!fee.ContainsKey(tx.Outputs[i].AssetId))
                        {
                            if (tx.Outputs[i].Fee != Fixed8.Zero)
                            {
                                fee[tx.Outputs[i].AssetId] = tx.Outputs[i].Fee;
                            }
                        }
                    }
                    Fixed8 qrgFee = fee.Sum(p => p.Value);
                    if (balance.Count > 0)
                    {
                        UInt256 assetId = balance.First().Key;
                        Fixed8  value   = balance.Sum(p => p.Value);

                        AssetState assetState = Blockchain.Default.GetAssetState(assetId);
                        obj["asset"]  = assetState.GetName();
                        obj["amount"] = value.ToString();
                        obj["fee"]    = qrgFee.ToString();
                    }
                }
                else if (tx is ClaimTransaction)
                {
                    ClaimTransaction claimTx = (ClaimTransaction)tx;
                    if (claimTx.Outputs.Length > 0)
                    {
                        from_script = to_script = tx.Outputs[0].ScriptHash;
                    }

                    Dictionary <UInt256, Fixed8> balance = new Dictionary <UInt256, Fixed8>();
                    Dictionary <UInt256, Fixed8> fee     = new Dictionary <UInt256, Fixed8>();

                    for (int i = 0; i < tx.Outputs.Length; i++)
                    {
                        AssetState state = Blockchain.Default.GetAssetState(tx.Outputs[i].AssetId);
                        if (tx.Outputs[i].ScriptHash.Equals(to_script))
                        {
                            if (balance.ContainsKey(tx.Outputs[i].AssetId))
                            {
                                balance[tx.Outputs[i].AssetId] += tx.Outputs[i].Value;
                            }
                            else
                            {
                                balance[tx.Outputs[i].AssetId] = tx.Outputs[i].Value;
                            }
                        }

                        if (!fee.ContainsKey(tx.Outputs[i].AssetId))
                        {
                            if (tx.Outputs[i].Fee != Fixed8.Zero)
                            {
                                fee[tx.Outputs[i].AssetId] = tx.Outputs[i].Fee;
                            }
                        }
                    }
                    obj["asset"]  = Blockchain.UtilityToken.Name;
                    obj["amount"] = balance[Blockchain.UtilityToken.Hash].value.ToString();
                    obj["fee"]    = Fixed8.Zero.ToString();
                }
                else if (tx is InvocationTransaction)
                {
                    InvocationTransaction invocTx = (InvocationTransaction)tx;
                    try
                    {
                        foreach (CoinReference input in tx.Inputs)
                        {
                            from_script = tx.References[input].ScriptHash;
                        }
                    }
                    catch (Exception ex) { }
                    obj["asset"]  = Blockchain.UtilityToken.Name;
                    obj["amount"] = invocTx.Gas.ToString();
                    obj["fee"]    = Fixed8.Zero.ToString();
                }
                else if (tx is IssueTransaction)
                {
                    AssetState       state   = Blockchain.Default.GetAssetState(Blockchain.UtilityToken.Hash);
                    IssueTransaction issueTx = (IssueTransaction)tx;

                    try
                    {
                        foreach (CoinReference input in tx.Inputs)
                        {
                            from_script = tx.References[input].ScriptHash;
                        }
                    }
                    catch (Exception ex) { }

                    if (tx.Outputs.Length > 0)
                    {
                        to_script = tx.Outputs[0].ScriptHash;
                    }


                    if (tx.Outputs.Length > 0)
                    {
                        state = Blockchain.Default.GetAssetState(tx.Outputs[0].AssetId);
                    }

                    Fixed8 totalAmount = Fixed8.Zero;
                    foreach (TransactionOutput output in tx.Outputs)
                    {
                        if (output.AssetId != Blockchain.UtilityToken.Hash)
                        {
                            totalAmount += output.Value;
                        }
                    }

                    Fixed8 fee = issueTx.NetworkFee + issueTx.SystemFee;

                    obj["asset"]  = state.GetName();
                    obj["amount"] = totalAmount.ToString();
                    obj["fee"]    = fee.ToString();
                }

                if (!ScriptHash.Equals(from_script) && !ScriptHash.Equals(to_script))
                {
                    continue;
                }

                if (from_script != null)
                {
                    obj["from"] = Wallet.ToAddress(from_script);
                }
                else
                {
                    obj["from"] = "";
                }

                if (to_script != null)
                {
                    obj["to"] = Wallet.ToAddress(to_script);
                }
                else
                {
                    obj["to"] = "";
                }

                obj["txType"]      = tx.Type;
                obj["blockHeight"] = Fixed8.Zero.ToString();
                obj["txid"]        = tx.Hash.ToString();
                obj["timestamp"]   = DateTime.Now.ToTimestamp();
                obj["status"]      = 0;
                result.Add(obj);
            }
            return(result);
        }
Exemple #21
0
 public void TestSetup()
 {
     uut = new IssueTransaction();
 }
        public async Task Persist_BurnAssets_DecreaseAvailable()
        {
            var assetId               = new UInt256(RandomByteArray(32));
            var oldAvailability       = RandomInt(20000, 100000);
            var changeInAvailability1 = RandomInt(10000);
            var changeInAvailability2 = RandomInt(10000);
            var prevTx1               = new Transaction
            {
                Hash    = new UInt256(RandomByteArray(32)),
                Outputs = new[]
                {
                    new TransactionOutput
                    {
                        AssetId    = assetId,
                        ScriptHash = new UInt160(RandomByteArray(20)),
                        Value      = new Fixed8(changeInAvailability1)
                    },
                    new TransactionOutput
                    {
                        AssetId    = assetId,
                        ScriptHash = new UInt160(RandomByteArray(20)),
                        Value      = new Fixed8(RandomInt())
                    }
                }
            };
            var prevTx2 = new Transaction
            {
                Hash    = new UInt256(RandomByteArray(32)),
                Outputs = new[]
                {
                    new TransactionOutput
                    {
                        AssetId    = assetId,
                        ScriptHash = new UInt160(RandomByteArray(20)),
                        Value      = new Fixed8(RandomInt())
                    },
                    new TransactionOutput
                    {
                        AssetId    = assetId,
                        ScriptHash = new UInt160(RandomByteArray(20)),
                        Value      = new Fixed8(changeInAvailability2)
                    }
                }
            };
            var input = new IssueTransaction
            {
                Inputs = new[]
                {
                    new CoinReference
                    {
                        PrevHash  = prevTx1.Hash,
                        PrevIndex = 0
                    },
                    new CoinReference
                    {
                        PrevHash  = prevTx2.Hash,
                        PrevIndex = 1
                    }
                }
            };
            var asset = new Asset
            {
                Available = new Fixed8(oldAvailability)
            };
            var repositoryMock = AutoMockContainer.GetMock <IRepository>();

            repositoryMock.Setup(m => m.GetTransaction(It.Is <UInt256>(u => u.Equals(prevTx1.Hash))))
            .ReturnsAsync(prevTx1);
            repositoryMock.Setup(m => m.GetTransaction(It.Is <UInt256>(u => u.Equals(prevTx2.Hash))))
            .ReturnsAsync(prevTx2);
            repositoryMock.Setup(m => m.GetAsset(It.Is <UInt256>(u => u.Equals(assetId)))).ReturnsAsync(asset);
            var testee = AutoMockContainer.Create <IssueTransactionPersister>();

            await testee.Persist(input);

            repositoryMock.Verify(m => m.AddAsset(It.Is <Asset>(a =>
                                                                a == asset &&
                                                                a.Available.Equals(new Fixed8(oldAvailability - changeInAvailability1 - changeInAvailability2)))));
        }