Example #1
0
        public void System_Blockchain_GetBlock()
        {
            var tx = new Transaction()
            {
                Script          = new byte[] { 0x01 },
                Attributes      = new TransactionAttribute[0],
                Cosigners       = new Cosigner[0],
                NetworkFee      = 0x02,
                SystemFee       = 0x03,
                Nonce           = 0x04,
                ValidUntilBlock = 0x05,
                Version         = 0x06,
                Witnesses       = new Witness[] { new Witness()
                                                  {
                                                      VerificationScript = new byte[] { 0x07 }
                                                  } },
                Sender = UInt160.Parse("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"),
            };

            var block = new Block()
            {
                Index     = 1,
                Timestamp = 2,
                Version   = 3,
                Witness   = new Witness()
                {
                    InvocationScript   = new byte[0],
                    VerificationScript = new byte[0]
                },
                PrevHash      = UInt256.Zero,
                MerkleRoot    = UInt256.Zero,
                NextConsensus = UInt160.Zero,
                ConsensusData = new ConsensusData()
                {
                    Nonce = 1, PrimaryIndex = 1
                },
                Transactions = new Transaction[] { tx }
            };

            var snapshot = TestBlockchain.GetStore().GetSnapshot();

            using (var script = new ScriptBuilder())
            {
                script.EmitPush(block.Hash.ToArray());
                script.EmitSysCall(InteropService.System_Blockchain_GetBlock);

                // Without block

                var engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0, true);
                engine.LoadScript(script.ToArray());

                Assert.AreEqual(engine.Execute(), VMState.HALT);
                Assert.AreEqual(1, engine.ResultStack.Count);
                Assert.IsTrue(engine.ResultStack.Peek().IsNull);

                // With block

                var blocks = (TestDataCache <UInt256, TrimmedBlock>)snapshot.Blocks;
                var txs    = (TestDataCache <UInt256, TransactionState>)snapshot.Transactions;
                blocks.Add(block.Hash, block.Trim());
                txs.Add(tx.Hash, new TransactionState()
                {
                    Transaction = tx, BlockIndex = block.Index, VMState = VMState.HALT
                });

                script.EmitSysCall(InteropService.Neo_Json_Serialize);
                engine = new ApplicationEngine(TriggerType.Application, null, snapshot, 0, true);
                engine.LoadScript(script.ToArray());

                Assert.AreEqual(engine.Execute(), VMState.HALT);
                Assert.AreEqual(1, engine.ResultStack.Count);
                Assert.IsInstanceOfType(engine.ResultStack.Peek(), typeof(ByteArray));
                Assert.AreEqual(engine.ResultStack.Pop().GetByteArray().ToHexString(),
                                "5b2235316138373966636161303339626461663437353436306637316334616130383562353964313833616239313764356437363762333865613738323766356266222c332c2230303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030222c2230303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030303030222c322c312c2230303030303030303030303030303030303030303030303030303030303030303030303030303030222c315d");
                Assert.AreEqual(0, engine.ResultStack.Count);

                // Clean
                blocks.Delete(block.Hash);
                txs.Delete(tx.Hash);
            }
        }
Example #2
0
        public void Save(MySqlConnection conn, JObject jToken)
        {
            JObject executions = null;

            try
            {
                if (jToken != null)
                {
                    executions = jToken["executions"];
                }
            }
            catch (Exception e)
            {
            }
            //try
            //{
            //    if (!TryGetDB(ChainHash, out DB db)) return;
            //    if (db.IsDisposed) return;
            //    UInt256 hash = UInt256.Parse(SpiderHelper.getString(jToken["txid"].ToString()));
            //    if (!db.TryGet(ReadOptions.Default, hash.ToArray(), out Slice value))
            //        throw new RpcException(-100, "Unknown transaction");
            //    result = JObject.Parse(value.ToString());
            //    if (result != null)
            //    executions = result["executions"];
            //}
            //catch (Exception e)
            //{
            //    LogConfig.Log($"error occured when call getapplicationlog, chain:{ChainHash} height:{blockHeight}, reason:{e.Message}", LogConfig.LogLevel.Error);
            //    //throw e;
            //}

            if (jToken != null && executions != null)
            {
                foreach (var execution in executions as JArray)
                {
                    List <string> slist = new List <string>();
                    slist.Add(SpiderHelper.getString(jToken["txid"].ToString()));
                    slist.Add(SpiderHelper.getString(execution["vmstate"].ToString()));
                    slist.Add(SpiderHelper.getString(execution["gas_consumed"].ToString()));
                    slist.Add(SpiderHelper.getString(execution["stack"].ToString()));
                    slist.Add(SpiderHelper.getString(execution["notifications"].ToString().Replace(@"[/n/r]", "")));

                    Dictionary <string, string> where = new Dictionary <string, string>();
                    where.Add("txid", SpiderHelper.getString(jToken["txid"].ToString()));
                    MysqlConn.Delete(conn, DataTableName, where);

                    MysqlConn.ExecuteDataInsert(conn, DataTableName, slist);

                    LogConfig.Log($"SaveNotify {ChainHash} {jToken["txid"]}", LogConfig.LogLevel.Info, ChainHash.ToString());

                    if (execution["vmstate"].ToString().Contains("FAULT"))
                    {
                        return;
                    }

                    JObject notifications = execution["notifications"];

                    foreach (JObject notify in notifications as JArray)
                    {
                        JArray values = notify["state"]["value"] as JArray;

                        if (values[0]["type"].ToString() == "ByteArray")
                        {
                            string transfer = Encoding.UTF8.GetString(SpiderHelper.HexString2Bytes(SpiderHelper.getString(values[0]["value"].ToString())));
                            string contract = SpiderHelper.getString(notify["contract"].ToString());

                            if (transfer == "transfer")
                            {
                                JObject nep5 = new JObject();
                                nep5["assetid"] = contract;
                                nep5Asset.Save(conn, nep5);

                                //存储Nep5Transfer内容
                                JObject tx = new JObject();
                                tx["txid"]  = SpiderHelper.getString(jToken["txid"].ToString());
                                tx["n"]     = 0;
                                tx["asset"] = contract;
                                if (SpiderHelper.getString(values[1]["value"].ToString()) == "")
                                {
                                    tx["from"] = "";
                                }
                                else
                                {
                                    tx["from"] = UInt160.Parse(SpiderHelper.getString(values[1]["value"].ToString())).ToAddress();
                                }

                                tx["to"] = UInt160.Parse(SpiderHelper.getString(values[2]["value"].ToString())).ToAddress();
                                if (SpiderHelper.getString(values[3]["type"].ToString()) == "ByteArray")
                                {
                                    tx["value"] = new BigInteger(SpiderHelper.HexString2Bytes(SpiderHelper.getString(values[3]["value"].ToString()))).ToString();
                                }
                                else
                                {
                                    tx["value"] = BigInteger.Parse(SpiderHelper.getString(values[3]["value"].ToString()), NumberStyles.AllowHexSpecifier).ToString();
                                }
                                JObject j = new JObject();
                                j["address"] = SpiderHelper.getString(tx["to"].ToString());
                                j["txid"]    = SpiderHelper.getString(tx["txid"].ToString());
                                address.Save(conn, j);
                                addressAsset.Save(conn, SpiderHelper.getString(tx["to"].ToString()), contract, "");
                                address_tx.Save(conn, j);
                                nep5Transfer.Save(conn, tx);
                            }
                        }
                    }
                }
            }
        }
Example #3
0
        protected virtual JObject SendMany(JArray _params)
        {
            CheckWallet();
            int     to_start = 0;
            UInt160 from     = null;

            if (_params[0] is JString)
            {
                from     = AddressToScriptHash(_params[0].AsString());
                to_start = 1;
            }
            JArray to = (JArray)_params[to_start];

            if (to.Count == 0)
            {
                throw new RpcException(-32602, "Invalid params");
            }
            Signer[] signers = _params.Count >= to_start + 2 ? ((JArray)_params[to_start + 1]).Select(p => new Signer()
            {
                Account = AddressToScriptHash(p.AsString()), Scopes = WitnessScope.CalledByEntry
            }).ToArray() : null;

            TransferOutput[] outputs = new TransferOutput[to.Count];
            for (int i = 0; i < to.Count; i++)
            {
                UInt160         asset_id   = UInt160.Parse(to[i]["asset"].AsString());
                AssetDescriptor descriptor = new AssetDescriptor(asset_id);
                outputs[i] = new TransferOutput
                {
                    AssetId    = asset_id,
                    Value      = BigDecimal.Parse(to[i]["value"].AsString(), descriptor.Decimals),
                    ScriptHash = AddressToScriptHash(to[i]["address"].AsString())
                };
                if (outputs[i].Value.Sign <= 0)
                {
                    throw new RpcException(-32602, "Invalid params");
                }
            }
            Transaction tx = wallet.MakeTransaction(outputs, from, signers);

            if (tx == null)
            {
                throw new RpcException(-300, "Insufficient funds");
            }

            ContractParametersContext transContext = new ContractParametersContext(tx);

            wallet.Sign(transContext);
            if (!transContext.Completed)
            {
                return(transContext.ToJson());
            }
            tx.Witnesses = transContext.GetWitnesses();
            if (tx.Size > 1024)
            {
                long calFee = tx.Size * 1000 + 100000;
                if (tx.NetworkFee < calFee)
                {
                    tx.NetworkFee = calFee;
                }
            }
            if (tx.NetworkFee > settings.MaxFee)
            {
                throw new RpcException(-301, "The necessary fee is more than the Max_fee, this transaction is failed. Please increase your Max_fee value.");
            }
            return(SignAndRelay(tx));
        }
Example #4
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            uint walletHeight = 0;

            if (Program.CurrentWallet != null)
            {
                walletHeight = (Program.CurrentWallet.WalletHeight > 0) ? Program.CurrentWallet.WalletHeight - 1 : 0;
            }

            lbl_height.Text = $"{walletHeight}/{Blockchain.Singleton.Height}/{Blockchain.Singleton.HeaderHeight}";

            lbl_count_node.Text = LocalNode.Singleton.ConnectedCount.ToString();
            TimeSpan persistence_span = DateTime.UtcNow - persistence_time;

            if (persistence_span < TimeSpan.Zero)
            {
                persistence_span = TimeSpan.Zero;
            }
            if (persistence_span > Blockchain.TimePerBlock)
            {
                toolStripProgressBar1.Style = ProgressBarStyle.Marquee;
            }
            else
            {
                toolStripProgressBar1.Value = persistence_span.Seconds;
                toolStripProgressBar1.Style = ProgressBarStyle.Blocks;
            }
            if (Program.CurrentWallet != null)
            {
                if (Program.CurrentWallet.WalletHeight <= Blockchain.Singleton.Height + 1)
                {
                    if (balance_changed)
                    {
                        using (Snapshot snapshot = Blockchain.Singleton.GetSnapshot())
                        {
                            IEnumerable <Coin> coins             = Program.CurrentWallet?.GetCoins().Where(p => !p.State.HasFlag(CoinState.Spent)) ?? Enumerable.Empty <Coin>();
                            Fixed8             bonus_available   = snapshot.CalculateBonus(Program.CurrentWallet.GetUnclaimedCoins().Select(p => p.Reference));
                            Fixed8             bonus_unavailable = snapshot.CalculateBonus(coins.Where(p => p.State.HasFlag(CoinState.Confirmed) && p.Output.AssetId.Equals(Blockchain.GoverningToken.Hash)).Select(p => p.Reference), snapshot.Height + 1);
                            Fixed8             bonus             = bonus_available + bonus_unavailable;
                            var assets = coins.GroupBy(p => p.Output.AssetId, (k, g) => new
                            {
                                Asset = snapshot.Assets.TryGet(k),
                                Value = g.Sum(p => p.Output.Value),
                                Claim = k.Equals(Blockchain.UtilityToken.Hash) ? bonus : Fixed8.Zero
                            }).ToDictionary(p => p.Asset.AssetId);
                            if (bonus != Fixed8.Zero && !assets.ContainsKey(Blockchain.UtilityToken.Hash))
                            {
                                assets[Blockchain.UtilityToken.Hash] = new
                                {
                                    Asset = snapshot.Assets.TryGet(Blockchain.UtilityToken.Hash),
                                    Value = Fixed8.Zero,
                                    Claim = bonus
                                };
                            }
                            var balance_ans = coins.Where(p => p.Output.AssetId.Equals(Blockchain.GoverningToken.Hash)).GroupBy(p => p.Output.ScriptHash).ToDictionary(p => p.Key, p => p.Sum(i => i.Output.Value));
                            var balance_anc = coins.Where(p => p.Output.AssetId.Equals(Blockchain.UtilityToken.Hash)).GroupBy(p => p.Output.ScriptHash).ToDictionary(p => p.Key, p => p.Sum(i => i.Output.Value));
                            foreach (ListViewItem item in listView1.Items)
                            {
                                UInt160 script_hash = item.Name.ToScriptHash();
                                Fixed8  ans         = balance_ans.ContainsKey(script_hash) ? balance_ans[script_hash] : Fixed8.Zero;
                                Fixed8  anc         = balance_anc.ContainsKey(script_hash) ? balance_anc[script_hash] : Fixed8.Zero;
                                item.SubItems["ans"].Text = ans.ToString();
                                item.SubItems["anc"].Text = anc.ToString();
                            }
                            foreach (AssetState asset in listView2.Items.OfType <ListViewItem>().Select(p => p.Tag as AssetState).Where(p => p != null).ToArray())
                            {
                                if (!assets.ContainsKey(asset.AssetId))
                                {
                                    listView2.Items.RemoveByKey(asset.AssetId.ToString());
                                }
                            }
                            foreach (var asset in assets.Values)
                            {
                                string value_text = asset.Value.ToString() + (asset.Asset.AssetId.Equals(Blockchain.UtilityToken.Hash) ? $"+({asset.Claim})" : "");
                                if (listView2.Items.ContainsKey(asset.Asset.AssetId.ToString()))
                                {
                                    listView2.Items[asset.Asset.AssetId.ToString()].SubItems["value"].Text = value_text;
                                }
                                else
                                {
                                    string asset_name = asset.Asset.AssetType == AssetType.GoverningToken ? "OXS" :
                                                        asset.Asset.AssetType == AssetType.UtilityToken ? "OXC" :
                                                        asset.Asset.GetName();
                                    listView2.Items.Add(new ListViewItem(new[]
                                    {
                                        new ListViewItem.ListViewSubItem
                                        {
                                            Name = "name",
                                            Text = asset_name
                                        },
                                        new ListViewItem.ListViewSubItem
                                        {
                                            Name = "type",
                                            Text = asset.Asset.AssetType.ToString()
                                        },
                                        new ListViewItem.ListViewSubItem
                                        {
                                            Name = "value",
                                            Text = value_text
                                        },
                                        new ListViewItem.ListViewSubItem
                                        {
                                            ForeColor = Color.Gray,
                                            Name      = "issuer",
                                            Text      = $"{LanHelper.LocalLanguage("unknown issuer")}[{asset.Asset.Owner}]"
                                        }
                                    }, -1, listView2.Groups["unchecked"])
                                    {
                                        Name = asset.Asset.AssetId.ToString(),
                                        Tag  = asset.Asset,
                                        UseItemStyleForSubItems = false
                                    });
                                }
                            }
                            balance_changed = false;
                        }
                    }
                    foreach (ListViewItem item in listView2.Groups["unchecked"].Items.OfType <ListViewItem>().ToArray())
                    {
                        ListViewItem.ListViewSubItem subitem = item.SubItems["issuer"];
                        AssetState             asset         = (AssetState)item.Tag;
                        CertificateQueryResult result;
                        if (asset.AssetType == AssetType.GoverningToken || asset.AssetType == AssetType.UtilityToken)
                        {
                            result = new CertificateQueryResult {
                                Type = CertificateQueryResultType.System
                            };
                        }
                        else
                        {
                            result = CertificateQueryService.Query(asset.Owner);
                        }
                        using (result)
                        {
                            subitem.Tag = result.Type;
                            switch (result.Type)
                            {
                            case CertificateQueryResultType.Querying:
                            case CertificateQueryResultType.QueryFailed:
                                break;

                            case CertificateQueryResultType.System:
                                subitem.ForeColor = Color.Green;
                                subitem.Text      = LanHelper.LocalLanguage("OX system");
                                break;

                            case CertificateQueryResultType.Invalid:
                                subitem.ForeColor = Color.Red;
                                subitem.Text      = $"[{ LanHelper.LocalLanguage("Invalid")}][{asset.Owner}]";
                                break;

                            case CertificateQueryResultType.Expired:
                                subitem.ForeColor = Color.Yellow;
                                subitem.Text      = $"[{LanHelper.LocalLanguage("Expired")}]{result.Certificate.Subject}[{asset.Owner}]";
                                break;

                            case CertificateQueryResultType.Good:
                                subitem.ForeColor = Color.Black;
                                subitem.Text      = $"{result.Certificate.Subject}[{asset.Owner}]";
                                break;
                            }
                            switch (result.Type)
                            {
                            case CertificateQueryResultType.System:
                            case CertificateQueryResultType.Missing:
                            case CertificateQueryResultType.Invalid:
                            case CertificateQueryResultType.Expired:
                            case CertificateQueryResultType.Good:
                                item.Group = listView2.Groups["checked"];
                                break;
                            }
                        }
                    }
                }
                if (check_nep5_balance && persistence_span > TimeSpan.FromSeconds(2))
                {
                    UInt160[] addresses = Program.CurrentWallet.GetAccounts().Select(p => p.ScriptHash).ToArray();
                    foreach (string s in Settings.Default.NEP5Watched)
                    {
                        UInt160 script_hash = UInt160.Parse(s);
                        byte[]  script;
                        using (ScriptBuilder sb = new ScriptBuilder())
                        {
                            foreach (UInt160 address in addresses)
                            {
                                sb.EmitAppCall(script_hash, "balanceOf", address);
                            }
                            sb.Emit(OpCode.DEPTH, OpCode.PACK);
                            sb.EmitAppCall(script_hash, "decimals");
                            sb.EmitAppCall(script_hash, "name");
                            script = sb.ToArray();
                        }
                        ApplicationEngine engine = ApplicationEngine.Run(script);
                        if (engine.State.HasFlag(VMState.FAULT))
                        {
                            continue;
                        }
                        string     name     = engine.ResultStack.Pop().GetString();
                        byte       decimals = (byte)engine.ResultStack.Pop().GetBigInteger();
                        BigInteger amount   = ((VMArray)engine.ResultStack.Pop()).Aggregate(BigInteger.Zero, (x, y) => x + y.GetBigInteger());
                        if (amount == 0)
                        {
                            listView2.Items.RemoveByKey(script_hash.ToString());
                            continue;
                        }
                        BigDecimal balance    = new BigDecimal(amount, decimals);
                        string     value_text = balance.ToString();
                        if (listView2.Items.ContainsKey(script_hash.ToString()))
                        {
                            listView2.Items[script_hash.ToString()].SubItems["value"].Text = value_text;
                        }
                        else
                        {
                            listView2.Items.Add(new ListViewItem(new[]
                            {
                                new ListViewItem.ListViewSubItem
                                {
                                    Name = "name",
                                    Text = name
                                },
                                new ListViewItem.ListViewSubItem
                                {
                                    Name = "type",
                                    Text = "NEP-5"
                                },
                                new ListViewItem.ListViewSubItem
                                {
                                    Name = "value",
                                    Text = value_text
                                },
                                new ListViewItem.ListViewSubItem
                                {
                                    ForeColor = Color.Gray,
                                    Name      = "issuer",
                                    Text      = $"ScriptHash:{script_hash}"
                                }
                            }, -1, listView2.Groups["checked"])
                            {
                                Name = script_hash.ToString(),
                                UseItemStyleForSubItems = false
                            });
                        }
                    }
                    check_nep5_balance = false;
                }
            }
        }
Example #5
0
        public void Test_GetNotifications()
        {
            var notifications = ((List <NotifyEventArgs>)_engine.Notifications);

            notifications.Clear();
            notifications.AddRange(new NotifyEventArgs[]
            {
                new NotifyEventArgs(null, UInt160.Zero, new Integer(0x01)),
                new NotifyEventArgs(null, UInt160.Parse("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"), new Integer(0x02))
            });

            var result = _engine.ExecuteTestCaseStandard("GetNotifications", new ByteArray(UInt160.Parse("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").ToArray()));

            Assert.AreEqual(1, result.Count);

            var item = result.Pop();

            Assert.IsInstanceOfType(item, typeof(Integer));
            Assert.AreEqual(0x02, item.GetBigInteger());

            _engine.Reset();
            result = _engine.ExecuteTestCaseStandard("GetAllNotifications");
            Assert.AreEqual(1, result.Count);

            item = result.Pop();
            Assert.IsInstanceOfType(item, typeof(Integer));
            Assert.AreEqual(0x03, item.GetBigInteger());
        }
Example #6
0
        public void Can_be_not_equal_to_null_of_object_type()
        {
            var a = UInt160.Parse("0x4520462a8c80056291f871da523bff0eb17e29d4");

            a.Equals((object)null).Should().BeFalse();
        }
        private dynamic dispatchEngineMethod(EngineMethod method, dynamic args)
        {
            switch (method)
            {
            case EngineMethod.create:
                TriggerType trigger   = (TriggerType)args.trigger;
                long        gas       = long.Parse((string)args.gas);
                IVerifiable container = null;
                if (args.container != null)
                {
                    container = deserializeContainer(args.container);
                }
                Block persistingBlock = null;
                if (args.persistingBlock != null)
                {
                    persistingBlock = new Block();
                    using (MemoryStream ms = new MemoryStream(args.persistingBlock))
                        using (BinaryReader reader = new BinaryReader(ms))
                        {
                            persistingBlock.Deserialize(reader);
                        }
                }
                ProtocolSettings settings = ProtocolSettings.Default;
                if (args.settings != null)
                {
                    settings = ProtocolSettings.Load(parseConfig(args.settings));
                }

                return(this._create(trigger, container, this.selectSnapshot(args.snapshot, false), persistingBlock, settings, gas));

            case EngineMethod.execute:
                return(this._execute());

            case EngineMethod.loadscript:
                Script    script          = new Script((byte[])args.script);
                CallFlags flags           = (CallFlags)((byte)args.flags);
                UInt160   scriptHash      = null;
                int       initialPosition = 0;
                int       rvcount         = -1;

                if (args.scriptHash != null)
                {
                    scriptHash = UInt160.Parse((string)args.scriptHash);
                }

                if (args.initialPosition != null)
                {
                    initialPosition = (int)args.initialPosition;
                }

                if (args.rvcount != null)
                {
                    rvcount = (int)args.rvcount;
                }

                return(this._loadScript(script, flags, scriptHash, rvcount, initialPosition));

            case EngineMethod.loadcontract:
                UInt160   contractHash   = new UInt160((byte[])args.hash);
                string    contractMethod = (string)args.method;
                CallFlags contractFlags  = (CallFlags)((byte)args.flags);
                int       pcount         = (int)args.pcount;

                return(this._loadContract(contractHash, contractMethod, pcount, contractFlags));

            case EngineMethod.getvmstate:
                return(this._getVMState());

            case EngineMethod.getresultstack:
                return(this._getResultStack());

            case EngineMethod.gettrigger:
                return(this._getTrigger());

            case EngineMethod.getgasconsumed:
                return(this._getGasConsumed());

            case EngineMethod.getnotifications:
                return(this._getNotifications());

            case EngineMethod.getlogs:
                return(this._getLogs());

            case EngineMethod.getfaultexception:
                return(this._getFaultException());

            case EngineMethod.dispose_engine:
                this.disposeEngine();

                return(true);

            case EngineMethod.push:
                return(this._push((string)args.item));

            default:
                throw new InvalidOperationException();
            }
        }
Example #8
0
        private JObject Process(string method, JArray _params)
        {
            switch (method)
            {
            case "getaccountstate":
            {
                UInt160 script_hash = _params[0].AsString().ToScriptHash();
                return(GetAccountState(script_hash));
            }

            case "getassetstate":
            {
                UInt256 asset_id = UInt256.Parse(_params[0].AsString());
                return(GetAssetState(asset_id));
            }

            case "getbestblockhash":
            {
                return(GetBestBlockHash());
            }

            case "getblock":
            {
                JObject key     = _params[0];
                bool    verbose = _params.Count >= 2 && _params[1].AsBoolean();
                return(GetBlock(key, verbose));
            }

            case "getblockcount":
            {
                return(GetBlockCount());
            }

            case "getblockhash":
            {
                uint height = uint.Parse(_params[0].AsString());
                return(GetBlockHash(height));
            }

            case "getblockheader":
            {
                JObject key     = _params[0];
                bool    verbose = _params.Count >= 2 && _params[1].AsBoolean();
                return(GetBlockHeader(key, verbose));
            }

            case "getblocksysfee":
            {
                uint height = uint.Parse(_params[0].AsString());
                return(GetBlockSysFee(height));
            }

            case "getconnectioncount":
            {
                return(GetConnectionCount());
            }

            case "getcontractstate":
            {
                UInt160 script_hash = UInt160.Parse(_params[0].AsString());
                return(GetContractState(script_hash));
            }

            case "getpeers":
            {
                return(GetPeers());
            }

            case "getrawmempool":
            {
                bool shouldGetUnverified = _params.Count >= 1 && _params[0].AsBoolean();
                return(GetRawMemPool(shouldGetUnverified));
            }

            case "getrawtransaction":
            {
                UInt256 hash    = UInt256.Parse(_params[0].AsString());
                bool    verbose = _params.Count >= 2 && _params[1].AsBoolean();
                return(GetRawTransaction(hash, verbose));
            }

            case "getstorage":
            {
                UInt160 script_hash = UInt160.Parse(_params[0].AsString());
                byte[]  key         = _params[1].AsString().HexToBytes();
                return(GetStorage(script_hash, key));
            }

            case "gettransactionheight":
            {
                UInt256 hash = UInt256.Parse(_params[0].AsString());
                return(GetTransactionHeight(hash));
            }

            case "gettxout":
            {
                UInt256 hash  = UInt256.Parse(_params[0].AsString());
                ushort  index = ushort.Parse(_params[1].AsString());
                return(GetTxOut(hash, index));
            }

            case "getvalidators":
            {
                return(GetValidators());
            }

            case "getversion":
            {
                return(GetVersion());
            }

            case "invoke":
            {
                UInt160             script_hash = UInt160.Parse(_params[0].AsString());
                ContractParameter[] parameters  = ((JArray)_params[1]).Select(p => ContractParameter.FromJson(p)).ToArray();
                return(Invoke(script_hash, parameters));
            }

            case "invokefunction":
            {
                UInt160             script_hash = UInt160.Parse(_params[0].AsString());
                string              operation   = _params[1].AsString();
                ContractParameter[] args        = _params.Count >= 3 ? ((JArray)_params[2]).Select(p => ContractParameter.FromJson(p)).ToArray() : new ContractParameter[0];
                return(InvokeFunction(script_hash, operation, args));
            }

            case "invokescript":
            {
                byte[] script = _params[0].AsString().HexToBytes();
                return(InvokeScript(script));
            }

            case "listplugins":
            {
                return(ListPlugins());
            }

            case "sendrawtransaction":
            {
                Transaction tx = Transaction.DeserializeFrom(_params[0].AsString().HexToBytes());
                return(SendRawTransaction(tx));
            }

            case "submitblock":
            {
                Block block = _params[0].AsString().HexToBytes().AsSerializable <Block>();
                return(SubmitBlock(block));
            }

            case "validateaddress":
            {
                string address = _params[0].AsString();
                return(ValidateAddress(address));
            }

            default:
                throw new RpcException(-32601, "Method not found");
            }
        }
Example #9
0
        private bool OnStressTestingCommand(string[] args)
        {
            if (Settings.Default.EnableManualParam == 1)
            {
                Console.Write("Transaction Type, 0 - NEP5 SmartContract, 1 - NativeNEP5, 2 - BCP:");
                var param1 = Console.ReadLine();
                Console.Write("Concurrency count:");
                var param2 = Console.ReadLine();
                Console.Write("Totoal transaction count:");
                var param3 = Console.ReadLine();
                Console.Write("Transfer value:");
                var param4 = Console.ReadLine();
                Console.Write("Random target address, 0 - no, 1 - yes:");
                var param5 = Console.ReadLine();
                Console.Write("Random gas price, 0 - no, 1 - yes:");
                var param6 = Console.ReadLine();

                transactionType     = int.Parse(param1);
                transferCount       = int.Parse(param3);
                concurrencyCount    = int.Parse(param2);
                transferValue       = param4;
                randomTargetAddress = int.Parse(param5) == 1;
                randomGasPrice      = int.Parse(param6) == 1;
            }
            else
            {
                transactionType     = Settings.Default.TransactionType;
                transferCount       = Settings.Default.TransferCount;
                concurrencyCount    = Settings.Default.ConcurrencyCount;
                transferValue       = Settings.Default.TransferValue.ToString();
                randomTargetAddress = Settings.Default.RandomTargetAddress == 1;
                randomGasPrice      = Settings.Default.RandomGasPrice == 1;
            }

            preventOverflow  = Settings.Default.PreventOverflow == 1;
            printErrorReason = Settings.Default.PrintErrorReason == 1;

            string chainHash = Settings.Default.TargetChainHash;
            string WIF       = Settings.Default.WIF;
            string targetWIF = Settings.Default.TargetWIF;

            keypair       = ZoroHelper.GetKeyPairFromWIF(WIF);
            scriptHash    = ZoroHelper.GetPublicKeyHash(keypair.PublicKey);
            targetAddress = ZoroHelper.GetPublicKeyHashFromWIF(targetWIF);

            nep5ContractHash  = UInt160.Parse(Settings.Default.NEP5Hash);
            nativeNEP5AssetId = UInt160.Parse(Settings.Default.NativeNEP5Hash);

            Blockchain blockchain = ZoroChainSystem.Singleton.GetBlockchain(chainHash);

            if (blockchain == null)
            {
                return(true);
            }

            if (randomTargetAddress)
            {
                PluginManager.EnableLog(false);

                InitializeRandomTargetAddressList(transferCount);

                PluginManager.EnableLog(true);
            }

            if (transactionType == 0 || transactionType == 1 || transactionType == 2)
            {
                Console.WriteLine($"From:{WIF}");
                Console.WriteLine($"To:{targetWIF}");
                Console.WriteLine($"Count:{transferCount}");
                Console.WriteLine($"Value:{transferValue}");
            }

            cancelTokenSource = new CancellationTokenSource();

            Task.Run(() => RunTask(chainHash, blockchain));

            Console.WriteLine("Input [enter] to stop:");
            var input = Console.ReadLine();

            cancelTokenSource.Cancel();

            return(true);
        }
        public void TestIsAllowed()
        {
            ContractManifest   contractManifest1   = TestUtils.CreateDefaultManifest();
            ContractPermission contractPermission1 = ContractPermission.DefaultPermission;

            contractPermission1.Contract = ContractPermissionDescriptor.Create(UInt160.Zero);
            Assert.AreEqual(true, contractPermission1.IsAllowed(new ContractState()
            {
                Hash = UInt160.Zero, Manifest = contractManifest1
            }, "AAA"));
            contractPermission1.Contract = ContractPermissionDescriptor.CreateWildcard();

            ContractManifest   contractManifest2   = TestUtils.CreateDefaultManifest();
            ContractPermission contractPermission2 = ContractPermission.DefaultPermission;

            contractPermission2.Contract = ContractPermissionDescriptor.Create(UInt160.Parse("0x0000000000000000000000000000000000000001"));
            Assert.AreEqual(false, contractPermission2.IsAllowed(new ContractState()
            {
                Hash = UInt160.Zero, Manifest = contractManifest2
            }, "AAA"));
            contractPermission2.Contract = ContractPermissionDescriptor.CreateWildcard();

            Random random = new();

            byte[] privateKey3 = new byte[32];
            random.NextBytes(privateKey3);
            ECPoint          publicKey3        = ECCurve.Secp256r1.G * privateKey3;
            ContractManifest contractManifest3 = TestUtils.CreateDefaultManifest();

            contractManifest3.Groups = new ContractGroup[] { new ContractGroup()
                                                             {
                                                                 PubKey = publicKey3
                                                             } };
            ContractPermission contractPermission3 = ContractPermission.DefaultPermission;

            contractPermission3.Contract = ContractPermissionDescriptor.Create(publicKey3);
            Assert.AreEqual(true, contractPermission3.IsAllowed(new ContractState()
            {
                Hash = UInt160.Zero, Manifest = contractManifest3
            }, "AAA"));
            contractPermission3.Contract = ContractPermissionDescriptor.CreateWildcard();

            byte[] privateKey41 = new byte[32];
            random.NextBytes(privateKey41);
            ECPoint publicKey41 = ECCurve.Secp256r1.G * privateKey41;

            byte[] privateKey42 = new byte[32];
            random.NextBytes(privateKey42);
            ECPoint          publicKey42       = ECCurve.Secp256r1.G * privateKey42;
            ContractManifest contractManifest4 = TestUtils.CreateDefaultManifest();

            contractManifest4.Groups = new ContractGroup[] { new ContractGroup()
                                                             {
                                                                 PubKey = publicKey42
                                                             } };
            ContractPermission contractPermission4 = ContractPermission.DefaultPermission;

            contractPermission4.Contract = ContractPermissionDescriptor.Create(publicKey41);
            Assert.AreEqual(false, contractPermission4.IsAllowed(new ContractState()
            {
                Hash = UInt160.Zero, Manifest = contractManifest4
            }, "AAA"));
            contractPermission4.Contract = ContractPermissionDescriptor.CreateWildcard();
        }
Example #11
0
        private static async Task WalletAndTransactionsTest()
        {
            // Create online wallet and import account
            var walletManager   = new WalletManager(new NeoScanRestService(NeoScanNet.MainNet), RpcClient);
            var importedAccount = walletManager.ImportAccount("WIF HERE (or use NEP2 bellow)", "Account_label");
            //var importedAccount = walletManager.ImportAccount("encryptedPrivateKey", "password", "Account_label");

            var neoService = new NeoApiService(RpcClient);

            //invoke test example using Phantasma smart contract
            var method             = "getMailboxFromAddress";                    //operation
            var contractScriptHash = "ed07cffad18f1308db51920d99a2af60ac66a7b3"; // smart contract scripthash
            var script             = NEP6.Helpers.Utils.GenerateScript(contractScriptHash, method,
                                                                       new object[] { "ARcZoZPn1ReBo4LPLvkEteyLu6S2A5cvY2".ToScriptHash().ToArray() });
            var result = await neoService.Contracts.InvokeScript.SendRequestAsync(script.ToHexString());

            var content = Encoding.UTF8.GetString(result.Stack[0].Value.ToString().HexToBytes()); //the way you read a result can vary

            //call contract example using Phantasma smart contract
            var RegisterInboxOperation = "registerMailbox"; //operation
            var user = importedAccount.Address.ToArray();
            var args = new object[] { user, "neomodules" };

            var transaction = await importedAccount.TransactionManager.CallContract("ed07cffad18f1308db51920d99a2af60ac66a7b3",
                                                                                    RegisterInboxOperation, //operation
                                                                                    args,                   // arguments
                                                                                    null,                   // array of transfer outputs you want to attach gas or neo with the contract call (optional)
                                                                                    0m,                     // network fee (optional)
                                                                                    null                    // attributes (optional)
                                                                                    );


            // list of transfer outputs
            var transferOutputWithNep5AndGas = new List <TransferOutput>
            {
                new TransferOutput
                {
                    AssetId    = UInt160.Parse("a58b56b30425d3d1f8902034996fcac4168ef71d"), //  e.g. Script Hash of ASA
                    Value      = BigDecimal.Parse("0.0001", byte.Parse("8")),               // majority of NEP5 tokens have 8 decimals
                    ScriptHash = "AddressScriptHash to sent here".ToScriptHash(),
                },
                new TransferOutput
                {
                    AssetId    = NEP6.Helpers.Utils.GasToken,                  //GAS
                    Value      = BigDecimal.Parse("0.00001", byte.Parse("8")), // GAS has 8 decimals too
                    ScriptHash = "AddressScriptHash to sent here".ToScriptHash(),
                }
            };

            var transferOutputWithOnlyGas = new List <TransferOutput>
            {
                new TransferOutput
                {
                    AssetId    = NEP6.Helpers.Utils.GasToken,                  //GAS
                    Value      = BigDecimal.Parse("0.00001", byte.Parse("8")), // GAS has 8 decimals too
                    ScriptHash = "AddressScriptHash to sent here".ToScriptHash(),
                }
            };

            // Claims unclaimed gas. Does not spent your neo to make gas claimable, you have to do it yourself!
            var claim = await importedAccount.TransactionManager.ClaimGas();

            // Transfer NEP5 and gas with fee
            var invocationTx = await importedAccount.TransactionManager.TransferNep5(null, transferOutputWithNep5AndGas, null, 0.00001m);

            // Send native assets (NEO and GAS) with fee
            var nativeTx = await importedAccount.TransactionManager.SendNativeAsset(null, transferOutputWithOnlyGas, null, 0.0001m);

            // Call contract
            var scriptHash = "a58b56b30425d3d1f8902034996fcac4168ef71d".ToScriptHash().ToArray(); // ASA e.g
            var operation  = "your operation here";
            var arguments  = new object[] { "arg1", "arg2", "etc" };

            // Estimate Gas consumed from contract call
            var estimateContractGasCall =
                await importedAccount.TransactionManager.EstimateGasContractInvocation(scriptHash, operation, arguments);

            // Confirm a transaction
            var confirmedTransaction =
                await importedAccount.TransactionManager.WaitForTxConfirmation(invocationTx.Hash.ToString(), 10000, 10);
        }
Example #12
0
        public JObject Process(string method, JArray _params)
        {
            try
            {
                switch (method)
                {
                case "getbestblockhash":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    return(GetBestBlockHash(blockchain));
                }

                case "getblock":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    JObject    key        = _params[1];
                    bool       verbose    = _params.Count >= 3 && _params[2].AsBoolean();
                    return(GetBlock(blockchain, key, verbose));
                }

                case "getblockcount":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    return(GetBlockCount(blockchain));
                }

                case "getblockhash":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    uint       height     = uint.Parse(_params[1].AsString());
                    return(GetBlockHash(blockchain, height));
                }

                case "getblockheader":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    JObject    key        = _params[1];
                    bool       verbose    = _params.Count >= 3 && _params[2].AsBoolean();
                    return(GetBlockHeader(blockchain, key, verbose));
                }

                case "getblocksysfee":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    uint       height     = uint.Parse(_params[1].AsString());
                    return(GetBlockSysFee(blockchain, height));
                }

                case "getconnectioncount":
                {
                    LocalNode localNode = GetTargetNode(_params[0]);
                    return(localNode != null ? localNode.ConnectedCount : 0);
                }

                case "getcontractstate":
                {
                    Blockchain blockchain  = GetTargetChain(_params[0]);
                    UInt160    script_hash = UInt160.Parse(_params[1].AsString());
                    return(GetContractState(blockchain, script_hash));
                }

                case "getpeers":
                {
                    return(GetPeers(_params[0]));
                }

                case "getrawmempool":
                {
                    Blockchain blockchain          = GetTargetChain(_params[0]);
                    bool       shouldGetUnverified = _params.Count >= 2 && _params[1].AsBoolean();
                    return(GetRawMemPool(blockchain, shouldGetUnverified));
                }

                case "getrawmempoolcount":
                {
                    Blockchain blockchain          = GetTargetChain(_params[0]);
                    bool       shouldGetUnverified = _params.Count >= 2 && _params[1].AsBoolean();
                    return(GetRawMemPoolCount(blockchain, shouldGetUnverified));
                }

                case "getrawtransaction":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    UInt256    hash       = UInt256.Parse(_params[1].AsString());
                    bool       verbose    = _params.Count >= 3 && _params[2].AsBoolean();
                    return(GetRawTransaction(blockchain, hash, verbose));
                }

                case "getstorage":
                {
                    Blockchain blockchain  = GetTargetChain(_params[0]);
                    UInt160    script_hash = UInt160.Parse(_params[1].AsString());
                    byte[]     key         = _params[2].AsString().HexToBytes();
                    return(GetStorage(blockchain, script_hash, key));
                }

                case "gettransactionheight":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    UInt256    hash       = UInt256.Parse(_params[1].AsString());
                    return(GetTransactionHeight(blockchain, hash));
                }

                case "getvalidators":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    return(GetValidators(blockchain));
                }

                case "getversion":
                {
                    return(GetVersion());
                }

                case "invokefunction":
                {
                    UInt160             script_hash = UInt160.Parse(_params[1].AsString());
                    string              operation   = _params[2].AsString();
                    ContractParameter[] args        = _params.Count >= 4 ? ((JArray)_params[3]).Select(p => ContractParameter.FromJson(p)).ToArray() : new ContractParameter[0];
                    return(InvokeFunction(_params[0], script_hash, operation, args));
                }

                case "invokescript":
                {
                    byte[] script = _params[1].AsString().HexToBytes();
                    return(InvokeScript(_params[0], script));
                }

                case "listplugins":
                {
                    return(ListPlugins());
                }

                case "sendrawtransaction":
                {
                    ZoroSystem targetSystem = GetTargetSystem(_params[0]);
                    if (targetSystem != null)
                    {
                        Transaction tx = Transaction.DeserializeFrom(_params[1].AsString().HexToBytes());
                        return(SendRawTransaction(targetSystem, tx));
                    }
                    return(RelayResultReason.Invalid);
                }

                case "submitblock":
                {
                    ZoroSystem targetSystem = GetTargetSystem(_params[0]);
                    if (targetSystem != null)
                    {
                        Block block = _params[0].AsString().HexToBytes().AsSerializable <Block>();
                        return(SubmitBlock(targetSystem, block));
                    }
                    return(RelayResultReason.Invalid);
                }

                case "validateaddress":
                {
                    string address = _params[0].AsString();
                    return(ValidateAddress(address));
                }

                case "getappchainhashlist":
                {
                    return(GetAppChainHashList());
                }

                case "getappchainstate":
                {
                    Blockchain blockchain  = GetTargetChain(_params[0]);
                    UInt160    script_hash = UInt160.Parse(_params[0].AsString());
                    return(GetAppChainState(blockchain, script_hash));
                }

                case "getappchainlist":
                {
                    return(GetAppChainList());
                }

                case "getappchainlistenerports":
                {
                    return(GetAppChainListenerPorts());
                }

                case "estimategas":
                {
                    Blockchain  blockchain = GetTargetChain(_params[0]);
                    Transaction tx         = Transaction.DeserializeFrom(_params[1].AsString().HexToBytes());
                    return(GetEstimateGas(blockchain, tx));
                }

                default:
                    throw new RpcException(-32601, "Method not found");
                }
            }
            catch (Exception ex)
            {
                JObject json = new JObject();
                json["message"] = ex.Message;
                json["method"]  = method;
                json["source"]  = ex.Source;
                return(json);
            }
        }
Example #13
0
        public String ExecuteFunction(byte[] fileContents, string function, string[] parameterTypes, string[] parameterValues, string returnType, Hashtable store)
        {
            if (fileContents == null || fileContents.Length == 0)
            {
                return("ERROR");
            }

            var generator = new RNGCryptoServiceProvider();

            /** CREATE FAKE PREVIOUS TRANSACTION */
            var initialTransaction = new CustomTransaction(TransactionType.ContractTransaction);
            var transactionOutput  = new TransactionOutput
            {
                ScriptHash = UInt160.Parse("A518E4F561F37782B39AB4F28B8D538F47B8AA6C"),
                Value      = new Neo.Fixed8(10),
                AssetId    = UInt256.Parse("B283C915F482DBC3A89189D865C4B42E74210BED735DCD307B1915C4E0A46C01")
            };

            initialTransaction.Outputs = new TransactionOutput[] { transactionOutput };

            /** CREATE FAKE CURRENT TRANSACTION */
            var coinRef = new CoinReference();

            coinRef.PrevHash  = initialTransaction.Hash;
            coinRef.PrevIndex = 0;
            var currentTransaction = new CustomTransaction(TransactionType.ContractTransaction);

            currentTransaction.Inputs = new CoinReference[] { coinRef };
            var hash = currentTransaction.Hash;

            CustomInteropService service = new CustomInteropService();

            service.storageContext.data = store;

            service.transactions.Add(initialTransaction.Hash.ToArray(), initialTransaction);
            service.transactions.Add(currentTransaction.Hash.ToArray(), currentTransaction);

            var engine = new ExecutionEngine(currentTransaction, Crypto.Default, null, service);

            engine.LoadScript(fileContents);
            IList <ContractParameter> parameters = new List <ContractParameter>();

            for (int i = 0; i < parameterTypes.Length; i++)
            {
                var param = parameterTypes[i];
                if (param == "string")
                {
                    parameters.Add(new ContractParameter
                    {
                        Type  = ContractParameterType.String,
                        Value = parameterValues[i]
                    });
                }

                if (param == "integer")
                {
                    parameters.Add(new ContractParameter
                    {
                        Type  = ContractParameterType.Integer,
                        Value = BigInteger.Parse(parameterValues[i])
                    });
                }
            }

            var parameter = new ContractParameter
            {
                Type  = ContractParameterType.Array,
                Value = parameters
            };

            using (ScriptBuilder sb = new ScriptBuilder())
            {
                Neo.VM.Helper.EmitPush(sb, parameter);
                sb.EmitPush(function);
                engine.LoadScript(sb.ToArray());
            }

            engine.Execute(); // start execution

            //var result = engine.EvaluationStack.Peek().GetBoolean(); // set the return value here
            if (engine.State == VMState.BREAK || engine.State == VMState.FAULT)
            {
                return("ERROR");
            }

            if (returnType == "boolean")
            {
                return(engine.EvaluationStack.Peek().GetBoolean().ToString());
            }

            if (returnType == "string")
            {
                return(engine.EvaluationStack.Peek().GetString());
            }

            if (returnType == "integer")
            {
                return(engine.EvaluationStack.Peek().GetBigInteger().ToString());
            }

            return("Unknown Result Type");
        }
Example #14
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            // those you need to set up------------------------------------------------------------

            rpcClient = new RpcClient("http://localhost:20002");                              // your node url, such as "http://47.89.240.111:12332"
            nep2Key   = "6PYLjXkQzADs7r36XQjByJXoggm3beRh6UzxuN59NZiBxFBnm1HPvv3ytM";         // you can find this in your wallet, the "key" field
            string password = "******";                                                            // your password

            UInt160 from       = "AQzRMe3zyGS8W177xLJfewRRQZY2kddMun".ToScriptHash();         // your account address, such as "APPmjituYcgfNxjuQDy9vP73R2PmhFsYJR"
            UInt160 scriptHash = UInt160.Parse("0x6b4f6926c28523519c758ec2015a60ddfe8b37dc"); // your contract script hash, such as "0x5be5fc0641e44b0003262b3fda775ea60133cb05"
            //byte[] param = new byte[] { }; // your contract parameter
            BigInteger param = 2;

            //-------------------------------------------------------------------------------------------

            ScriptBuilder sb = new ScriptBuilder().EmitAppCall(scriptHash, "getProxyHash", new ContractParameter[] { new ContractParameter()
                                                                                                                     {
                                                                                                                         Type = ContractParameterType.Integer, Value = param
                                                                                                                     } });
            var script = sb.ToArray();

            InvocationTransaction itx = new InvocationTransaction();

            itx.Inputs     = new CoinReference[] { };
            itx.Outputs    = new TransactionOutput[] { };
            itx.Attributes = new TransactionAttribute[] { };
            itx.Witnesses  = new Witness[] { };
            itx.Version    = 1;
            itx.Script     = script;
            itx.Gas        = GetGasConsumed(script);

            Fixed8 fee = itx.Gas;

            if (itx.Size > 1024)
            {
                fee += Fixed8.FromDecimal(0.001m);
                fee += Fixed8.FromDecimal(itx.Size * 0.00001m);
            }

            var(inputs, sum) = GetTransactionInputs(from, Blockchain.UtilityToken.Hash, fee);
            if (sum > fee)
            {
                itx.Outputs = itx.Outputs.Concat(new[] { new TransactionOutput()
                                                         {
                                                             AssetId = Blockchain.UtilityToken.Hash, Value = sum - fee, ScriptHash = from
                                                         } }).ToArray();
            }
            itx.Inputs = itx.Inputs.Concat(inputs).ToArray();

            // sign the itx
            Random random = new Random();
            var    nonce  = new byte[32];

            random.NextBytes(nonce);
            TransactionAttribute[] attributes = new TransactionAttribute[]
            {
                new TransactionAttribute()
                {
                    Usage = TransactionAttributeUsage.Script, Data = from.ToArray()
                },
                new TransactionAttribute()
                {
                    Usage = TransactionAttributeUsage.Remark1, Data = nonce
                }                                                                                      // if a transaction has no inputs and outputs, need to add nonce for duplication
            };
            itx.Attributes = itx.Attributes.Concat(attributes).ToArray();

            KeyPair keyPair = WalletHelper.KeyPairFromNep2(nep2Key, password);
            Witness witness = WalletHelper.CreateTransactionWitness(itx, keyPair);

            itx.Witnesses = itx.Witnesses.Concat(new[] { witness }).ToArray();

            var raw  = itx.ToArray();
            var txid = rpcClient.SendRawTransaction(raw);

            Console.WriteLine(txid.ToString());
        }
 public AccountItemBuilder WithHash(string hash)
 {
     this.hashInternal = UInt160.Parse(hash);
     return(this);
 }
Example #16
0
        private bool OnInvokeCommand(string[] args)
        {
            var scriptHash = UInt160.Parse(args[1]);

            List <ContractParameter> contractParameters = new List <ContractParameter>();

            for (int i = 3; i < args.Length; i++)
            {
                contractParameters.Add(new ContractParameter()
                {
                    // TODO: support contract params of type other than string.
                    Type  = ContractParameterType.String,
                    Value = args[i]
                });
            }

            Transaction tx = new Transaction
            {
                Sender     = UInt160.Zero,
                Attributes = new TransactionAttribute[0],
                Witness    = new Witness
                {
                    InvocationScript   = new byte[0],
                    VerificationScript = new byte[0]
                }
            };

            using (ScriptBuilder scriptBuilder = new ScriptBuilder())
            {
                scriptBuilder.EmitAppCall(scriptHash, args[2], contractParameters.ToArray());
                tx.Script = scriptBuilder.ToArray();
                Console.WriteLine($"Invoking script with: '{tx.Script.ToHexString()}'");
            }

            ApplicationEngine engine = ApplicationEngine.Run(tx.Script, tx);

            Console.WriteLine($"VM State: {engine.State}");
            Console.WriteLine($"Gas Consumed: {engine.GasConsumed}");
            Console.WriteLine($"Evaluation Stack: {new JArray(engine.ResultStack.Select(p => p.ToParameter().ToJson()))}");
            Console.WriteLine();
            if (engine.State.HasFlag(VMState.FAULT))
            {
                Console.WriteLine("Engine faulted.");
                return(true);
            }
            if (NoWallet())
            {
                return(true);
            }
            try
            {
                Program.Wallet.FillTransaction(tx);
            }
            catch (InvalidOperationException)
            {
                Console.WriteLine("Error: insufficient balance.");
                return(true);
            }
            if (ReadUserInput("relay tx(no|yes)") != "yes")
            {
                return(true);
            }
            return(SignAndSendTx(tx));
        }
Example #17
0
        public void Can_parse_and_stringify()
        {
            var actual = UInt160.Parse("0x4520462a8c80056291f871da523bff0eb17e29d4");

            actual.ToString().Should().Be("0x4520462a8c80056291f871da523bff0eb17e29d4");
        }
Example #18
0
        private bool OnSendCommand(string[] args)
        {
            if (args.Length < 4 || args.Length > 5)
            {
                Console.WriteLine("error");
                return(true);
            }
            if (NoWallet())
            {
                return(true);
            }
            string password = ReadUserInput("password", true);

            if (password.Length == 0)
            {
                Console.WriteLine("cancelled");
                return(true);
            }
            if (!Program.Wallet.VerifyPassword(password))
            {
                Console.WriteLine("Incorrect password");
                return(true);
            }
            UInt160 assetId;

            switch (args[1].ToLower())
            {
            case "neo":
                assetId = NativeContract.NEO.Hash;
                break;

            case "gas":
                assetId = NativeContract.GAS.Hash;
                break;

            default:
                assetId = UInt160.Parse(args[1]);
                break;
            }
            UInt160         to = args[2].ToScriptHash();
            Transaction     tx;
            AssetDescriptor descriptor = new AssetDescriptor(assetId);

            if (!BigDecimal.TryParse(args[3], descriptor.Decimals, out BigDecimal amount) || amount.Sign <= 0)
            {
                Console.WriteLine("Incorrect Amount Format");
                return(true);
            }
            tx = Program.Wallet.MakeTransaction(null, new[]
            {
                new TransferOutput
                {
                    AssetId    = assetId,
                    Value      = amount,
                    ScriptHash = to
                }
            });

            if (tx == null)
            {
                Console.WriteLine("Insufficient funds");
                return(true);
            }

            ContractParametersContext context = new ContractParametersContext(tx);

            Program.Wallet.Sign(context);
            if (context.Completed)
            {
                tx.Witness = context.GetWitness();
                system.LocalNode.Tell(new LocalNode.Relay {
                    Inventory = tx
                });
                Console.WriteLine($"TXID: {tx.Hash}");
            }
            else
            {
                Console.WriteLine("SignatureContext:");
                Console.WriteLine(context.ToString());
            }

            return(true);
        }
Example #19
0
        private JObject Process(string method, JArray _params)
        {
            switch (method)
            {
            case "dumpprivkey":
                if (wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    UInt160       scriptHash = _params[0].AsString().ToScriptHash();
                    WalletAccount account    = wallet.GetAccount(scriptHash);
                    return(account.GetKey().Export());
                }

            case "getaccountstate":
            {
                UInt160      script_hash = _params[0].AsString().ToScriptHash();
                AccountState account     = Blockchain.Singleton.Store.GetAccounts().TryGet(script_hash) ?? new AccountState(script_hash);
                return(account.ToJson());
            }

            case "getassetstate":
            {
                UInt256    asset_id = UInt256.Parse(_params[0].AsString());
                AssetState asset    = Blockchain.Singleton.Store.GetAssets().TryGet(asset_id);
                return(asset?.ToJson() ?? throw new RpcException(-100, "Unknown asset"));
            }

            case "getbalance":
                if (wallet == null)
                {
                    throw new RpcException(-400, "Access denied.");
                }
                else
                {
                    JObject json = new JObject();
                    switch (UIntBase.Parse(_params[0].AsString()))
                    {
                    case UInt160 asset_id_160:         //NEP-5 balance
                        json["balance"] = wallet.GetAvailable(asset_id_160).ToString();
                        break;

                    case UInt256 asset_id_256:         //Global Assets balance
                        IEnumerable <Coin> coins = wallet.GetCoins().Where(p => !p.State.HasFlag(CoinState.Spent) && p.Output.AssetId.Equals(asset_id_256));
                        json["balance"]   = coins.Sum(p => p.Output.Value).ToString();
                        json["confirmed"] = coins.Where(p => p.State.HasFlag(CoinState.Confirmed)).Sum(p => p.Output.Value).ToString();
                        break;
                    }
                    return(json);
                }

            case "getbestblockhash":
                return(Blockchain.Singleton.CurrentBlockHash.ToString());

            case "getblock":
            {
                Block block;
                if (_params[0] is JNumber)
                {
                    uint index = (uint)_params[0].AsNumber();
                    block = Blockchain.Singleton.Store.GetBlock(index);
                }
                else
                {
                    UInt256 hash = UInt256.Parse(_params[0].AsString());
                    block = Blockchain.Singleton.Store.GetBlock(hash);
                }
                if (block == null)
                {
                    throw new RpcException(-100, "Unknown block");
                }
                bool verbose = _params.Count >= 2 && _params[1].AsBooleanOrDefault(false);
                if (verbose)
                {
                    JObject json = block.ToJson();
                    json["confirmations"] = Blockchain.Singleton.Height - block.Index + 1;
                    UInt256 hash = Blockchain.Singleton.Store.GetNextBlockHash(block.Hash);
                    if (hash != null)
                    {
                        json["nextblockhash"] = hash.ToString();
                    }
                    return(json);
                }
                return(block.ToArray().ToHexString());
            }

            case "getblockcount":
                return(Blockchain.Singleton.Height + 1);

            case "getblockhash":
            {
                uint height = (uint)_params[0].AsNumber();
                if (height <= Blockchain.Singleton.Height)
                {
                    return(Blockchain.Singleton.GetBlockHash(height).ToString());
                }
                throw new RpcException(-100, "Invalid Height");
            }

            case "getblockheader":
            {
                Header header;
                if (_params[0] is JNumber)
                {
                    uint height = (uint)_params[0].AsNumber();
                    header = Blockchain.Singleton.Store.GetHeader(height);
                }
                else
                {
                    UInt256 hash = UInt256.Parse(_params[0].AsString());
                    header = Blockchain.Singleton.Store.GetHeader(hash);
                }
                if (header == null)
                {
                    throw new RpcException(-100, "Unknown block");
                }

                bool verbose = _params.Count >= 2 && _params[1].AsBooleanOrDefault(false);
                if (verbose)
                {
                    JObject json = header.ToJson();
                    json["confirmations"] = Blockchain.Singleton.Height - header.Index + 1;
                    UInt256 hash = Blockchain.Singleton.Store.GetNextBlockHash(header.Hash);
                    if (hash != null)
                    {
                        json["nextblockhash"] = hash.ToString();
                    }
                    return(json);
                }

                return(header.ToArray().ToHexString());
            }

            case "getblocksysfee":
            {
                uint height = (uint)_params[0].AsNumber();
                if (height <= Blockchain.Singleton.Height)
                {
                    return(Blockchain.Singleton.Store.GetSysFeeAmount(height).ToString());
                }
                throw new RpcException(-100, "Invalid Height");
            }

            case "getconnectioncount":
                return(LocalNode.Singleton.ConnectedCount);

            case "getcontractstate":
            {
                UInt160       script_hash = UInt160.Parse(_params[0].AsString());
                ContractState contract    = Blockchain.Singleton.Store.GetContracts().TryGet(script_hash);
                return(contract?.ToJson() ?? throw new RpcException(-100, "Unknown contract"));
            }

            case "getnewaddress":
                if (wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    WalletAccount account = wallet.CreateAccount();
                    if (wallet is NEP6Wallet nep6)
                    {
                        nep6.Save();
                    }
                    return(account.Address);
                }

            case "getpeers":
            {
                JObject json = new JObject();
                json["unconnected"] = new JArray(LocalNode.Singleton.GetUnconnectedPeers().Select(p =>
                    {
                        JObject peerJson    = new JObject();
                        peerJson["address"] = p.Address.ToString();
                        peerJson["port"]    = p.Port;
                        return(peerJson);
                    }));
                json["bad"]       = new JArray();   //badpeers has been removed
                json["connected"] = new JArray(LocalNode.Singleton.GetRemoteNodes().Select(p =>
                    {
                        JObject peerJson    = new JObject();
                        peerJson["address"] = p.Remote.Address.ToString();
                        peerJson["port"]    = p.ListenerPort;
                        return(peerJson);
                    }));
                return(json);
            }

            case "getrawmempool":
                return(new JArray(Blockchain.Singleton.GetMemoryPool().Select(p => (JObject)p.Hash.ToString())));

            case "getrawtransaction":
            {
                UInt256     hash    = UInt256.Parse(_params[0].AsString());
                bool        verbose = _params.Count >= 2 && _params[1].AsBooleanOrDefault(false);
                Transaction tx      = Blockchain.Singleton.GetTransaction(hash);
                if (tx == null)
                {
                    throw new RpcException(-100, "Unknown transaction");
                }
                if (verbose)
                {
                    JObject json   = tx.ToJson();
                    uint?   height = Blockchain.Singleton.Store.GetTransactions().TryGet(hash)?.BlockIndex;
                    if (height != null)
                    {
                        Header header = Blockchain.Singleton.Store.GetHeader((uint)height);
                        json["blockhash"]     = header.Hash.ToString();
                        json["confirmations"] = Blockchain.Singleton.Height - header.Index + 1;
                        json["blocktime"]     = header.Timestamp;
                    }
                    return(json);
                }
                return(tx.ToArray().ToHexString());
            }

            case "getstorage":
            {
                UInt160     script_hash = UInt160.Parse(_params[0].AsString());
                byte[]      key         = _params[1].AsString().HexToBytes();
                StorageItem item        = Blockchain.Singleton.Store.GetStorages().TryGet(new StorageKey
                    {
                        ScriptHash = script_hash,
                        Key        = key
                    }) ?? new StorageItem();
                return(item.Value?.ToHexString());
            }

            case "gettxout":
            {
                UInt256 hash  = UInt256.Parse(_params[0].AsString());
                ushort  index = (ushort)_params[1].AsNumber();
                return(Blockchain.Singleton.Store.GetUnspent(hash, index)?.ToJson(index));
            }

            case "getvalidators":
                using (Snapshot snapshot = Blockchain.Singleton.GetSnapshot())
                {
                    var validators = snapshot.GetValidators();
                    return(snapshot.GetEnrollments().Select(p =>
                    {
                        JObject validator = new JObject();
                        validator["publickey"] = p.PublicKey.ToString();
                        validator["votes"] = p.Votes.ToString();
                        validator["active"] = validators.Contains(p.PublicKey);
                        return validator;
                    }).ToArray());
                }

            case "getversion":
            {
                JObject json = new JObject();
                json["port"]      = LocalNode.Singleton.ListenerPort;
                json["nonce"]     = LocalNode.Nonce;
                json["useragent"] = LocalNode.UserAgent;
                return(json);
            }

            case "getwalletheight":
                if (wallet == null)
                {
                    throw new RpcException(-400, "Access denied.");
                }
                else
                {
                    return((wallet.WalletHeight > 0) ? wallet.WalletHeight - 1 : 0);
                }

            case "invoke":
            {
                UInt160             script_hash = UInt160.Parse(_params[0].AsString());
                ContractParameter[] parameters  = ((JArray)_params[1]).Select(p => ContractParameter.FromJson(p)).ToArray();
                byte[] script;
                using (ScriptBuilder sb = new ScriptBuilder())
                {
                    script = sb.EmitAppCall(script_hash, parameters).ToArray();
                }
                return(GetInvokeResult(script));
            }

            case "invokefunction":
            {
                UInt160             script_hash = UInt160.Parse(_params[0].AsString());
                string              operation   = _params[1].AsString();
                ContractParameter[] args        = _params.Count >= 3 ? ((JArray)_params[2]).Select(p => ContractParameter.FromJson(p)).ToArray() : new ContractParameter[0];
                byte[]              script;
                using (ScriptBuilder sb = new ScriptBuilder())
                {
                    script = sb.EmitAppCall(script_hash, operation, args).ToArray();
                }
                return(GetInvokeResult(script));
            }

            case "invokescript":
            {
                byte[] script = _params[0].AsString().HexToBytes();
                return(GetInvokeResult(script));
            }

            case "listaddress":
                if (wallet == null)
                {
                    throw new RpcException(-400, "Access denied.");
                }
                else
                {
                    return(wallet.GetAccounts().Select(p =>
                    {
                        JObject account = new JObject();
                        account["address"] = p.Address;
                        account["haskey"] = p.HasKey;
                        account["label"] = p.Label;
                        account["watchonly"] = p.WatchOnly;
                        return account;
                    }).ToArray());
                }

            case "sendfrom":
                if (wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    UIntBase        assetId    = UIntBase.Parse(_params[0].AsString());
                    AssetDescriptor descriptor = new AssetDescriptor(assetId);
                    UInt160         from       = _params[1].AsString().ToScriptHash();
                    UInt160         to         = _params[2].AsString().ToScriptHash();
                    BigDecimal      value      = BigDecimal.Parse(_params[3].AsString(), descriptor.Decimals);
                    if (value.Sign <= 0)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    Fixed8 fee = _params.Count >= 5 ? Fixed8.Parse(_params[4].AsString()) : Fixed8.Zero;
                    if (fee < Fixed8.Zero)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    UInt160     change_address = _params.Count >= 6 ? _params[5].AsString().ToScriptHash() : null;
                    Transaction tx             = wallet.MakeTransaction(null, new[]
                    {
                        new TransferOutput
                        {
                            AssetId    = assetId,
                            Value      = value,
                            ScriptHash = to
                        }
                    }, from: from, change_address: change_address, fee: fee);
                    if (tx == null)
                    {
                        throw new RpcException(-300, "Insufficient funds");
                    }
                    ContractParametersContext context = new ContractParametersContext(tx);
                    wallet.Sign(context);
                    if (context.Completed)
                    {
                        tx.Witnesses = context.GetWitnesses();
                        wallet.ApplyTransaction(tx);
                        system.LocalNode.Tell(new LocalNode.Relay {
                            Inventory = tx
                        });
                        return(tx.ToJson());
                    }
                    else
                    {
                        return(context.ToJson());
                    }
                }

            case "sendmany":
                if (wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    JArray to = (JArray)_params[0];
                    if (to.Count == 0)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    TransferOutput[] outputs = new TransferOutput[to.Count];
                    for (int i = 0; i < to.Count; i++)
                    {
                        UIntBase        asset_id   = UIntBase.Parse(to[i]["asset"].AsString());
                        AssetDescriptor descriptor = new AssetDescriptor(asset_id);
                        outputs[i] = new TransferOutput
                        {
                            AssetId    = asset_id,
                            Value      = BigDecimal.Parse(to[i]["value"].AsString(), descriptor.Decimals),
                            ScriptHash = to[i]["address"].AsString().ToScriptHash()
                        };
                        if (outputs[i].Value.Sign <= 0)
                        {
                            throw new RpcException(-32602, "Invalid params");
                        }
                    }
                    Fixed8 fee = _params.Count >= 2 ? Fixed8.Parse(_params[1].AsString()) : Fixed8.Zero;
                    if (fee < Fixed8.Zero)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    UInt160     change_address = _params.Count >= 3 ? _params[2].AsString().ToScriptHash() : null;
                    Transaction tx             = wallet.MakeTransaction(null, outputs, change_address: change_address, fee: fee);
                    if (tx == null)
                    {
                        throw new RpcException(-300, "Insufficient funds");
                    }
                    ContractParametersContext context = new ContractParametersContext(tx);
                    wallet.Sign(context);
                    if (context.Completed)
                    {
                        tx.Witnesses = context.GetWitnesses();
                        wallet.ApplyTransaction(tx);
                        system.LocalNode.Tell(new LocalNode.Relay {
                            Inventory = tx
                        });
                        return(tx.ToJson());
                    }
                    else
                    {
                        return(context.ToJson());
                    }
                }

            case "sendrawtransaction":
            {
                Transaction       tx     = Transaction.DeserializeFrom(_params[0].AsString().HexToBytes());
                RelayResultReason reason = system.Blockchain.Ask <RelayResultReason>(tx).Result;
                return(GetRelayResult(reason));
            }

            case "sendtoaddress":
                if (wallet == null)
                {
                    throw new RpcException(-400, "Access denied");
                }
                else
                {
                    UIntBase        assetId    = UIntBase.Parse(_params[0].AsString());
                    AssetDescriptor descriptor = new AssetDescriptor(assetId);
                    UInt160         scriptHash = _params[1].AsString().ToScriptHash();
                    BigDecimal      value      = BigDecimal.Parse(_params[2].AsString(), descriptor.Decimals);
                    if (value.Sign <= 0)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    Fixed8 fee = _params.Count >= 4 ? Fixed8.Parse(_params[3].AsString()) : Fixed8.Zero;
                    if (fee < Fixed8.Zero)
                    {
                        throw new RpcException(-32602, "Invalid params");
                    }
                    UInt160     change_address = _params.Count >= 5 ? _params[4].AsString().ToScriptHash() : null;
                    Transaction tx             = wallet.MakeTransaction(null, new[]
                    {
                        new TransferOutput
                        {
                            AssetId    = assetId,
                            Value      = value,
                            ScriptHash = scriptHash
                        }
                    }, change_address: change_address, fee: fee);
                    if (tx == null)
                    {
                        throw new RpcException(-300, "Insufficient funds");
                    }
                    ContractParametersContext context = new ContractParametersContext(tx);
                    wallet.Sign(context);
                    if (context.Completed)
                    {
                        tx.Witnesses = context.GetWitnesses();
                        wallet.ApplyTransaction(tx);
                        system.LocalNode.Tell(new LocalNode.Relay {
                            Inventory = tx
                        });
                        return(tx.ToJson());
                    }
                    else
                    {
                        return(context.ToJson());
                    }
                }

            case "submitblock":
            {
                Block             block  = _params[0].AsString().HexToBytes().AsSerializable <Block>();
                RelayResultReason reason = system.Blockchain.Ask <RelayResultReason>(block).Result;
                return(GetRelayResult(reason));
            }

            case "validateaddress":
            {
                JObject json = new JObject();
                UInt160 scriptHash;
                try
                {
                    scriptHash = _params[0].AsString().ToScriptHash();
                }
                catch
                {
                    scriptHash = null;
                }
                json["address"] = _params[0];
                json["isvalid"] = scriptHash != null;
                return(json);
            }

            default:
                throw new RpcException(-32601, "Method not found");
            }
        }
Example #20
0
        /// <summary>
        /// Converts the signer from a JSON object.
        /// </summary>
        /// <param name="json">The signer represented by a JSON object.</param>
        /// <returns>The converted signer.</returns>
        public static Signer FromJson(JObject json)
        {
            Signer signer = new();

            signer.Account = UInt160.Parse(json["account"].GetString());
            signer.Scopes  = Enum.Parse <WitnessScope>(json["scopes"].GetString());
            if (signer.Scopes.HasFlag(WitnessScope.CustomContracts))
            {
                signer.AllowedContracts = ((JArray)json["allowedcontracts"]).Select(p => UInt160.Parse(p.GetString())).ToArray();
            }
            if (signer.Scopes.HasFlag(WitnessScope.CustomGroups))
            {
                signer.AllowedGroups = ((JArray)json["allowedgroups"]).Select(p => ECPoint.Parse(p.GetString(), ECCurve.Secp256r1)).ToArray();
            }
            if (signer.Scopes.HasFlag(WitnessScope.WitnessRules))
            {
                signer.Rules = ((JArray)json["rules"]).Select(p => WitnessRule.FromJson((JObject)p)).ToArray();
            }
            return(signer);
        }
 public ContractSettings(IConfigurationSection section)
 {
     this.NEP5 = section.GetSection("NEP5").GetChildren().Select(p => UInt160.Parse(p.Value)).ToArray();
 }
Example #22
0
        public void Test_GetNotifications()
        {
            _engine.ClearNotifications();
            _engine.SendTestNotification(UInt160.Zero, "", new VM.Types.Array(new StackItem[] { new Integer(0x01) }));
            _engine.SendTestNotification(UInt160.Parse("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"), "", new VM.Types.Array(new StackItem[] { new Integer(0x02) }));

            var result = _engine.ExecuteTestCaseStandard("getNotifications", new ByteString(UInt160.Parse("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF").ToArray()));

            Assert.AreEqual(1, result.Count);

            var item = result.Pop();

            Assert.IsInstanceOfType(item, typeof(Integer));
            Assert.AreEqual(0x02, item.GetInteger());

            _engine.Reset();
            result = _engine.ExecuteTestCaseStandard("getAllNotifications");
            Assert.AreEqual(1, result.Count);

            item = result.Pop();
            Assert.IsInstanceOfType(item, typeof(Integer));
            Assert.AreEqual(0x03, item.GetInteger());
        }
Example #23
0
        public void Check_BlockAccount()
        {
            var snapshot = _snapshot.CreateSnapshot();

            // Fake blockchain

            Block block = new Block()
            {
                Header = new Header
                {
                    Index    = 1000,
                    PrevHash = UInt256.Zero
                }
            };

            // Without signature

            Assert.ThrowsException <InvalidOperationException>(() =>
            {
                NativeContract.Policy.Call(snapshot, new Nep17NativeContractExtensions.ManualWitness(UInt160.Zero), block,
                                           "blockAccount",
                                           new ContractParameter(ContractParameterType.ByteArray)
                {
                    Value = UInt160.Parse("0xa400ff00ff00ff00ff00ff00ff00ff00ff00ff01").ToArray()
                });
            });

            // With signature

            UInt160 committeeMultiSigAddr = NativeContract.NEO.GetCommitteeAddress(snapshot);
            var     ret = NativeContract.Policy.Call(snapshot, new Nep17NativeContractExtensions.ManualWitness(committeeMultiSigAddr), block,
                                                     "blockAccount",
                                                     new ContractParameter(ContractParameterType.ByteArray)
            {
                Value = UInt160.Parse("0xa400ff00ff00ff00ff00ff00ff00ff00ff00ff01").ToArray()
            });

            ret.Should().BeOfType <VM.Types.Boolean>();
            ret.GetBoolean().Should().BeTrue();

            // Same account
            ret = NativeContract.Policy.Call(snapshot, new Nep17NativeContractExtensions.ManualWitness(committeeMultiSigAddr), block,
                                             "blockAccount",
                                             new ContractParameter(ContractParameterType.ByteArray)
            {
                Value = UInt160.Parse("0xa400ff00ff00ff00ff00ff00ff00ff00ff00ff01").ToArray()
            });
            ret.Should().BeOfType <VM.Types.Boolean>();
            ret.GetBoolean().Should().BeFalse();

            // Account B

            ret = NativeContract.Policy.Call(snapshot, new Nep17NativeContractExtensions.ManualWitness(committeeMultiSigAddr), block,
                                             "blockAccount",
                                             new ContractParameter(ContractParameterType.ByteArray)
            {
                Value = UInt160.Parse("0xb400ff00ff00ff00ff00ff00ff00ff00ff00ff01").ToArray()
            });
            ret.Should().BeOfType <VM.Types.Boolean>();
            ret.GetBoolean().Should().BeTrue();

            // Check

            NativeContract.Policy.IsBlocked(snapshot, UInt160.Zero).Should().BeFalse();
            NativeContract.Policy.IsBlocked(snapshot, UInt160.Parse("0xa400ff00ff00ff00ff00ff00ff00ff00ff00ff01")).Should().BeTrue();
            NativeContract.Policy.IsBlocked(snapshot, UInt160.Parse("0xb400ff00ff00ff00ff00ff00ff00ff00ff00ff01")).Should().BeTrue();
        }
Example #24
0
        public void TestSetValue()
        {
            ContractParameter contractParameter1 = new(ContractParameterType.Signature);

            byte[] expectedArray1 = new byte[64];
            contractParameter1.SetValue(new byte[64].ToHexString());
            Assert.AreEqual(Encoding.Default.GetString(expectedArray1), Encoding.Default.GetString((byte[])contractParameter1.Value));
            Action action1 = () => contractParameter1.SetValue(new byte[50].ToHexString());

            action1.Should().Throw <FormatException>();

            ContractParameter contractParameter2 = new(ContractParameterType.Boolean);

            contractParameter2.SetValue("true");
            Assert.AreEqual(true, contractParameter2.Value);

            ContractParameter contractParameter3 = new(ContractParameterType.Integer);

            contractParameter3.SetValue("11");
            Assert.AreEqual(new BigInteger(11), contractParameter3.Value);

            ContractParameter contractParameter4 = new(ContractParameterType.Hash160);

            contractParameter4.SetValue("0x0000000000000000000000000000000000000001");
            Assert.AreEqual(UInt160.Parse("0x0000000000000000000000000000000000000001"), contractParameter4.Value);

            ContractParameter contractParameter5 = new(ContractParameterType.Hash256);

            contractParameter5.SetValue("0x0000000000000000000000000000000000000000000000000000000000000000");
            Assert.AreEqual(UInt256.Parse("0x0000000000000000000000000000000000000000000000000000000000000000"), contractParameter5.Value);

            ContractParameter contractParameter6 = new(ContractParameterType.ByteArray);

            contractParameter6.SetValue("2222");
            byte[] expectedArray6 = new byte[2];
            expectedArray6[0] = 0x22;
            expectedArray6[1] = 0x22;
            Assert.AreEqual(Encoding.Default.GetString(expectedArray6), Encoding.Default.GetString((byte[])contractParameter6.Value));

            ContractParameter contractParameter7 = new(ContractParameterType.PublicKey);
            Random            random7            = new();

            byte[] privateKey7 = new byte[32];
            for (int j = 0; j < privateKey7.Length; j++)
            {
                privateKey7[j] = (byte)random7.Next(256);
            }
            ECPoint publicKey7 = ECCurve.Secp256r1.G * privateKey7;

            contractParameter7.SetValue(publicKey7.ToString());
            Assert.AreEqual(true, publicKey7.Equals(contractParameter7.Value));

            ContractParameter contractParameter8 = new(ContractParameterType.String);

            contractParameter8.SetValue("AAA");
            Assert.AreEqual("AAA", contractParameter8.Value);

            ContractParameter contractParameter9 = new(ContractParameterType.Array);
            Action            action9            = () => contractParameter9.SetValue("AAA");

            action9.Should().Throw <ArgumentException>();
        }
Example #25
0
        protected virtual JObject Process(string method, JArray _params)
        {
            switch (method)
            {
            case "getaccountstate":
            {
                UInt160      script_hash = Wallet.ToScriptHash(_params[0].AsString());
                AccountState account     = Blockchain.Default.GetAccountState(script_hash) ?? new AccountState(script_hash);
                return(account.ToJson());
            }

            case "getassetstate":
            {
                UInt256    asset_id = UInt256.Parse(_params[0].AsString());
                AssetState asset    = Blockchain.Default.GetAssetState(asset_id);
                return(asset?.ToJson() ?? throw new RpcException(-100, "Unknown asset"));
            }

            case "getbestblockhash":
                return(Blockchain.Default.CurrentBlockHash.ToString());

            case "getblock":
            {
                Block block;
                if (_params[0] is JNumber)
                {
                    uint index = (uint)_params[0].AsNumber();
                    block = Blockchain.Default.GetBlock(index);
                }
                else
                {
                    UInt256 hash = UInt256.Parse(_params[0].AsString());
                    block = Blockchain.Default.GetBlock(hash);
                }
                if (block == null)
                {
                    throw new RpcException(-100, "Unknown block");
                }
                bool verbose = _params.Count >= 2 && _params[1].AsBooleanOrDefault(false);
                if (verbose)
                {
                    JObject json = block.ToJson();
                    json["confirmations"] = Blockchain.Default.Height - block.Index + 1;
                    UInt256 hash = Blockchain.Default.GetNextBlockHash(block.Hash);
                    if (hash != null)
                    {
                        json["nextblockhash"] = hash.ToString();
                    }
                    return(json);
                }
                else
                {
                    return(block.ToArray().ToHexString());
                }
            }

            case "getblockcount":
                return(Blockchain.Default.Height + 1);

            case "getblockhash":
            {
                uint height = (uint)_params[0].AsNumber();
                if (height >= 0 && height <= Blockchain.Default.Height)
                {
                    return(Blockchain.Default.GetBlockHash(height).ToString());
                }
                else
                {
                    throw new RpcException(-100, "Invalid Height");
                }
            }

            case "getblocksysfee":
            {
                uint height = (uint)_params[0].AsNumber();
                if (height >= 0 && height <= Blockchain.Default.Height)
                {
                    return(Blockchain.Default.GetSysFeeAmount(height).ToString());
                }
                else
                {
                    throw new RpcException(-100, "Invalid Height");
                }
            }

            case "getconnectioncount":
                return(LocalNode.RemoteNodeCount);

            case "getcontractstate":
            {
                UInt160       script_hash = UInt160.Parse(_params[0].AsString());
                ContractState contract    = Blockchain.Default.GetContract(script_hash);
                return(contract?.ToJson() ?? throw new RpcException(-100, "Unknown contract"));
            }

            case "getrawmempool":
                return(new JArray(LocalNode.GetMemoryPool().Select(p => (JObject)p.Hash.ToString())));

            case "getrawtransaction":
            {
                UInt256     hash    = UInt256.Parse(_params[0].AsString());
                bool        verbose = _params.Count >= 2 && _params[1].AsBooleanOrDefault(false);
                int         height  = -1;
                Transaction tx      = LocalNode.GetTransaction(hash);
                if (tx == null)
                {
                    tx = Blockchain.Default.GetTransaction(hash, out height);
                }
                if (tx == null)
                {
                    throw new RpcException(-100, "Unknown transaction");
                }
                if (verbose)
                {
                    JObject json = tx.ToJson();
                    if (height >= 0)
                    {
                        Header header = Blockchain.Default.GetHeader((uint)height);
                        json["blockhash"]     = header.Hash.ToString();
                        json["confirmations"] = Blockchain.Default.Height - header.Index + 1;
                        json["blocktime"]     = header.Timestamp;
                    }
                    return(json);
                }
                else
                {
                    return(tx.ToArray().ToHexString());
                }
            }

            case "getstorage":
            {
                UInt160     script_hash = UInt160.Parse(_params[0].AsString());
                byte[]      key         = _params[1].AsString().HexToBytes();
                StorageItem item        = Blockchain.Default.GetStorageItem(new StorageKey
                    {
                        ScriptHash = script_hash,
                        Key        = key
                    }) ?? new StorageItem();
                return(item.Value?.ToHexString());
            }

            case "gettxout":
            {
                UInt256 hash  = UInt256.Parse(_params[0].AsString());
                ushort  index = (ushort)_params[1].AsNumber();
                return(Blockchain.Default.GetUnspent(hash, index)?.ToJson(index));
            }

            case "invoke":
            {
                UInt160             script_hash = UInt160.Parse(_params[0].AsString());
                ContractParameter[] parameters  = ((JArray)_params[1]).Select(p => ContractParameter.FromJson(p)).ToArray();
                byte[] script;
                using (ScriptBuilder sb = new ScriptBuilder())
                {
                    script = sb.EmitAppCall(script_hash, parameters).ToArray();
                }
                return(GetInvokeResult(script));
            }

            case "invokefunction":
            {
                UInt160             script_hash = UInt160.Parse(_params[0].AsString());
                string              operation   = _params[1].AsString();
                ContractParameter[] args        = _params.Count >= 3 ? ((JArray)_params[2]).Select(p => ContractParameter.FromJson(p)).ToArray() : new ContractParameter[0];
                byte[]              script;
                using (ScriptBuilder sb = new ScriptBuilder())
                {
                    script = sb.EmitAppCall(script_hash, operation, args).ToArray();
                }
                return(GetInvokeResult(script));
            }

            case "invokescript":
            {
                byte[] script = _params[0].AsString().HexToBytes();
                return(GetInvokeResult(script));
            }

            case "sendrawtransaction":
            {
                Transaction tx = Transaction.DeserializeFrom(_params[0].AsString().HexToBytes());
                return(LocalNode.Relay(tx));
            }

            case "submitblock":
            {
                Block block = _params[0].AsString().HexToBytes().AsSerializable <Block>();
                return(LocalNode.Relay(block));
            }

            case "validateaddress":
            {
                JObject json = new JObject();
                UInt160 scriptHash;
                try
                {
                    scriptHash = Wallet.ToScriptHash(_params[0].AsString());
                }
                catch
                {
                    scriptHash = null;
                }
                json["address"] = _params[0];
                json["isvalid"] = scriptHash != null;
                return(json);
            }

            case "getpeers":
            {
                JObject json = new JObject();

                {
                    JArray unconnectedPeers = new JArray();
                    foreach (IPEndPoint peer in LocalNode.GetUnconnectedPeers())
                    {
                        JObject peerJson = new JObject();
                        peerJson["address"] = peer.Address.ToString();
                        peerJson["port"]    = peer.Port;
                        unconnectedPeers.Add(peerJson);
                    }
                    json["unconnected"] = unconnectedPeers;
                }

                {
                    JArray badPeers = new JArray();
                    foreach (IPEndPoint peer in LocalNode.GetBadPeers())
                    {
                        JObject peerJson = new JObject();
                        peerJson["address"] = peer.Address.ToString();
                        peerJson["port"]    = peer.Port;
                        badPeers.Add(peerJson);
                    }
                    json["bad"] = badPeers;
                }

                {
                    JArray connectedPeers = new JArray();
                    foreach (RemoteNode node in LocalNode.GetRemoteNodes())
                    {
                        JObject peerJson = new JObject();
                        peerJson["address"] = node.RemoteEndpoint.Address.ToString();
                        peerJson["port"]    = node.ListenerEndpoint?.Port ?? 0;
                        connectedPeers.Add(peerJson);
                    }
                    json["connected"] = connectedPeers;
                }

                return(json);
            }

            case "getversion":
            {
                JObject json = new JObject();
                json["port"]      = LocalNode.Port;
                json["nonce"]     = LocalNode.Nonce;
                json["useragent"] = LocalNode.UserAgent;
                return(json);
            }

            default:
                throw new RpcException(-32601, "Method not found");
            }
        }
Example #26
0
        public static UInt160 ToScriptHash(this JObject value, ProtocolSettings protocolSettings)
        {
            var addressOrScriptHash = value.AsString();

            return(addressOrScriptHash.Length < 40 ?
                   addressOrScriptHash.ToScriptHash(protocolSettings.AddressVersion) : UInt160.Parse(addressOrScriptHash));
        }
Example #27
0
 static UInt160 GetScriptHashFromParam(string addressOrScriptHash)
 => addressOrScriptHash.Length < 40
         ? addressOrScriptHash.ToScriptHash()
         : UInt160.Parse(addressOrScriptHash);
Example #28
0
 private UInt160 GetScriptHashFromParam(string addressOrScriptHash)
 {
     return(addressOrScriptHash.Length < 40 ?
            addressOrScriptHash.ToScriptHash() : UInt160.Parse(addressOrScriptHash));
 }
Example #29
0
        public void Transaction_Serialize_Deserialize_MaxSizeCosigners()
        {
            // cosigners must respect count

            int maxCosigners = 16;

            // --------------------------------------
            // this should pass (respecting max size)

            var cosigners1 = new Cosigner[maxCosigners];

            for (int i = 0; i < cosigners1.Length; i++)
            {
                string hex = i.ToString("X4");
                while (hex.Length < 40)
                {
                    hex = hex.Insert(0, "0");
                }
                cosigners1[i] = new Cosigner
                {
                    Account = UInt160.Parse(hex)
                };
            }

            Transaction txCosigners1 = new Transaction
            {
                Version         = 0x00,
                Nonce           = 0x01020304,
                Sender          = UInt160.Zero,
                SystemFee       = (long)BigInteger.Pow(10, 8), // 1 GAS
                NetworkFee      = 0x0000000000000001,
                ValidUntilBlock = 0x01020304,
                Attributes      = new TransactionAttribute[0] {
                },
                Cosigners       = cosigners1, // max + 1 (should fail)
                Script          = new byte[] { (byte)OpCode.PUSH1 },
                Witnesses       = new Witness[0] {
                }
            };

            byte[] sTx1 = txCosigners1.ToArray();

            // back to transaction (should fail, due to non-distinct cosigners)
            Transaction tx1 = Neo.IO.Helper.AsSerializable <Transaction>(sTx1);

            Assert.IsNotNull(tx1);

            // ----------------------------
            // this should fail (max + 1)

            var cosigners = new Cosigner[maxCosigners + 1];

            for (var i = 0; i < maxCosigners + 1; i++)
            {
                string hex = i.ToString("X4");
                while (hex.Length < 40)
                {
                    hex = hex.Insert(0, "0");
                }
                cosigners[i] = new Cosigner
                {
                    Account = UInt160.Parse(hex)
                };
            }

            Transaction txCosigners = new Transaction
            {
                Version         = 0x00,
                Nonce           = 0x01020304,
                Sender          = UInt160.Zero,
                SystemFee       = (long)BigInteger.Pow(10, 8), // 1 GAS
                NetworkFee      = 0x0000000000000001,
                ValidUntilBlock = 0x01020304,
                Attributes      = new TransactionAttribute[0] {
                },
                Cosigners       = cosigners, // max + 1 (should fail)
                Script          = new byte[] { (byte)OpCode.PUSH1 },
                Witnesses       = new Witness[0] {
                }
            };

            byte[] sTx2 = txCosigners.ToArray();

            // back to transaction (should fail, due to non-distinct cosigners)
            Transaction tx2 = null;

            Assert.ThrowsException <FormatException>(() =>
                                                     tx2 = Neo.IO.Helper.AsSerializable <Transaction>(sTx2)
                                                     );
            Assert.IsNull(tx2);
        }
Example #30
0
        public static ContractParameter JsonToContractParameter(JObject json)
        {
            ContractParameter parameter = new ContractParameter
            {
                Type = json["type"].TryGetEnum <ContractParameterType>()
            };

            if (json["value"] == null)
            {
                return(parameter);
            }
            if (json["type"].AsString() == "Address")
            {
                parameter.Type  = ContractParameterType.Hash160;
                parameter.Value = json["value"].AsString().ToScriptHash();
                return(parameter);
            }
            switch (parameter.Type)
            {
            case ContractParameterType.Signature:
            case ContractParameterType.ByteArray:
                parameter.Value = Convert.FromBase64String(json["value"].AsString());
                break;

            case ContractParameterType.Boolean:
                parameter.Value = json["value"].AsBoolean();
                break;

            case ContractParameterType.Integer:
                parameter.Value = BigInteger.Parse(json["value"].AsString());
                break;

            case ContractParameterType.Hash160:
                parameter.Value = UInt160.Parse(json["value"].AsString());
                break;

            case ContractParameterType.Hash256:
                parameter.Value = UInt256.Parse(json["value"].AsString());
                break;

            case ContractParameterType.PublicKey:
                parameter.Value = ECPoint.Parse(json["value"].AsString(), ECCurve.Secp256r1);
                break;

            case ContractParameterType.String:
                parameter.Value = json["value"].AsString();
                break;

            case ContractParameterType.Array:
                parameter.Value = ((JArray)json["value"]).Select(p => JsonToContractParameter(p)).ToList();
                break;

            case ContractParameterType.Map:
                parameter.Value = ((JArray)json["value"]).Select(p =>
                                                                 new KeyValuePair <ContractParameter, ContractParameter>(JsonToContractParameter(p["key"]),
                                                                                                                         JsonToContractParameter(p["value"]))).ToList();
                break;

            default:
                throw new ArgumentException();
            }
            return(parameter);
        }