Ejemplo n.º 1
0
        public void CreateProfile()
        {
            var _cid     = Guid.NewGuid().ToString();
            var _profile = new Profile()
            {
                BasicProfile          = _mockCustomer,
                CitizenIdentifier     = _cid,
                ActiveState           = "NJ",
                CurrentHealthcarePlan = new HealthcarePlan(),
                StateApprover         = " ",
                Status = ProfileStatus.ProfileCreated,
                PreferredHealthcarePlan = new HealthcarePlanItem()
                {
                    Name = "my preferred plan - fake", Id = "0"
                },
                Description = @"description for citizen profile " + _cid
            };

            _profile.BasicProfile.FedIncome   = 10000;
            _profile.BasicProfile.StateIncome = 10000;
            _profile.BasicProfile.Address.Zip = "07188";
            ContractTransaction result = _client.CreateProfile(_profile);

            if (result != null)
            {
                citizenIdentifier = result.BusinessContractDTO.CitizenIdentifier;
            }

            Assert.AreEqual(result.BusinessContractDTO.CitizenIdentifier, _profile.CitizenIdentifier, "CreateProfile Confirmation not returned");
        }
Ejemplo n.º 2
0
        private void  除DToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (listView2.SelectedIndices.Count == 0)
            {
                return;
            }
            var delete = listView2.SelectedItems.OfType <ListViewItem>().Select(p => (RegisterTransaction)p.Tag).Select(p => new
            {
                Asset = p,
                Value = Program.CurrentWallet.GetAvailable(p.Hash)
            }).ToArray();

            if (MessageBox.Show("资产删除后将无法恢复,您确定要删除以下资产吗?\n"
                                + string.Join("\n", delete.Select(p => $"{p.Asset.GetName()}:{p.Value}"))
                                , "删除确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) != DialogResult.Yes)
            {
                return;
            }
            ContractTransaction tx = Program.CurrentWallet.MakeTransaction(new ContractTransaction
            {
                Outputs = delete.Select(p => new TransactionOutput
                {
                    AssetId    = p.Asset.Hash,
                    Value      = p.Value,
                    ScriptHash = RecycleScriptHash
                }).ToArray()
            }, Fixed8.Zero);

            Helper.SignAndShowInformation(tx);
        }
Ejemplo n.º 3
0
        public async Task Persist_TransactionWithOutputs_GainOutputs()
        {
            var input = new ContractTransaction
            {
                Hash    = UInt256.Parse(RandomInt().ToString("X64")),
                Outputs = new TransactionOutput[3]
            };

            for (var i = 0; i < input.Outputs.Length; i++)
            {
                input.Outputs[i] = new TransactionOutput
                {
                    AssetId    = UInt256.Parse(RandomInt().ToString("X64")),
                    ScriptHash = UInt160.Parse(RandomInt().ToString("X40")),
                    Value      = new Fixed8(RandomInt())
                }
            }
            ;
            var accountManagerMock = AutoMockContainer.GetMock <IAccountManager>();
            var repositoryMock     = AutoMockContainer.GetMock <IRepository>();
            var testee             = AutoMockContainer.Create <TransactionPersister>();

            await testee.Persist(input);

            foreach (var expectedOutput in input.Outputs)
            {
                accountManagerMock.Verify(m =>
                                          m.UpdateBalance(expectedOutput.ScriptHash, expectedOutput.AssetId, expectedOutput.Value));
            }
            repositoryMock.Verify(m => m.AddCoinStates(input.Hash,
                                                       It.Is <CoinState[]>(cs => cs.Length == input.Outputs.Length && cs.All(c => c.Equals(CoinState.New)))));
        }
        public async Task <bool> LogTransaction(ContractTransaction transactionInformation, string description = null)
        {
            //Marking previous tx as inactive
            var previousTxs =
                _transactionIndexRepository.FindAll(new GenericSpecification <ContractTransaction>(x => x.BusinessContractDTO.CitizenIdentifier == transactionInformation.BusinessContractDTO.CitizenIdentifier));

            foreach (var item in previousTxs)
            {
                if (item.IsActiveTransaction)
                {
                    item.IsActiveTransaction = false;
                    await _transactionIndexRepository.SaveAsync(item);
                }
            }

            if (!string.IsNullOrEmpty(description))
            {
                transactionInformation.BusinessContractDTO.Description = description;
            }

            transactionInformation.IsActiveTransaction = true;
            await _transactionIndexRepository.SaveAsync(transactionInformation);

            return(true);
        }
Ejemplo n.º 5
0
        //Transfer Global Asset
        public static Transaction CreateGlobalTransfer(SignDelegate sign)
        {
            //交易输入是 1 GAS
            var inputs = new List <CoinReference> {
                //coin reference A
                new CoinReference()
                {
                    PrevHash  = new UInt256("0x21b64eb35881e7261c72c70f38bd6d5eb6aa18f232e08ba3022220b46c13d9a2".Remove(0, 2).HexToBytes().Reverse().ToArray()),
                    PrevIndex = 0
                }
            }.ToArray();
            //交易输出是 0.999 GAS,找回到原地址
            var outputs = new List <TransactionOutput> {
                new TransactionOutput()
                {
                    AssetId    = Blockchain.UtilityToken.Hash,                        //Asset Id, this is GAS
                    ScriptHash = "Ad1HKAATNmFT5buNgSxspbW68f4XVSssSw".ToScriptHash(), //Receiver
                    Value      = new Fixed8((long)(0.999 * (long)Math.Pow(10, 8)))    //Value (satoshi unit)
                }
            }.ToArray();
            //则手续费是 0.001 GAS

            var tx = new ContractTransaction()
            {
                Outputs    = outputs,
                Inputs     = inputs,
                Attributes = new TransactionAttribute[0],
                Witnesses  = new Witness[0],
            };

            return(sign.Invoke(tx));
        }
        public async Task <NeoModules.NEP6.Transactions.Transaction> BuildGasTransactionAsync(string @from, string to, decimal amount)
        {
            var tx = new ContractTransaction
            {
                Attributes = new TransactionAttribute[0],
                Inputs     = new CoinReference[0],
                Outputs    = new List <TransferOutput>
                {
                    new TransferOutput
                    {
                        AssetId    = Utils.GasToken,
                        ScriptHash = to.ToScriptHash(),
                        Value      = BigDecimal.Parse(amount.ToString(CultureInfo.InvariantCulture),
                                                      Constants.Assets.Gas.Accuracy)
                    }
                }.Select(p => p.ToTxOutput()).ToArray(),
                Witnesses = new Witness[0]
            };

            var unspentOutputs = await _transactionOutputsService.GetUnspentOutputsAsync(from);

            tx = MakeTransaction(tx,
                                 unspentOutputs,
                                 from.ToScriptHash(),
                                 changeAddress: from.ToScriptHash());

            return(tx);
        }
Ejemplo n.º 7
0
        public async Task Persist_ContractTx_NoSpecialCalls()
        {
            var input  = new ContractTransaction();
            var testee = AutoMockContainer.Create <TransactionPersister>();

            await testee.Persist(input);
        }
Ejemplo n.º 8
0
        private void button3_Click(object sender, EventArgs e)
        {
            SignatureContext context;
            JObject          json1 = JObject.Parse(textBox2.Text);

            if (json1.ContainsProperty("hex"))
            {
                context = SignatureContext.FromJson(json1);
            }
            else
            {
                ContractTransaction tx1 = JsonToRequest(json1);
                ContractTransaction tx2 = JsonToRequest(JObject.Parse(textBox3.Text));
                context = new SignatureContext(new ContractTransaction
                {
                    Attributes = new TransactionAttribute[0],
                    Inputs     = tx1.Inputs.Concat(tx2.Inputs).ToArray(),
                    Outputs    = tx1.Outputs.Concat(tx2.Outputs).ToArray()
                });
            }
            Program.CurrentWallet.Sign(context);
            if (context.Completed)
            {
                context.Verifiable.Scripts = context.GetScripts();
                ContractTransaction tx = (ContractTransaction)context.Verifiable;
                Program.CurrentWallet.SaveTransaction(tx);
                Program.LocalNode.Relay(tx);
                InformationBox.Show(tx.Hash.ToString(), Strings.TradeSuccessMessage, Strings.TradeSuccessCaption);
            }
            else
            {
                InformationBox.Show(context.ToString(), Strings.TradeNeedSignatureMessage, Strings.TradeNeedSignatureCaption);
            }
        }
Ejemplo n.º 9
0
        private void button3_Click(object sender, EventArgs e)
        {
            SignatureContext context;
            JObject          json1 = JObject.Parse(textBox2.Text);

            if (json1.ContainsProperty("hex"))
            {
                context = SignatureContext.FromJson(json1);
            }
            else
            {
                ContractTransaction tx1 = JsonToRequest(json1);
                ContractTransaction tx2 = JsonToRequest(JObject.Parse(textBox3.Text));
                context = new SignatureContext(new ContractTransaction
                {
                    Attributes = new TransactionAttribute[0],
                    Inputs     = tx1.Inputs.Concat(tx2.Inputs).ToArray(),
                    Outputs    = tx1.Outputs.Concat(tx2.Outputs).ToArray()
                });
            }
            Program.CurrentWallet.Sign(context);
            if (context.Completed)
            {
                context.Signable.Scripts = context.GetScripts();
                ContractTransaction tx = (ContractTransaction)context.Signable;
                Program.CurrentWallet.SendTransaction(tx);
                Program.LocalNode.Relay(tx);
                InformationBox.Show(tx.Hash.ToString(), "交易已发送,这是交易编号(TXID):", "交易成功");
            }
            else
            {
                InformationBox.Show(context.ToString(), "交易构造完成,请将以下信息发送给对方进行签名:", "签名不完整");
            }
        }
Ejemplo n.º 10
0
        private void  除DToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (listView2.SelectedIndices.Count == 0)
            {
                return;
            }
            var delete = listView2.SelectedItems.OfType <ListViewItem>().Select(p => p.Tag as AssetState).Where(p => p != null).Select(p => new
            {
                Asset = p,
                Value = Program.CurrentWallet.GetAvailable(p.AssetId)
            }).ToArray();

            if (delete.Length == 0)
            {
                return;
            }
            if (MessageBox.Show($"{Strings.DeleteAssetConfirmationMessage}\n"
                                + string.Join("\n", delete.Select(p => $"{p.Asset.GetName()}:{p.Value}"))
                                , Strings.DeleteConfirmation, MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) != DialogResult.Yes)
            {
                return;
            }
            ContractTransaction tx = Program.CurrentWallet.MakeTransaction(new ContractTransaction
            {
                Outputs = delete.Select(p => new TransactionOutput
                {
                    AssetId    = p.Asset.AssetId,
                    Value      = p.Value,
                    ScriptHash = RecycleScriptHash
                }).ToArray()
            }, fee: Fixed8.Zero);

            Helper.SignAndShowInformation(tx);
        }
 public async Task HandleAsync(ContractTransaction tx)
 {
     await _contractRepository.UpsertAsync(
         tx.ContractAddress,
         tx.Code,
         tx.Transaction);
 }
Ejemplo n.º 12
0
        public static Transaction CreateGlobalTransfer(SignDelegate2 sign)
        {
            CoinReference[] inputs = new CoinReference[]
            {
                new CoinReference()
                {
                    PrevHash  = new UInt256(preTxId.Remove(0, 2).HexToBytes().Reverse().ToArray()),
                    PrevIndex = prevIndex //vout n
                }
            }.ToArray();

            var outputs = new List <TransactionOutput>();
            var output1 = new TransactionOutput()
            {
                AssetId    = UInt256.Parse(assetid),
                ScriptHash = tansferAddress.ToScriptHash(),
                Value      = tansferValue
            };

            outputs.Add(output1);

            var tx = new ContractTransaction()
            {
                Outputs    = outputs.ToArray(),
                Inputs     = inputs,
                Attributes = new TransactionAttribute[0],
                Witnesses  = new Witness[0]
            };

            return(sign.Invoke(tx));
        }
Ejemplo n.º 13
0
        public ContractTransaction MakeTransaction(ContractTransaction transaction, UInt160 changeAddress = null,
                                                   Fixed8 fee = default(Fixed8))
        {
            this.ThrowIfWalletIsNotOpen();

            return(this.currentWallet.MakeTransaction(transaction, changeAddress, fee));
        }
Ejemplo n.º 14
0
        private JObject RequestToJson(ContractTransaction tx)
        {
            JObject json = new JObject();

            json["vin"]            = tx.Inputs.Select(p => p.ToJson()).ToArray();
            json["vout"]           = tx.Outputs.Select((p, i) => p.ToJson((ushort)i)).ToArray();
            json["change_address"] = Wallet.ToAddress(Program.CurrentWallet.GetChangeAddress());
            return(json);
        }
Ejemplo n.º 15
0
        public static Transaction CreateGlobalTransfer(SignDelegate2 sign)
        {
            //utxo txid
            string      preTxId = "0x1db3ae57b5f3fda94aa6a81add07a70fc38f0eae9e26f39d7d51183fad0c849f";
            UInt256     hash    = UInt256.Parse(preTxId);
            Transaction tx1     = Blockchain.Singleton.GetTransaction(hash);

            Fixed8 preOutVal     = tx1.Outputs[100].Value;
            Fixed8 currentOutVal = new Fixed8(1 * (long)Math.Pow(10, 8));

            if (preOutVal < currentOutVal)
            {
                Console.WriteLine("insufficient fund");
                return(null);
            }

            var inputs = new List <CoinReference>
            {
                new CoinReference()
                {
                    PrevHash  = new UInt256(preTxId.Remove(0, 2).HexToBytes().Reverse().ToArray()),
                    PrevIndex = 440
                }
            }.ToArray();

            var outputs = new List <TransactionOutput>();

            var output1 = new TransactionOutput()
            {
                AssetId    = UInt256.Parse(assetid),
                ScriptHash = "AbUAKqt8crJQnhDJWQtFGHT7Pgv9ABnQE6".ToScriptHash(),
                Value      = currentOutVal
            };

            outputs.Add(output1);
            //if (preOutVal > currentOutVal)
            //{
            //    var output2 = new TransactionOutput()
            //    {
            //        AssetId = UInt256.Parse(assetid),
            //        ScriptHash = "AZi4EzuSSp4kiWCUvLZcWo8daymKf53ez6".ToScriptHash(),
            //        Value = preOutVal - currentOutVal
            //    };
            //    outputs.Add(output2);
            //}

            var tx = new ContractTransaction()
            {
                Outputs    = outputs.ToArray(),
                Inputs     = inputs,
                Attributes = new TransactionAttribute[0],
                Witnesses  = new Witness[0]
            };

            return(sign.Invoke(tx));
        }
Ejemplo n.º 16
0
        private void TransactProcess(TransactionOutput[] pOutputs, Wallet pWallet)
        {
            //构造交易
            string availableA = accountA.Wallet.GetAvailable(Blockchain.GoverningToken.Hash).ToString();
            string balanceA   = accountA.Wallet.GetBalance(Blockchain.GoverningToken.Hash).ToString();
            string availableB = accountB.Wallet.GetAvailable(Blockchain.GoverningToken.Hash).ToString();
            string balanceB   = accountB.Wallet.GetBalance(Blockchain.GoverningToken.Hash).ToString();

            ContractTransaction tx = pWallet.MakeTransaction(new ContractTransaction {
                Outputs = pOutputs
            }, null, null, Fixed8.Zero);

            if (tx == null)
            {
                //amount = amount * 10;
                //Thread.Sleep(300);
                MessageBox.Show("余额不足以支付系统费用。");
                return;
            }
            ContractParametersContext context;

            try
            {
                context = new ContractParametersContext(tx);
            }
            catch (InvalidOperationException)
            {
                //Thread.Sleep(20000);
                MessageBox.Show("钱包余额不足,或区块链未同步完成,无法发送该交易。");
                return;
            }
            Program.CurrentWallet.Sign(context);
            if (context.Completed)
            {
                tx.Scripts = context.GetScripts();
                Program.CurrentWallet.ApplyTransaction(tx);
                Program.LocalNode.Relay(tx);
                string result = "交易已发送,这是交易编号(TXID):" + tx.Hash.ToString();

                this.Dispatcher.Invoke(DispatcherPriority.Send, new Action(() =>
                {
                    this.RecordInfoList.Add(new RecordInfo(result, availableA, balanceA, availableB, balanceB));
                    this.listView.ScrollIntoView(this.listView.Items[this.listView.Items.Count - 1]);
                    GridView gv = listView.View as GridView;
                    if (gv != null)
                    {
                        foreach (GridViewColumn gvc in gv.Columns)
                        {
                            gvc.Width = gvc.ActualWidth;
                            gvc.Width = Double.NaN;
                        }
                    }
                }));
                Thread.Sleep(100);
            }
        }
Ejemplo n.º 17
0
        private void button1_Click(object sender, EventArgs e)
        {
            ContractTransaction tx = Program.CurrentWallet.MakeTransaction(new ContractTransaction {
                Outputs = txOutListBox1.Items.Select(p => p.Output).ToArray()
            }, fee: Fixed8.Zero);

            textBox3.Text = RequestToJson(tx).ToString();
            InformationBox.Show(textBox3.Text, Strings.TradeRequestCreatedMessage, Strings.TradeRequestCreatedCaption);
            tabControl1.SelectedTab = tabPage2;
        }
Ejemplo n.º 18
0
        private void button1_Click(object sender, EventArgs e)
        {
            ContractTransaction tx = Program.CurrentWallet.MakeTransaction(new ContractTransaction {
                Outputs = txOutListBox1.Items.Select(p => p.Output).ToArray()
            }, Fixed8.Zero);

            textBox3.Text = RequestToJson(tx).ToString();
            InformationBox.Show(textBox3.Text, "交易请求已生成,请发送给对方,或与对方的请求合并:", "交易请求");
            tabControl1.SelectedTab = tabPage2;
        }
Ejemplo n.º 19
0
        public async Task Persist_Transaction_SaveTx()
        {
            var input          = new ContractTransaction();
            var repositoryMock = AutoMockContainer.GetMock <IRepository>();
            var testee         = AutoMockContainer.Create <TransactionPersister>();

            await testee.Persist(input);

            repositoryMock.Verify(m => m.AddTransaction(input));
        }
Ejemplo n.º 20
0
        public static Transaction CreateGlobalTransfer(SignDelegate sign)
        {
            string      preTxId = "0x7866a1aae60e7e6a2da87a681edf8c265db200ba68f4a96b447f85bb60c3594b";
            UInt256     hash    = UInt256.Parse(preTxId);
            Transaction tx1     = Blockchain.Singleton.GetTransaction(hash);

            Fixed8 preOutVal     = tx1.Outputs[100].Value;
            Fixed8 currentOutVal = new Fixed8(1 * (long)Math.Pow(10, 8));

            if (preOutVal < currentOutVal)
            {
                Console.WriteLine("insufficient fund");
                return(null);
            }

            var inputs = new List <CoinReference>
            {
                new CoinReference()
                {
                    PrevHash  = new UInt256(preTxId.Remove(0, 2).HexToBytes().Reverse().ToArray()),
                    PrevIndex = 100
                }
            }.ToArray();

            var outputs = new List <TransactionOutput>();

            var output1 = new TransactionOutput()
            {
                AssetId    = UInt256.Parse(assetid),
                ScriptHash = "AYuApoS1MQvJMQF7J9GiMcCA9du7s6YBwo".ToScriptHash(),
                Value      = currentOutVal
            };

            outputs.Add(output1);
            if (preOutVal > currentOutVal)
            {
                var output2 = new TransactionOutput()
                {
                    AssetId    = UInt256.Parse(assetid),
                    ScriptHash = "AZi4EzuSSp4kiWCUvLZcWo8daymKf53ez6".ToScriptHash(),
                    Value      = preOutVal - currentOutVal
                };
                outputs.Add(output2);
            }

            var tx = new ContractTransaction()
            {
                Outputs    = outputs.ToArray(),
                Inputs     = inputs,
                Attributes = new TransactionAttribute[0],
                Witnesses  = new Witness[0]
            };

            return(sign.Invoke(tx));
        }
Ejemplo n.º 21
0
        private void button1_Click(object sender, EventArgs e)
        {
            ContractTransaction tx = Program.CurrentWallet.MakeTransaction(new ContractTransaction
            {
                Outputs = txOutListBox1.Items.Select(p => p.ToTxOutput()).ToArray()
            }, fee: Fixed8.Zero);

            textBox3.Text = RequestToJson(tx).ToString();
            InformationBox.Show(textBox3.Text, LanHelper.LocalLanguage("Transaction request generated, please send it to the counterparty or merge it with the counterparty's request."), LanHelper.LocalLanguage("Trade Request"));
            tabControl1.SelectedTab = tabPage2;
        }
Ejemplo n.º 22
0
        public async Task <bool> LogTransaction(ContractTransaction transactionInformation, string description = null)
        {
            if (!string.IsNullOrEmpty(description))
            {
                transactionInformation.BusinessContractDTO.Description = description;
            }

            await _transactionIndexRepository.SaveAsync(transactionInformation);

            return(true);
        }
Ejemplo n.º 23
0
        public void AssignHealthcarePlan()
        {
            HealthcarePlanItem healthcarePlan = new HealthcarePlanItem
            {
                Id   = "id",
                Name = "NY Healthcare Plan"
            };
            ContractTransaction result = _client.AssignHealthcarePlan(citizenIdentifier, healthcarePlan);

            Assert.AreEqual(result.BusinessContractDTO.CurrentHealthcarePlan.Plan.Name, healthcarePlan.Name, "AssignHealthcarePlan confirmation not returned");
        }
Ejemplo n.º 24
0
        public async Task Persist_TransactionWithInputs_SpendOutputs()
        {
            var repositoryMock = AutoMockContainer.GetMock <IRepository>();
            var input          = new ContractTransaction
            {
                Hash   = UInt256.Parse(RandomInt().ToString("X64")),
                Inputs = new CoinReference[3]
            };
            var txs = new Transaction[3];

            for (var i = 0; i < input.Inputs.Length; i++)
            {
                var reference = new CoinReference
                {
                    PrevHash  = UInt256.Parse(RandomInt().ToString("X64")),
                    PrevIndex = 0
                };
                input.Inputs[i] = reference;
                txs[i]          = new Transaction
                {
                    Hash    = reference.PrevHash,
                    Outputs = new[]
                    {
                        new TransactionOutput
                        {
                            AssetId    = UInt256.Parse(RandomInt().ToString("X64")),
                            ScriptHash = UInt160.Parse(RandomInt().ToString("X40")),
                            Value      = new Fixed8(RandomInt())
                        }
                    }
                };
                repositoryMock
                .Setup(m => m.GetTransaction(reference.PrevHash))
                .ReturnsAsync(txs[i]);
                repositoryMock
                .Setup(m => m.GetCoinStates(reference.PrevHash))
                .ReturnsAsync(new[] { CoinState.Confirmed });
            }

            var accountManagerMock = AutoMockContainer.GetMock <IAccountManager>();
            var testee             = AutoMockContainer.Create <TransactionPersister>();

            await testee.Persist(input);

            for (var i = 0; i < input.Outputs.Length; i++)
            {
                var output = txs[i].Outputs[0];
                accountManagerMock.Verify(m => m.UpdateBalance(output.ScriptHash, output.AssetId, -output.Value));
                var hash = txs[i].Hash;
                repositoryMock.Verify(m => m.AddCoinStates(It.Is <UInt256>(u => u.Equals(hash)),
                                                           It.Is <CoinState[]>(cs => cs.Length == 1 && cs[0].Equals(CoinState.Confirmed | CoinState.Spent))));
            }
        }
Ejemplo n.º 25
0
        public void PerformFundTransfer(Fixed8 amountToTransfer, UInt160 destinationScriptHash, IInventory assetId, UInt160 fromAddress)
        {
            //  public UInt160 ChangeAddress => Wallet.ToScriptHash((string)comboBox1.SelectedItem);

            var tx        = new ContractTransaction();
            var neoOutput = new TransactionOutput();

            neoOutput.AssetId    = assetId.Hash;
            neoOutput.Value      = amountToTransfer;
            neoOutput.ScriptHash = destinationScriptHash;
            tx.Outputs           = new[] { neoOutput };

            var walletTx = NeoWallet.MakeTransaction(tx, fromAddress);

            if (walletTx == null)
            {
                throw new ApplicationException("Wallet TX was null. Possibly insufficient funds");
            }

            ContractParametersContext context;

            try
            {
                context = new ContractParametersContext(walletTx);
            }
            catch (InvalidOperationException)
            {
                throw new ApplicationException("unsynchronized block");
            }

            var sign = NeoWallet.Sign(context);

            if (context.Completed)
            {
                context.Verifiable.Scripts = context.GetScripts();
                NeoWallet.ApplyTransaction(walletTx); //changes with different versions of NEO
                var relay = _node.Relay(walletTx);

                //TODO: make this use our transaction watcher
                var originalHeight = Blockchain.Default.Height; //store the height we sent at then wait for the next block
                //possibly check if sign/relay/save has actually worked?

                while (Blockchain.Default.Height <= originalHeight + 1)
                {
                    Thread.Sleep(1000);                                                     //wait for next block
                }
            }
            else
            {
                throw new ApplicationException("Incompleted Signature");
            }
        }
Ejemplo n.º 26
0
        //private string RequestRpc(string method, string kvs)
        //{
        //    string jsonRes = "";
        //    using (HttpClient client = new HttpClient())
        //    {
        //        string uri = $"{ExtensionSettings.Default.DataRPCServer.Host}/{method}?{kvs}";
        //        client.BaseAddress = new Uri(uri);
        //        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        //        var response = client.GetAsync(uri).Result;
        //        Task<Stream> task = response.Content.ReadAsStreamAsync();
        //        Stream backStream = task.Result;
        //        StreamReader reader = new StreamReader(backStream);
        //        jsonRes = reader.ReadToEnd();
        //        reader.Close();
        //        backStream.Close();
        //    }
        //    return jsonRes;
        //}

        private Transaction MakeToColdTransaction(Coin[] coins, UInt160 outAddress, UInt256 assetId, UInt160 fee_address = null)
        {
            int         MaxInputCount = 50;
            Transaction tx            = new ContractTransaction();

            tx.Attributes = new TransactionAttribute[0];
            tx.Witnesses  = new Witness[0];

            List <CoinReference>     inputs  = new List <CoinReference>();
            List <TransactionOutput> outputs = new List <TransactionOutput>();

            Fixed8 sum = Fixed8.Zero;

            if (coins.Length < 50)
            {
                MaxInputCount = coins.Length;
            }
            for (int j = 0; j < MaxInputCount; j++)
            {
                sum += coins[j].Output.Value;
                inputs.Add(new CoinReference
                {
                    PrevHash  = coins[j].Reference.PrevHash,
                    PrevIndex = coins[j].Reference.PrevIndex
                });
            }
            tx.Inputs = inputs.ToArray();
            outputs.Add(new TransactionOutput
            {
                AssetId    = assetId,
                ScriptHash = outAddress,
                Value      = sum
            });
            if (tx.SystemFee > Fixed8.Zero)
            {
                outputs.Add(new TransactionOutput
                {
                    AssetId = Blockchain.UtilityToken.Hash,
                    Value   = tx.SystemFee
                });
            }
            tx.Outputs = outputs.ToArray();
            Fixed8 transfee = BhpTxFee.EstimateTxFee(tx, assetId);

            if (tx.Outputs[0].Value <= transfee)
            {
                return(null);
            }
            tx.Outputs[0].Value -= transfee;
            return(TransactionContract.EstimateFee(wallet, tx, null, fee_address));
        }
Ejemplo n.º 27
0
        private static ContractTransaction prepareDeployObject(string bindingID, Order orderObject)
        {
            var accomodation = orderObject.Consignments[0].AccommodationData;
            var activity     = orderObject.Consignments[0].ActivityData;


            SampleDTO _dto = new SampleDTO()
            {
                ContractID     = bindingID,
                TransactionID  = bindingID,
                TransactedTime = DateTime.Now,
                Description    = "Transacted",
                AdminDetail    = new AdminDetails()
                {
                    OrderCode         = orderObject.OrderCode,
                    ConsignmentCode   = orderObject.Consignments[0].Code,
                    ConsignmentStatus = orderObject.Consignments[0].Status,
                    BookingDate       = orderObject.BookingDate.ToString(),
                    CheckinDate       = accomodation == null ? null : accomodation.CheckIn.ToString(),
                    CheckoutDate      = accomodation == null ? null : accomodation.CheckOut.ToString(),
                    Currency          = orderObject.Currency,
                    Quantity          = "1",
                    Price             = orderObject.OrderPrice.ToString(),
                    ServiceDate       = DateTime.Now.ToString(),
                    ServiceType       = orderObject.Consignments[0].Type,
                    Supplier          = orderObject.Supplier
                }
            };
            ConstructorConfirmation _deployConfirmation = new ConstructorConfirmation()
            {
                BindingId = bindingID,
                Name      = "New Enterprise Smart Contract instance",
                TransactionConfirmation = new TransactionConfirmation()
                {
                    BlockHash        = "0xfa4e2a31506c1f930efc7701ff6ddc1451d08a38a7a9267fe263766b4c7ea2d0",
                    BlockNumber      = "1",
                    ContractAddress  = "0xed9d02e382b34818e88b88a309c7fe71e65f419d",
                    TransactionHash  = "",
                    ContractName     = "",
                    ProxyId          = "",
                    TransactionIndex = "1"
                }
            };
            ContractTransaction _txInformation = new ContractTransaction(_dto, _deployConfirmation);

            _txInformation.OrderDetails = orderObject;

            return(_txInformation);
        }
Ejemplo n.º 28
0
        private void button2_Click(object sender, EventArgs e)
        {
            IEnumerable <CoinReference>     inputs;
            IEnumerable <TransactionOutput> outputs;
            JObject json = JObject.Parse(textBox2.Text);

            if (json.ContainsProperty("hex"))
            {
                ContractTransaction tx_mine   = JsonToRequest(JObject.Parse(textBox3.Text));
                ContractTransaction tx_others = (ContractTransaction)ContractParametersContext.FromJson(json).Verifiable;
                inputs = tx_others.Inputs.Except(tx_mine.Inputs);
                List <TransactionOutput> outputs_others = new List <TransactionOutput>(tx_others.Outputs);
                foreach (TransactionOutput output_mine in tx_mine.Outputs)
                {
                    TransactionOutput output_others = outputs_others.FirstOrDefault(p => p.AssetId == output_mine.AssetId && p.Value == output_mine.Value && p.ScriptHash == output_mine.ScriptHash);
                    if (output_others == null)
                    {
                        MessageBox.Show(LanHelper.LocalLanguage("Validation failed, the counterparty falsified the transaction content!"), LanHelper.LocalLanguage("Failed"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    outputs_others.Remove(output_others);
                }
                outputs = outputs_others;
            }
            else
            {
                ContractTransaction tx_others = JsonToRequest(json);
                inputs  = tx_others.Inputs;
                outputs = tx_others.Outputs;
            }
            try
            {
                if (inputs.Select(p => Blockchain.Singleton.GetTransaction(p.PrevHash).Outputs[p.PrevIndex].ScriptHash).Distinct().Any(p => Program.CurrentWallet.Contains(p)))
                {
                    MessageBox.Show(LanHelper.LocalLanguage("Validation failed, the counterparty generated illegal transaction content!"), LanHelper.LocalLanguage("Failed"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            catch
            {
                MessageBox.Show(LanHelper.LocalLanguage("Validation failed, invalid transaction or unsynchronized blockchain, please try again when synchronized!"), LanHelper.LocalLanguage("Failed"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            outputs = outputs.Where(p => Program.CurrentWallet.Contains(p.ScriptHash));
            using (TradeVerificationDialog dialog = new TradeVerificationDialog(outputs))
            {
                button3.Enabled = dialog.ShowDialog() == DialogResult.OK;
            }
        }
Ejemplo n.º 29
0
        private void button2_Click(object sender, EventArgs e)
        {
            IEnumerable <CoinReference>     inputs;
            IEnumerable <TransactionOutput> outputs;
            JObject json = JObject.Parse(textBox2.Text);

            if (json.ContainsProperty("hex"))
            {
                ContractTransaction tx_mine   = JsonToRequest(JObject.Parse(textBox3.Text));
                ContractTransaction tx_others = (ContractTransaction)SignatureContext.FromJson(json).Verifiable;
                inputs = tx_others.Inputs.Except(tx_mine.Inputs);
                List <TransactionOutput> outputs_others = new List <TransactionOutput>(tx_others.Outputs);
                foreach (TransactionOutput output_mine in tx_mine.Outputs)
                {
                    TransactionOutput output_others = outputs_others.FirstOrDefault(p => p.AssetId == output_mine.AssetId && p.Value == output_mine.Value && p.ScriptHash == output_mine.ScriptHash);
                    if (output_others == null)
                    {
                        MessageBox.Show(Strings.TradeFailedFakeDataMessage, Strings.Failed, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    outputs_others.Remove(output_others);
                }
                outputs = outputs_others;
            }
            else
            {
                ContractTransaction tx_others = JsonToRequest(json);
                inputs  = tx_others.Inputs;
                outputs = tx_others.Outputs;
            }
            try
            {
                if (inputs.Select(p => Blockchain.Default.GetTransaction(p.PrevHash).Outputs[p.PrevIndex].ScriptHash).Distinct().Any(p => Program.CurrentWallet.ContainsAddress(p)))
                {
                    MessageBox.Show(Strings.TradeFailedInvalidDataMessage, Strings.Failed, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            catch
            {
                MessageBox.Show(Strings.TradeFailedNoSyncMessage, Strings.Failed, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            outputs = outputs.Where(p => Program.CurrentWallet.ContainsAddress(p.ScriptHash));
            using (TradeVerificationDialog dialog = new TradeVerificationDialog(outputs))
            {
                button3.Enabled = dialog.ShowDialog() == DialogResult.OK;
            }
        }
Ejemplo n.º 30
0
        public static void Verify()
        {
            var inputs = new List <CoinReference> {
                new CoinReference()
                {
                    PrevHash  = new UInt256("0xdb4c4f1a17b365a68497ef0e118db89b827db24f67ee71d317d38c68c84424ef".Remove(0, 2).HexToBytes().Reverse().ToArray()),
                    PrevIndex = 0
                }
            }.ToArray();

            var outputs = new List <TransactionOutput> {
                new TransactionOutput()
                {
                    AssetId    = Blockchain.UtilityToken.Hash, //Asset Id, this is GAS
                    ScriptHash = User,
                    Value      = new Fixed8((long)(1 * (long)Math.Pow(10, 8)))
                }
            }.ToArray();

            Transaction tx = null;

            var verificationScript = new byte[0];

            using (ScriptBuilder sb = new ScriptBuilder())
            {
                sb.EmitPush(2);
                sb.EmitPush("1");
                verificationScript = sb.ToArray();
            }

            var witness = new Witness
            {
                InvocationScript   = verificationScript,
                VerificationScript = Blockchain.Singleton.Store.GetContracts().TryGet(ScriptHash).Script
            };

            tx = new ContractTransaction
            {
                Version    = 0,
                Outputs    = outputs,
                Inputs     = inputs,
                Attributes = new TransactionAttribute[0],
                Witnesses  = new Witness[] { witness }
            };

            Verify(tx);
        }