public void JTokenToStringTest() { JArray a = new JArray("test"); JNumber n = new JNumber("number", 7.3); JString s = new JString("string", "example"); JBool b = new JBool("bool", true); JNull nu = new JNull("nil"); JArray aa = new JArray("inside"); JToken root = new JToken("root"); JToken t = new JToken("token"); JToken tt = new JToken("token2"); aa.Value.Add(n); aa.Value.Add(b); tt.Value.Add(b); tt.Value.Add(nu); aa.Value.Add(tt); a.Value.Add(s); a.Value.Add(aa); a.Value.Add(n); t.Value.Add(aa); t.Value.Add(s); root.Value.Add(n); root.Value.Add(t); Console.WriteLine(root.ValueToString(0)); Assert.Fail(); }
public void JTokenToStringPressedTest() { JNumber n = new JNumber(7.3); JNumber n2 = new JNumber(42); JNumber n3 = new JNumber(3.14); JString s = new JString("example"); JBool b = new JBool(true); JNull nu = new JNull(); JArray aa = new JArray(); JToken root = new JToken(); JToken t = new JToken(); JToken tt = new JToken(); JRoot r = new JRoot(); r["mnau"] = root; root["dalsi cislo"] = n; root["token"] = t; t["inside"] = aa; t["string"] = s; aa.Add(n2); aa.Add(b); aa.Add(tt); tt["cislo"] = n3; tt["nil"] = (nu); try { aa.Add(nu); } catch (JsonDuplicatedException e) { Console.WriteLine("zkusili jsme pridat podruhe"); } Console.WriteLine(root.ToStringPressed()); Console.WriteLine(root.ToString()); Console.WriteLine(r.ToStringPressed()); Console.WriteLine(r.ToString()); }
public void JTokenToStringPressedTest() { JArray a = new JArray("test"); JNumber n = new JNumber("number", 7.3); JString s = new JString("string", "example"); JBool b = new JBool("bool", true); JNull nu = new JNull("nil"); JArray aa = new JArray("inside"); JToken root = new JToken("root"); JToken t = new JToken("token"); JToken tt = new JToken("token2"); aa.Value.Add(n); aa.Value.Add(b); tt.Value.Add(b); tt.Value.Add(nu); aa.Value.Add(tt); a.Value.Add(s); a.Value.Add(aa); a.Value.Add(n); t.Value.Add(aa); t.Value.Add(s); root.Value.Add(n); root.Value.Add(t); Console.WriteLine(root.ValueToStringPressed()); Assert.AreEqual("{\"number\":7.3,\"token\":{\"inside\":[7.3,true,{\"bool\":true,\"nil\":null}],\"string\":\"example\"}}", root.ValueToStringPressed()); }
public void JArrayToStringTest() { JArray a = new JArray(); JNumber n = new JNumber(42); JNumber n2 = new JNumber(7.3); JString s = new JString("pokus"); JString s2 = new JString("pokus2"); JBool b = new JBool(true); JBool b2 = new JBool(false); JNull nu = new JNull(); JNull nu2 = new JNull(); JNull nu3 = new JNull(); JToken t = new JToken(); JRoot root = new JRoot(); root["pole"] = a; a.Add(n); a.Add(s); a.Add(b); a.Add(nu); a.Add(t); t["string"] = s2; t["nill"] = nu2; t["cislo"] = n2; Console.WriteLine(a.ToString()); JArray aa = new JArray(); a.Add(aa); aa.Add(nu3); aa.Add(b2); Console.WriteLine(a.ToString()); }
public IActionResult GetBlockHeader(string hash, int index, bool verbose = false) { JObject key; Header header; if (hash != null) { key = new JString(hash); UInt256 _hash = UInt256.Parse(key.AsString()); header = Blockchain.Singleton.View.GetHeader(_hash); } else { key = new JNumber(index); uint height = uint.Parse(key.AsString()); header = Blockchain.Singleton.GetHeader(height); } if (header == null) { throw new RestException(-100, "Unknown block"); } if (verbose) { JObject json = header.ToJson(); json["confirmations"] = Blockchain.Singleton.Height - header.Index + 1; UInt256 _hash = Blockchain.Singleton.GetNextBlockHash(header.Hash); if (_hash != null) { json["nextblockhash"] = _hash.ToString(); } return(FormatJson(json)); } return(FormatJson(header.ToArray().ToHexString())); }
private JObject Assets() { var jassets = new JArray(); using (var snapshot = Blockchain.Singleton.GetSnapshot()) { var assets = snapshot.Assets.Find(); var contracts = snapshot.Contracts.Find(); foreach (var asset in assets) { var jasset = new JObject(); jasset["id"] = asset.Key.ToString(); jasset["name"] = asset.Value.GetName(); jasset["type"] = asset.Value.AssetType; jasset["amount"] = new JNumber((double)(decimal)asset.Value.Amount); jasset["available"] = new JNumber((double)(decimal)asset.Value.Available); jasset["issuer"] = asset.Value.Issuer.ToString(); jassets.Add(jasset); } } return(jassets); }
internal JValue parseValue() { char chr = stringPointer.getNextNonWhiteChar(); if (chr == '"') { return(JString.zParse(this, false)); } else if (chr == '-' || (chr >= '0' && chr <= '9')) { return(JNumber.zParse(this, chr)); } else if (chr == '{') { return(JSON.zParse(this, false, false, false)); } else if (chr == '[') { return(JArray.zParse(this, false)); } else if (chr == 't' || chr == 'f') { return(JBoolean.zParse(this, (chr == 't'))); } else if (chr == 'n') { return(JNull.zParse(this)); } else { throw ParseException.forInvalidCharacter("Invalid character '" + chr + "' when expecting start of any value", this); } }
JNumber ParseNumber(ref int pos, int first) { JNumber num = new JNumber(first); int p = pos; for (;;) { if (p >= length - 1) { throw ParseEx; } int b = this[++p]; if (b == '.') { num.Pt = true; } else if (b >= '0' && b <= '9') { num.Add(b); } else { pos = p - 1; return(num); } } }
public override void Excute(ExcutingStack stack) { Operands[0].Excute(stack); var func = stack.Get(Operands[0]); if (func is JFunction jsf) { var ls = new List <Any>(); for (int i = 1; i < Operands.Count; i++) { Operands[i].Excute(stack); ls.Add(stack.Get(Operands[i])); } stack.Push(this, jsf.Excute(stack, ls.ToArray())); } else if (func is JMappingFunction jmaf) { var ls = new List <object>(); for (int i = 1; i < Operands.Count; i++) { Operands[i].Excute(stack); ls.Add(stack.Get(Operands[i]).GetObject()); } var result = jmaf.Invoker(jmaf.Parent.Instance, ls.ToArray()); var type = result.GetType(); if (BaseTypes.Numbers.Contains(type)) { stack.Push(this, JNumber.CreateJNumber(result)); } else if (BaseTypes.TString == type) { stack.Push(this, new JString((string)result)); } else if (BaseTypes.TBoolean == type) { stack.Push(this, new JBool((bool)result)); } else if (type == typeof(void)) { stack.Push(this, new JVoid()); } else { stack.Push(this, new JMappingObject(result)); } } else { throw new MemberNotAFunctionException(); } }
private JObject ProcessGetUnspents(JArray _params) { UInt160 scriptHash = GetScriptHashFromParam(_params[0].AsString()); byte startingToken = 0; // 0 = Utility Token (GAS), 1 = Governing Token (NEO) int maxIterations = 2; if (_params.Count > 1) { maxIterations = 1; bool isGoverningToken = _params[1].AsBoolean(); if (isGoverningToken) { startingToken = 1; } } var unspentsCache = new DbCache <UserSystemAssetCoinOutputsKey, UserSystemAssetCoinOutputs>( _db, null, null, SystemAssetUnspentCoinsPrefix); string[] nativeAssetNames = { "GAS", "NEO" }; UInt256[] nativeAssetIds = { Blockchain.UtilityToken.Hash, Blockchain.GoverningToken.Hash }; JObject json = new JObject(); JArray balances = new JArray(); json["balance"] = balances; json["address"] = scriptHash.ToAddress(); for (byte tokenIndex = startingToken; maxIterations-- > 0; tokenIndex++) { byte[] prefix = new [] { tokenIndex }.Concat(scriptHash.ToArray()).ToArray(); var unspents = new JArray(); Fixed8 total = new Fixed8(0); foreach (var unspentInTx in unspentsCache.Find(prefix)) { if (!AddUnspents(unspents, ref total, unspentInTx)) { break; } } if (unspents.Count <= 0) { continue; } var balance = new JObject(); balance["unspent"] = unspents; balance["asset_hash"] = nativeAssetIds[tokenIndex].ToString().Substring(2); balance["asset_symbol"] = balance["asset"] = nativeAssetNames[tokenIndex]; balance["amount"] = new JNumber((double)(decimal)total);; balances.Add(balance); } return(json); }
public void TestParse() { Action action1 = () => JNumber.Parse(new StringReader("100.a")); action1.ShouldThrow <FormatException>(); Action action2 = () => JNumber.Parse(new StringReader("100.+")); action2.ShouldThrow <FormatException>(); }
// ================================================================================= // Import // --------------------------------------------------------------------------------- public static bool Import(iCS_VisualScriptData storage, string path) { // -- Decode JSON string. -- JObject root = JSONFile.Read(path); if (root == null || root.isNull) { Debug.LogWarning("iCanScript: Import failure: JSON file corrupted."); return(false); } // -- Extract version information. -- var cache = new iCS_VisualScriptData(); JNumber majorVersion = root.GetValueFor("Storage.MajorVersion") as JNumber; JNumber minorVersion = root.GetValueFor("Storage.MinorVersion") as JNumber; JNumber bugFixVersion = root.GetValueFor("Storage.BugFixVersion") as JNumber; cache.MajorVersion = (int)majorVersion.value; cache.MinorVersion = (int)minorVersion.value; cache.BugFixVersion = (int)bugFixVersion.value; // -- Extract visual script attributes. -- JBool isEditorScript = root.GetValueFor("Storage.IsEditorScript") as JBool; JString csharpFileName = root.GetValueFor("Storage.CSharpFileName") as JString; JBool baseTypeOverride = root.GetValueFor("Storage.BaseTypeOverride") as JBool; JString baseType = root.GetValueFor("Storage.BaseType") as JString; JString sourceFileGUID = root.GetValueFor("Storage.SourceFileGUID") as JString; cache.IsEditorScript = isEditorScript.value; cache.CSharpFileName = csharpFileName.value; cache.BaseTypeOverride = baseTypeOverride.value; cache.BaseType = baseType.value; cache.SourceFileGUID = sourceFileGUID.value; // -- Extract engine objects. -- JArray engineObjects = root.GetValueFor("Storage.EngineObjects") as JArray; if (engineObjects == null) { Debug.LogWarning("iCanScript: Import failure: Unable to locate engine array."); return(false); } cache.EngineObjects.Capacity = engineObjects.value.Length; foreach (var eobj in engineObjects.value) { var newObj = ReadEngineObject(eobj as JObject); if (newObj != null) { cache.EngineObjects.Add(newObj); } else { Debug.LogWarning("iCanScript: Unable to create instance of iCS_EngineObject"); } } cache.CopyTo(storage); return(true); }
public void Put(string name, JNumber v) { if (name != null) { Build(name); } else { Add(v); } }
public void JNumberValueToStrinTest() { JNumber n = new JNumber("", 42); Assert.IsNotNull(n); Console.WriteLine(n.ValueToString(0)); Assert.AreEqual("42", n.ValueToString(0)); n.Value = 42.73; Assert.AreEqual(42.73, n.Value); Console.WriteLine(n.ValueToString(0)); Assert.AreEqual("42.73", n.ValueToString(0)); }
// ================================================================================= // Software Update Verification Support Functions. // --------------------------------------------------------------------------------- // Returns the version string of the latest available release. static Version GetLatestReleaseId(out string downloadUrl, float waitTime = 2f) { downloadUrl = null; var url = URL_VersionFile; var download = iCS_WebUtils.WebRequest(url, waitTime); if (!String.IsNullOrEmpty(download.error)) { return(null); } #if DEBUG_INFO Debug.Log(download.text); #endif JNumber jMajor = null; JNumber jMinor = null; JNumber jBugFix = null; try { JObject rootObject = JSON.JSON.GetRootObject(download.text); JObject latestVersion = rootObject.GetValueFor("iCanScript") as JObject; if (!latestVersion.isNull) { jMajor = latestVersion.GetValueFor("major") as JNumber; jMinor = latestVersion.GetValueFor("minor") as JNumber; jBugFix = latestVersion.GetValueFor("bugFix") as JNumber; JString jDownloadUrl = rootObject.GetValueFor("downloadUrl") as JString; if (jDownloadUrl != null) { downloadUrl = jDownloadUrl.value; } #if DEBUG_INFO else { Debug.Log("iCanScript: Unable to determine the download URL"); Debug.Log("iCanScript: JSON root object is: " + rootObject.Encode()); } #endif } } #if DEBUG_INFO catch (System.Exception e) { Debug.LogWarning("iCanScript: JSON exception: " + e.Message); } #else catch (System.Exception) {} #endif if (jMajor == null || jMinor == null || jBugFix == null) { return(null); } return(new Version((int)jMajor.value, (int)jMinor.value, (int)jBugFix.value)); }
private void Test2() { // Create new JSON object from dictionary Dictionary <string, object> dict = new Dictionary <string, object>(); dict.Add("one", 1); dict.Add("two", 2f); JSON jsonFromDict = new JSON(dict); // Create new JSON array from list List <string> list = new List <string>(); list.Add("ABC"); list.Add("XYZ"); list.Add("ijk"); JArray jArrayFromList = new JArray(list); // Create number that would be outside c# supported integers, by creating new JSON number from string JNumber bigInteger = new JNumber("184467440737095516150"); // Add them all to one JSON JSON json = new JSON(); json.Add("fromDict", jsonFromDict); json.Add("fromList", jArrayFromList); json.Add("bigInteger", bigInteger); // Print out in pretty form Debug.Log(json.CreateString(new CreateStringSettings() { HumanReadable = true })); /* * Prints out: * { * "fromDict": { * "one": 1, * "two": 2.0 * }, * "fromList": [ * "ABC", * "XYZ", * "ijk" * ], * "bigInteger": 184467440737095516150 * } */ }
public void JNumberFillTest() { JNumber s = new JNumber(42); Assert.IsNotNull(s); Assert.AreEqual(42, s.Value); JNumber n = new JNumber(7.3); Assert.IsNotNull(n); Assert.AreEqual(7.3, n.Value); JNumber m = new JNumber(3.14e+12); Assert.IsNotNull(m); Assert.AreEqual(3.14e+12, m.Value); }
public void JNumberFillTest() { JNumber s = new JNumber("test") { Value = 42 }; Assert.IsNotNull(s); Assert.AreEqual(42, s.Value); Assert.AreEqual("test", s.Name); JNumber n = new JNumber("test2", 73); Assert.IsNotNull(n); Assert.AreEqual(73, n.Value); Assert.AreEqual("test2", n.Name); }
private JObject StatScenarioZero(JArray parameters) { JObject obj = new JObject(); var txns = Blockchain.Singleton.GetSnapshot() .Transactions.Find() .Where(x => x.Value.Transaction.Type == TransactionType.ClaimTransaction); var issued = txns.Sum(x => x.Value.Transaction.Outputs .Where(z => z.AssetId == Blockchain.UtilityToken.Hash) .Sum(z => { return((decimal)z.Value); })); obj["claimed"] = new JNumber((double)issued); return(obj); }
public void JNumberToStringPressedTest() { JNumber n = new JNumber("test") { Value = 42 }; Assert.IsNotNull(n); Assert.AreEqual("test", n.Name); Assert.AreEqual(42, n.Value); Console.WriteLine(n.ToStringPressed()); Assert.AreEqual("\"test\":42", n.ToStringPressed()); n.Value = 42.73; Assert.AreEqual(42.73, n.Value); Console.WriteLine(n.ToStringPressed()); Assert.AreEqual("\"test\":42.73", n.ToStringPressed()); }
public void JNumberToStringPressedTest() { JNumber n = new JNumber(42); Assert.IsNotNull(n); Assert.AreEqual(42, n.Value); Console.WriteLine(n.ToStringPressed()); Assert.AreEqual("42", n.ToStringPressed()); n.Value = 42.73; Assert.AreEqual(42.73, n.Value); Console.WriteLine(n.ToString()); Assert.AreEqual("42.73", n.ToStringPressed()); n.Value = 3.14e12; Assert.AreEqual(3.14e12, n.Value); Console.WriteLine(n.ToStringPressed()); Assert.AreEqual("3.14e12", n.ToStringPressed()); }
public JObject SearchScenarioZero(JArray parameters) { string address = Try(() => { return(parameters[1].AsString()); }); byte[] contains = Try(() => { return(parameters[2].AsString().HexToBytes()); }); TransactionType type = Try(() => { return((TransactionType)(int)parameters[3].AsNumber()); }); TransactionAttributeUsage?usage = Try(() => { return((TransactionAttributeUsage?)(int)parameters[4].AsNumber()); }); int lengthOutMin = Try(() => { return((int)parameters[5].AsNumber()); }); int lengthOutMax = Try(() => { return((int)parameters[6].AsNumber()); }); int flags = Try(() => { return((int)parameters[7].AsNumber()); }); var txns = Blockchain.Singleton.GetSnapshot() .Transactions.Find() .Where(x => (x.Value.Transaction.Type == type) && ((0 == (flags & 1)) || x.Value.Transaction.Outputs.Length > lengthOutMin) && ((0 == (flags & 2)) || x.Value.Transaction.Outputs.Length < lengthOutMax) && ((0 == (flags & 4)) || ContainsInput(x.Value.Transaction.Inputs, address)) && ((0 == (flags & 8)) || ContainsOutput(x.Value.Transaction.Outputs, address)) && ((0 == (flags & 16)) || usage == null || SearchBytes(GetAttributeByUsage(x.Value, usage.Value), contains) != -1)); if (128 == (flags & 128)) { txns = txns.OrderByDescending(x => x.Value.Transaction.Outputs.Length); } JArray ja = new JArray(); foreach (var tx in txns) { JObject jo = new JObject(); jo["hash"] = tx.Value.Transaction.Hash.ToString(); if ((usage != null) && (16 == (flags & 16))) { jo["attribute"] = GetAttributeByUsage(tx.Value, usage.Value).ToHexString(); } jo["fee"] = new JNumber((double)tx.Value.Transaction.NetworkFee); jo["outputs"] = tx.Value.Transaction.Outputs.Length; jo["inputs"] = tx.Value.Transaction.Inputs.Length; ja.Add(jo); } return(ja); }
private bool AddUnspents(JArray unspents, ref Fixed8 runningTotal, KeyValuePair <UserSystemAssetCoinOutputsKey, UserSystemAssetCoinOutputs> unspentInTx) { var txId = unspentInTx.Key.TxHash.ToString().Substring(2); foreach (var unspent in unspentInTx.Value.AmountByTxIndex) { var utxo = new JObject(); utxo["txid"] = txId; utxo["n"] = unspent.Key; utxo["value"] = new JNumber((double)(decimal)unspent.Value); runningTotal += unspent.Value; unspents.Add(utxo); // if (unspents.Count > _maxResults) // return false; } return(true); }
public void JArrayToStringTest() { JArray a = new JArray("test"); JNumber n = new JNumber("cislo", 42); JString s = new JString("string", "pokus"); JBool b = new JBool("bool", true); JNull nu = new JNull("nil"); JArray aa = new JArray("inside"); a.Value.Add(nu); a.Value.Add(b); a.Value.Add(s); aa.Value.Add(n); aa.Value.Add(s); a.Value.Add(aa); Assert.IsNotNull(a); Console.WriteLine(a.ToString(0)); Assert.AreEqual("\"test\": [\n\tnull,\n\ttrue,\n\t\"pokus\",\n\t[\n\t\t42,\n\t\t\"pokus\"\n\t]\n]", a.ToString(0)); }
public IActionResult GetBlock(string hash, int index, bool verbose = false) { JObject key; if (hash != null) { key = new JString(hash); } else { key = new JNumber(index); } Block block; if (key is JNumber) { uint _index = uint.Parse(key.AsString()); block = Blockchain.Singleton.GetBlock(_index); } else { UInt256 _hash = UInt256.Parse(key.AsString()); block = Blockchain.Singleton.View.GetBlock(_hash); } if (block == null) { throw new RestException(-100, "Unknown block"); } if (verbose) { JObject json = block.ToJson(); json["confirmations"] = Blockchain.Singleton.Height - block.Index + 1; UInt256 _hash = Blockchain.Singleton.GetNextBlockHash(block.Hash); if (hash != null) { json["nextblockhash"] = hash.ToString(); } return(FormatJson(json)); } return(FormatJson(block.ToArray().ToHexString())); }
protected override void excuteSingle(Any obj, ExcutingStack stack) { if (obj is JMappingObject jm) { jm.SetProperty(((JNumber)obj).Value -= 1); } else { var jmnu = new JNumber((((JNumber)obj).Value + 1)); jmnu.Name = obj.Name; if (obj.HasParent) { obj.Parent.SetProperty(obj.Name, jmnu); } else { Block.Reset(obj.Name, jmnu); } } }
public void JArrayValueToStringPressedTest() { JArray a = new JArray("test"); JNumber n = new JNumber("cislo", 42); JString s = new JString("string", "pokus"); JBool b = new JBool("bool", true); JNull nu = new JNull("nil"); //Jobject o = ... a.Value.Add(n); a.Value.Add(s); a.Value.Add(b); a.Value.Add(nu); JArray aa = new JArray("inside"); aa.Value.Add(nu); aa.Value.Add(b); a.Value.Add(aa); Console.WriteLine(a.ValueToStringPressed()); Assert.IsNotNull(a); Assert.AreEqual("[42,\"pokus\",true,null,[null,true]]", a.ValueToStringPressed()); }
JObj ParseObj(ref int pos) { JObj jo = new JObj(); int p = pos; for (;;) { for (;;) { if (p >= length - 1) { throw ParseEx; } int b = this[++p]; if (b == ' ' || b == '\t' || b == '\n' || b == '\r') { continue; } if (b == '"') { break; // meet first quote } if (b == '}') // close early empty { pos = p; return(jo); } throw ParseEx; } str.Clear(); // parse name for (;;) { if (p >= length - 1) { throw ParseEx; } int b = this[++p]; if (b == '"') { break; // meet second quote } str.Add((char)b); } for (;;) // till a colon { if (p >= length - 1) { throw ParseEx; } int b = this[++p]; if (b == ' ' || b == '\t' || b == '\n' || b == '\r') { continue; } if (b == ':') { break; } throw ParseEx; } string name = str.ToString(); // parse the value part for (;;) { if (p >= length - 1) { throw ParseEx; } int b = this[++p]; if (b == ' ' || b == '\t' || b == '\n' || b == '\r') { continue; // skip ws } if (b == '{') { JObj v = ParseObj(ref p); jo.Add(name, v); } else if (b == '[') { JArr v = ParseArr(ref p); jo.Add(name, v); } else if (b == '"') { string v = ParseString(ref p); jo.Add(name, v); } else if (b == 'n') { if (ParseNull(ref p)) { jo.AddNull(name); } } else if (b == 't' || b == 'f') { bool v = ParseBool(ref p, b); jo.Add(name, v); } else if (b == '-' || b >= '0' && b <= '9') { JNumber v = ParseNumber(ref p, b); jo.Add(name, v); } else if (b == '&') // bytes extension { byte[] v = ParseBytes(p); jo.Add(name, v); } else { throw ParseEx; } break; } // comma or end for (;;) { if (p >= length - 1) { throw ParseEx; } int b = this[++p]; if (b == ' ' || b == '\t' || b == '\n' || b == '\r') { continue; } if (b == ',') { break; } if (b == '}') // close normal { pos = p; return(jo); } throw ParseEx; } } }
JArr ParseArr(ref int pos) { JArr ja = new JArr(); int p = pos; for (;;) { if (p >= length - 1) { throw ParseEx; } int b = this[++p]; if (b == ' ' || b == '\t' || b == '\n' || b == '\r') { continue; // skip ws } if (b == ']') // close early empty { pos = p; return(ja); } if (b == '{') { JObj v = ParseObj(ref p); ja.Add(new JMbr(null, v)); } else if (b == '[') { JArr v = ParseArr(ref p); ja.Add(new JMbr(null, v)); } else if (b == '"') { string v = ParseString(ref p); ja.Add(new JMbr(null, v)); } else if (b == 'n') { if (ParseNull(ref p)) { ja.Add(new JMbr()); } } else if (b == 't' || b == 'f') { bool v = ParseBool(ref p, b); ja.Add(new JMbr(null, v)); } else if (b == '-' || b >= '0' && b <= '9') { JNumber v = ParseNumber(ref p, b); ja.Add(new JMbr(null, v)); } else if (b == '&') // bytes extension { byte[] v = ParseBytes(p); ja.Add(new JMbr(null, v)); } else { throw ParseEx; } // comma or return for (;;) { if (p >= length - 1) { throw ParseEx; } b = this[++p]; if (b == ' ' || b == '\t' || b == '\n' || b == '\r') { continue; // skip ws } if (b == ',') { break; } if (b == ']') // close normal { pos = p; return(ja); } throw ParseEx; } } }
private JObject ProcessGetUnspents(JArray _params) { UInt160 scriptHash = GetScriptHashFromParam(_params[0].AsString()); byte startingToken = 0; // 0 = Utility Token (CRON), 1 = Governing Token (CRONIUM) int maxIterations = 2; UInt256 th = UInt256.Zero; if (_params.Count > 1) { string gh = _params[1].AsString(); bool isGoverningToken = (gh == "yes"); bool isUtilityToken = (gh == "util"); if (isGoverningToken) { startingToken = 1; maxIterations = 1; } else if (isUtilityToken) { startingToken = 0; maxIterations = 1; } if (_params.Count > 2) { th = ParseTokenHash(_params[2].AsString()); if (th.Equals(Blockchain.UtilityToken.Hash)) { th = UInt256.Zero; } } } var unspentsCache = new DbCache <UserSystemAssetCoinOutputsKey, UserSystemAssetCoinOutputs>( _db, null, null, SystemAssetUnspentCoinsPrefix); string[] nativeAssetNames = { "CRON", "CRONIUM" }; UInt256[] nativeAssetIds = { Blockchain.UtilityToken.Hash, Blockchain.GoverningToken.Hash }; byte tokenId = 255; var snapshot = Blockchain.Singleton.GetSnapshot(); var r = snapshot.Assets.Find(); var txs = snapshot.Transactions; if (!th.Equals(UInt256.Zero)) { tokenId = GetTokenID(r, th, txs); if (tokenId != 255) { nativeAssetNames[1] = snapshot.Assets.TryGet(th).GetName(); nativeAssetIds[1] = th; } else { throw new Cron.Network.RPC.RpcException(-7166, "Token not found"); } } JObject json = new JObject(); JArray balances = new JArray(); json["balance"] = balances; json["address"] = scriptHash.ToAddress(); for (byte tokenIndex = startingToken; maxIterations-- > 0; tokenIndex++) { byte[] prefix = new[] { (tokenId == 255 || tokenIndex == 0 ? tokenIndex : tokenId) }.Concat(scriptHash.ToArray()).ToArray(); var unspents = new JArray(); Fixed8 total = new Fixed8(0); foreach (var unspentInTx in unspentsCache.Find(prefix)) { if (!AddUnspents(unspents, ref total, unspentInTx)) { break; } } if (unspents.Count <= 0) { continue; } var balance = new JObject(); balance["unspent"] = unspents; balance["asset_hash"] = nativeAssetIds[tokenIndex].ToString().Substring(2); balance["asset_symbol"] = balance["asset"] = nativeAssetNames[tokenIndex]; balance["amount"] = new JNumber((double)(decimal)total);; balances.Add(balance); } return(json); }
static void Main(string[] args) { if (false) { ///////////////////////// // Stringifier Test ///////////////////////// // implicity conversion JArray jArrTest = new JArray(); jArrTest.Value.Add("jArrTest primitive string"); Console.WriteLine(jArrTest.ToJSON()); JString jStrTest = null; jStrTest = "primitive string test"; Console.WriteLine(jStrTest.ToJSON()); // Null tests JString jstr = new JString(null); Console.WriteLine(jstr.ToJSON()); // string with a backward slash JString jstrslash = new JString("\\\\n\n"); JObject jobjslash = new JObject(); jobjslash.Items.Add("\r\n\\\n", jstrslash); Console.WriteLine(jobjslash.ToJSON()); // stringify a jstring that contain break line JString breakstr = new JString("abc \n cba"); Console.WriteLine(breakstr.ToJSON()); JObject jNullObj = new JObject(); jNullObj["test1"] = new JNumber(23); jNullObj["test2"] = null; jNullObj["test3"] = new JString(null); jNullObj["test4"] = new JArray(); ((JArray)jNullObj["test4"]).Value.Add(new JNumber(234)); ((JArray)jNullObj["test4"]).Value.Add(null); ((JArray)jNullObj["test4"]).Value.Add(new JString("sdf")); Console.WriteLine(jNullObj.ToJSON()); // Array tests JObject testObject = new JObject(); testObject.Items.Add("key1", new JBoolean(false)); testObject.Items.Add("key2", new JNumber(333)); JArray testArray = new JArray(new JSONObject[] { new JBoolean(false), new JBoolean(true), new JNumber(20), new JString("test"), testObject, new JNumber(0) }); Console.WriteLine(testArray.ToJSON()); // test JArray.this[int index] Console.WriteLine(((JNumber)testArray[2]).Value.ToString()); Console.WriteLine(((JNumber)testArray[2]).Value = 556); Console.WriteLine(testArray.ToJSON()); // test JArray.this[string key] testArray["alimali"] = new JString("alimali"); Console.WriteLine(testArray["alimali"].ToJSON()); Console.WriteLine(testArray.ToJSON()); // test implicit convert from int to JNumber Console.WriteLine((testArray[2] = (JNumber)234).ToJSON()); Console.WriteLine(testArray.ToJSON()); // test implicit convert from string to JString Console.WriteLine((testArray[2] = (JString)"jstring converted!").ToJSON()); Console.WriteLine(testArray.ToJSON()); } else { ///////////////////////// // Parser Test ///////////////////////// // unicode tests JArray unicode1 = (JArray)Helpers.Parse(@"['HR\u9762\u8bd5',3,3,4]"); // array tests JArray array = (JArray)Helpers.Parse(@"[1,3,3,4]"); JObject array2 = (JObject)Helpers.Parse(@"{'Processes':['20ed6436-5b44-47f8-8642-1184811d4a99']}"); JObject array3 = (JObject)Helpers.Parse(@"{'Processes':['20ed6436-5b44-47f8-8642-1184811d4a99','20ed6436-5b44-47f8-8642-1184811d4a99']}"); JObject array4 = (JObject)Helpers.Parse(@"{'name': 'asfdasf', 'items': [{'name': 'HR\u9762\u8bd5'},{'name': '\u4f53\u68c0'},{'name': '\u5165\u804c'},{'name': '\u5ba2\u6237\u9762\u8bd5'},{'name': '\u7b7e\u7f72OFFER'},{'name': '\u90e8\u95e8\u9762\u8bd5'}]}"); // positive tests JObject p_number1 = (JObject)Helpers.Parse(@"{""test"":23423}"); JObject p_number2_blank = (JObject)Helpers.Parse(@" { ""test"" : 23423 } "); JObject p_number3 = (JObject)Helpers.Parse(@"{""test"":-23}"); // negative number JObject p_string1 = (JObject)Helpers.Parse(@"{""test"":""23423""}"); JObject p_string2 = (JObject)Helpers.Parse(@"{""test"":'23423'}"); JObject p_string3 = (JObject)Helpers.Parse(@"{""test"":'23423\0'}"); JObject p_string4 = (JObject)Helpers.Parse(@"{""test"":'23""423\0'}"); JObject p_string5 = (JObject)Helpers.Parse(@"{""test"":""23'423\0""}"); JObject p_string6 = (JObject)Helpers.Parse(@"{""test"":""23\""423\0""}"); JObject p_string7 = (JObject)Helpers.Parse(@"{""test"":'23\""423\0'}"); JObject p_bool1 = (JObject)Helpers.Parse(@"{""test"":false}"); JObject p_bool2 = (JObject)Helpers.Parse(@"{""test"":true}"); // variable name tests JObject p_variable1 = (JObject)Helpers.Parse(@"{""test"":true}"); JObject p_variable2 = (JObject)Helpers.Parse(@"{'test':false}"); // TODO: multiple object JObject p_multipleObject1 = (JObject)Helpers.Parse(@"{""test"":23423,""test2"":234}"); JObject p_multipleObject2 = (JObject)Helpers.Parse(@"{""X"":350,""Y"":500,""Z"":9}"); // TODO: mixed types JObject p_mixTypes1 = (JObject)Helpers.Parse(@"{""test"":23423,""test2"":""sdf"",""test3"":false,""test4"":234}"); // TODO: dupilcated variable names // TODO: nested JObject p_nested1 = (JObject)Helpers.Parse(@"{""test"":{""test2"":234,""test3"":""sdf""}}"); JObject p_nested2 = (JObject)Helpers.Parse(@" { ""test"" : { ""test2"" : { ""test4"" : false } , ""test3"" : ""sdf"" } } "); // TODO: string escape test // Expected pass JObject p_variableNameEscape_1 = (JObject)Helpers.Parse(@" { ""t\nest"" : 23423 } ", true); JObject p_variableNameEscape_2 = (JObject)Helpers.Parse(@" { ""t\0est"" : 23423 } ", true); JObject p_variableNameEscape_3 = (JObject)Helpers.Parse(@" { ""t\0est"" : ""sdfsdf\0sdfsdf\""df"" } ", true); // Expected error JObject n_variableNameEscape_1 = (JObject)Helpers.Parse(@" { ""t\nest"" : 23423 } "); JObject n_variableNameEscape_2 = (JObject)Helpers.Parse(@" { ""t\0est"" : 23423 } ", false); // negative tests JObject n = (JObject)Helpers.Parse(@"{""test"":23423a}"); JObject n2 = (JObject)Helpers.Parse(@"{""test"":false1}"); JObject n3 = (JObject)Helpers.Parse(@"{""test':false1}"); } }
/// <summary> /// Parse a JSON string to a doufu json object /// </summary> /// <param name="sJSON">JSON string</param> /// <param name="bAllowNonStandardVariableName">True to allow non-standard variable name, for example {"foo\0\nfoo":"str"} is allowed. /// Otherwise incorrect format exception will be thrown.</param> /// <returns>Return a doufu json object</returns> public static JSONObject Parse(string sJSON, bool bAllowNonStandardVariableName) { sJSON = sJSON.Trim(); // indicate current json is array format bool isArray = false; if (sJSON[0] == BRACKET_START) { if (sJSON[sJSON.Length - 1] != BRACKET_END) { throw new Exception("Incorrect format, json starts with { but not ends with }"); } } else if (sJSON[0] == BRACE_START) { if (sJSON[sJSON.Length - 1] != BRACE_END) { throw new Exception("Incorrect format, json starts with [ but not ends with ]"); } isArray = true; } else { throw new Exception("Incorrect format, json should starts with { or ["); } // remove brackets sJSON = sJSON.Substring(1, sJSON.Length - 2); sJSON = sJSON.Trim(); JObject jsonRet = new JObject(); JArray jsonArrRet = new JArray(); Regex reVariableName = new Regex(@"^[""|'][a-zA-Z$]+[a-zA-Z0-9_\$]*[""|']$", RegexOptions.None); if (bAllowNonStandardVariableName) { reVariableName = new Regex(@"^[""|'].*[""|']$", RegexOptions.None); } Regex reIsLetter = new Regex(@"^[a-zA-Z]*$", RegexOptions.None); Regex reIsNumberChar = new Regex(@"^-?[0-9]*$", RegexOptions.None); Regex reIsNumber = new Regex(@"^-?[0-9]+$", RegexOptions.None); string sVariableName = string.Empty; JSONObject oVariableValue; ParsingStatus iStatus = ParsingStatus.Unstarted; Collection<char> cStartSymbs = new Collection<char>(); Collection<char> cEndSymbs = new Collection<char>(); if (isArray) { iStatus = ParsingStatus.ExpectVariableValue | ParsingStatus.ExpectStartBracket | ParsingStatus.ExpectStartBrace; } else { iStatus = ParsingStatus.ExpectVariableName; } // indicate whether the last loop exited with error. // if there were error, the iConditionMet would be 0 int iConditionMet = 1; for (int i = 0; i < sJSON.Length; ) { if (iConditionMet <= 0) { throw new Exception("Incorrect format: Expected " + iStatus.ToString() + " position: " + i.ToString()); } else { iConditionMet = 0; } if (iStatus == (iStatus | ParsingStatus.ExpectStartBracket)) { // is start symbol? if (BRACKET_START == sJSON[i]) { StringBuilder sInnerJSON = new StringBuilder(); int iBracketCounter = 0; int j; for (j = i; j < sJSON.Length; j++) { sInnerJSON.Append(sJSON[j]); if (sJSON[j] == BRACKET_START) { iBracketCounter++; } else if (sJSON[j] == BRACKET_END) { iBracketCounter--; } if (iBracketCounter == 0) { break; } } oVariableValue = Parse(sInnerJSON.ToString()); // add value if (isArray) { jsonArrRet.Value.Add(oVariableValue); } else { jsonRet.Items.Add(sVariableName, oVariableValue); } i = ++j; iStatus = ParsingStatus.ExpectCommas | ParsingStatus.ExpectEOS | ParsingStatus.ExpectBlank; iConditionMet++; continue; } } if (iStatus == (iStatus | ParsingStatus.ExpectEndBracket)) { } if (iStatus == (iStatus | ParsingStatus.ExpectStartBrace)) { // check if it is "[" if (BRACE_START == sJSON[i]) { StringBuilder sInnerJSON = new StringBuilder(); int iBracketCounter = 0; int j; for (j = i; j < sJSON.Length; j++) { sInnerJSON.Append(sJSON[j]); if (sJSON[j] == BRACE_START) { iBracketCounter++; } else if (sJSON[j] == BRACE_END) { iBracketCounter--; } if (iBracketCounter == 0) { break; } } oVariableValue = Parse(sInnerJSON.ToString()); // add value if (isArray) { jsonArrRet.Value.Add(oVariableValue); } else { jsonRet.Items.Add(sVariableName, oVariableValue); } i = ++j; iStatus = ParsingStatus.ExpectCommas | ParsingStatus.ExpectEOS | ParsingStatus.ExpectBlank; iConditionMet++; continue; } } if (iStatus == (iStatus | ParsingStatus.ExpectEndBrace)) { } if (iStatus == (iStatus | ParsingStatus.ExpectVariableName)) { StringBuilder sName = new StringBuilder(); string sActualName; bool bBroke = false; int j; for (j = i; j < sJSON.Length; j++) { if (sJSON[j] == NAME_VALUE_SEPARATOR) { bBroke = true; break; } sName.Append(sJSON[j]); } sActualName = sName.ToString(); sActualName = sActualName.Trim(); if (reVariableName.IsMatch(sActualName.ToString()) && bBroke == true) { // TODO: string escape sActualName = sActualName.Substring(1, sActualName.Length - 2); sVariableName = sActualName; i = ++j; iStatus = ParsingStatus.ExpectVariableValue | ParsingStatus.ExpectStartBrace | ParsingStatus.ExpectStartBracket | ParsingStatus.ExpectBlank; iConditionMet++; continue; } } if (iStatus == (iStatus | ParsingStatus.ExpectVariableValue)) { if (sJSON[i] == '"' || sJSON[i] == '\'') { StringBuilder sValue = new StringBuilder(); bool bBroke = false; int j; for (j = i + 1; j < sJSON.Length; j++) { if (sJSON[j] == sJSON[i] && sJSON[j - 1] != '\\') { bBroke = true; break; } // process escaped unicode if (sJSON[j] == '\\') { if (j + 5 < sJSON.Length && sJSON[j+1] == 'u') { string hex = sJSON.Substring(j + 2, 4); sValue.Append((char)Int16.Parse(hex, System.Globalization.NumberStyles.HexNumber)); j += 5; continue; } } sValue.Append(sJSON[j]); } if (bBroke == true) { string sFinalValue = sValue.ToString(); sFinalValue = sFinalValue.Replace("\\\"", "\""); sFinalValue = sFinalValue.Replace("\\\'", "\'"); oVariableValue = new JString(sFinalValue); // add value if (isArray) { jsonArrRet.Value.Add(oVariableValue); } else { jsonRet.Items.Add(sVariableName, oVariableValue); } i = j + 1; iStatus = ParsingStatus.ExpectEOS | ParsingStatus.ExpectCommas | ParsingStatus.ExpectBlank; iConditionMet++; continue; } } else if (reIsLetter.IsMatch(sJSON[i].ToString())) { StringBuilder sBool = new StringBuilder(); bool bFound = false; int j; for (j = 0; j < 5; j++) { sBool.Append(sJSON[i + j]); if (j == 3 && sBool.ToString() == "true") { bFound = true; break; } else if (j == 4 && sBool.ToString() == "false") { bFound = true; break; } } if (bFound == true) { oVariableValue = new JBoolean(bool.Parse(sBool.ToString())); // add value if (isArray) { jsonArrRet.Value.Add(oVariableValue); } else { jsonRet.Items.Add(sVariableName, oVariableValue); } i += j + 1; iStatus = ParsingStatus.ExpectEOS | ParsingStatus.ExpectCommas | ParsingStatus.ExpectBlank; iConditionMet++; continue; } } else if (reIsNumberChar.IsMatch(sJSON[i].ToString())) { // check if negative number if (sJSON[i].ToString() == "-" && !reIsNumber.IsMatch(sJSON[i].ToString() + sJSON[i + 1].ToString())) { break; } StringBuilder sNumber = new StringBuilder(); int j; for (j = i; j < sJSON.Length; j++) { if (reIsNumberChar.IsMatch(sJSON[j].ToString())) { sNumber.Append(sJSON[j]); } else { if (sJSON[j] != '.') { break; } sNumber.Append(sJSON[j]); } } if (j == sJSON.Length || sJSON[j] == ',' || sJSON[j] == ' ') { oVariableValue = new JNumber(Int32.Parse(sNumber.ToString())); // add value if (isArray) { jsonArrRet.Value.Add(oVariableValue); } else { jsonRet.Items.Add(sVariableName, oVariableValue); } i = j; iStatus = ParsingStatus.ExpectEOS | ParsingStatus.ExpectCommas | ParsingStatus.ExpectBlank; iConditionMet++; continue; } } } if (iStatus == (iStatus | ParsingStatus.ExpectBlank)) { if (i < sJSON.Length && sJSON[i] == ' ') { i++; iConditionMet++; continue; } } if (iStatus == (iStatus | ParsingStatus.ExpectCommas)) { if (i < sJSON.Length && sJSON[i] == ',') { i++; if (isArray) { iStatus = ParsingStatus.ExpectVariableValue | ParsingStatus.ExpectStartBracket | ParsingStatus.ExpectStartBrace | ParsingStatus.ExpectBlank; } else { iStatus = ParsingStatus.ExpectVariableName | ParsingStatus.ExpectBlank; } iConditionMet++; continue; } } if (iStatus == (iStatus | ParsingStatus.ExpectEOS)) { if (i == sJSON.Length) { iConditionMet++; continue; } } } if (isArray) { return jsonArrRet; } else { return jsonRet; } }