/// <summary> /// Constructor from the API. /// </summary> /// <param name="ccpCharacter">The CCP character.</param> /// <param name="src">The source.</param> /// <exception cref="System.ArgumentNullException">src</exception> internal Contract(CCPCharacter ccpCharacter, SerializableContractListItem src) { src.ThrowIfNull(nameof(src)); Character = ccpCharacter; PopulateContractInfo(src); m_state = GetState(src); }
/// <summary> /// Constructor from an object deserialized from the settings file. /// </summary> /// <param name="ccpCharacter">The CCP character.</param> /// <param name="src">The source.</param> internal Contract(CCPCharacter ccpCharacter, SerializableContract src) { Character = ccpCharacter; ID = src.ContractID; IssuedFor = src.IssuedFor; if (IssuedFor == IssuedFor.Corporation) IssuerID = Character.CharacterID; m_state = src.ContractState; }
/// <summary> /// Process "invoke" command /// </summary> /// <param name="scriptHash">Script hash</param> /// <param name="operation">Operation</param> /// <param name="result">Result</param> /// <param name="verificable">Transaction</param> /// <param name="contractParameters">Contract parameters</param> /// <param name="showStack">Show result stack if it is true</param> /// <param name="gas">Max fee for running the script</param> /// <returns>Return true if it was successful</returns> private bool OnInvokeWithResult(UInt160 scriptHash, string operation, out StackItem result, IVerifiable verificable = null, JArray contractParameters = null, bool showStack = true, long gas = TestModeGas) { List <ContractParameter> parameters = new List <ContractParameter>(); if (contractParameters != null) { foreach (var contractParameter in contractParameters) { parameters.Add(ContractParameter.FromJson(contractParameter)); } } ContractState contract = NativeContract.ContractManagement.GetContract(NeoSystem.StoreView, scriptHash); if (contract == null) { Console.WriteLine("Contract does not exist."); result = StackItem.Null; return(false); } else { if (contract.Manifest.Abi.GetMethod(operation, parameters.Count) == null) { Console.WriteLine("This method does not not exist in this contract."); result = StackItem.Null; return(false); } } byte[] script; using (ScriptBuilder scriptBuilder = new ScriptBuilder()) { scriptBuilder.EmitDynamicCall(scriptHash, operation, parameters.ToArray()); script = scriptBuilder.ToArray(); Console.WriteLine($"Invoking script with: '{script.ToBase64String()}'"); } if (verificable is Transaction tx) { tx.Script = script; } using ApplicationEngine engine = ApplicationEngine.Run(script, NeoSystem.StoreView, container: verificable, settings: NeoSystem.Settings, gas: gas); PrintExecutionOutput(engine, showStack); result = engine.State == VMState.FAULT ? null : engine.ResultStack.Peek(); return(engine.State != VMState.FAULT); }
private bool _loadContract(UInt160 hash, string method, int pcount, CallFlags flags) { this.isEngineInitialized(); ContractState cs = NativeContract.ContractManagement.GetContract(this.snapshot, hash); if (cs is null) { return(false); } ContractMethodDescriptor md = cs.Manifest.Abi.GetMethod(method, pcount); this.engine.LoadContract(cs, md, flags); return(true); }
protected bool Blockchain_GetContract(ExecutionEngine engine) { UInt160 hash = new UInt160(engine.CurrentContext.EvaluationStack.Pop().GetByteArray()); ContractState contract = Snapshot.Contracts.TryGet(hash); if (contract == null) { engine.CurrentContext.EvaluationStack.Push(new byte[0]); } else { engine.CurrentContext.EvaluationStack.Push(StackItem.FromInterface(contract)); } return(true); }
/// <summary> /// Constructor from an object deserialized from the settings file. /// </summary> /// <param name="ccpCharacter">The CCP character.</param> /// <param name="src">The source.</param> internal Contract(CCPCharacter ccpCharacter, SerializableContract src) { src.ThrowIfNull(nameof(src)); m_bidsResponse = m_itemsResponse = null; Character = ccpCharacter; ID = src.ContractID; IssuedFor = src.IssuedFor; if (IssuedFor == IssuedFor.Corporation) { IssuerID = Character.CharacterID; } m_state = src.ContractState; m_bids = new LinkedList <ContractBid>(); }
public void TestDeserialize() { ISerializable newContract = new ContractState(); using (MemoryStream ms = new MemoryStream(1024)) using (BinaryWriter writer = new BinaryWriter(ms)) using (BinaryReader reader = new BinaryReader(ms)) { ((ISerializable)contract).Serialize(writer); ms.Seek(0, SeekOrigin.Begin); newContract.Deserialize(reader); } ((ContractState)newContract).Manifest.ToJson().ToString().Should().Be(contract.Manifest.ToJson().ToString()); ((ContractState)newContract).Script.Should().BeEquivalentTo(contract.Script); }
public override bool Execute(out ResultTuple ret, ResultTuple[] results, Plan.ParameterChooser[] parameterMap, TextWriter executionLog, TextWriter debugLog, out bool preconditionViolated, out Exception exceptionThrown, out bool contractViolated, bool forbidNull, bool useRandoopContracts, out ContractState contractStates) { contractViolated = false; preconditionViolated = false; contractStates = new ContractState(); //if (forbidNull) // Util.Assert(fvalue != null); exceptionThrown = null; ret = new ResultTuple(ftype, new object[] { fvalue }); executionLog.WriteLine("execute primitive value type " + ftype.ToString()); //[email protected] adds return(true); }
private void button1_Click(object sender, EventArgs e) { script_hash = UInt160.Parse(textBox1.Text); ContractState contract = Blockchain.Default.GetContract(script_hash); parameters = contract.Code.ParameterList.Select(p => new ContractParameter { Type = p }).ToArray(); textBox2.Text = contract.Name; textBox3.Text = contract.CodeVersion; textBox4.Text = contract.Author; textBox5.Text = string.Join(", ", contract.Code.ParameterList); button2.Enabled = parameters.Length > 0; UpdateScript(); }
public void Setup(ContractState contract) { _contract = contract; if (ContractName != null) { ContractName.text = contract.Info.Name; } if (Timer != null) { Timer.MaxTime = contract.WorkVotingState.Info.Duration; Timer.RemainingTime = contract.WorkVotingState.TimeRemaining; } Debug.LogWarning("UIDevelopmentStatus component is deprecated, dont use it"); }
public void TestSetup() { manifest = TestUtils.CreateDefaultManifest(); contract = new ContractState { Nef = new NefFile { Compiler = nameof(ScriptBuilder), Tokens = Array.Empty <MethodToken>(), Script = script }, Hash = script.ToScriptHash(), Manifest = manifest }; contract.Nef.CheckSum = NefFile.ComputeChecksum(contract.Nef); }
public MethodCallback(ApplicationEngine engine, UInt160 hash, string method) : base(ApplicationEngine.System_Contract_Call, false) { if (method.StartsWith('_')) { throw new ArgumentException(); } this.contract = engine.Snapshot.Contracts[hash]; ContractManifest currentManifest = engine.Snapshot.Contracts.TryGet(engine.CurrentScriptHash)?.Manifest; if (currentManifest != null && !currentManifest.CanCall(this.contract.Manifest, method)) { throw new InvalidOperationException(); } this.method = this.contract.Manifest.Abi.Methods.First(p => p.Name == method); }
public MethodCallback(ApplicationEngine engine, UInt160 hash, string method) : base(ApplicationEngine.System_Contract_Call, false) { if (method.StartsWith('_')) { throw new ArgumentException(); } this.contract = NativeContract.Management.GetContract(engine.Snapshot, hash); ContractState currentContract = NativeContract.Management.GetContract(engine.Snapshot, engine.CurrentScriptHash); if (currentContract?.CanCall(this.contract, method) == false) { throw new InvalidOperationException(); } this.method = this.contract.Manifest.Abi.Methods.First(p => p.Name == method); }
private void Destroy(ApplicationEngine engine) { UInt160 hash = engine.CallingScriptHash; StorageKey ckey = CreateStorageKey(Prefix_Contract).Add(hash); ContractState contract = engine.Snapshot.Storages.TryGet(ckey)?.GetInteroperable <ContractState>(); if (contract is null) { return; } engine.Snapshot.Storages.Delete(ckey); foreach (var(key, _) in engine.Snapshot.Storages.Find(BitConverter.GetBytes(contract.Id))) { engine.Snapshot.Storages.Delete(key); } }
public void Setup(ContractState state) { _state = state; BasePopup.Setup(state.Info.Name, state.Info.Description); if (Timer != null) { Timer.Timer = state.WorkVotingState.Timer; } ClearItems(); foreach (var kvp in state.WorkVotingState.Progress) { AddItem(kvp.Key, kvp.Value); } }
private Color stateColor(ContractState state) { switch (state) { case ContractState.Active: return(textColor); case ContractState.Complete: return(successColor); case ContractState.Fail: return(failColor); default: return(textColor); } }
private void button1_Click(object sender, EventArgs e) { script_hash = UInt160.Parse(textBox1.Text); ContractState contract = Blockchain.Singleton.Store.GetContracts().TryGet(script_hash); if (contract == null) { return; } parameters = contract.ParameterList.Select(p => new ContractParameter(p)).ToArray(); textBox2.Text = contract.Name; textBox3.Text = contract.CodeVersion; textBox4.Text = contract.Author; textBox5.Text = string.Join(", ", contract.ParameterList); button2.Enabled = parameters.Length > 0; UpdateScript(); }
/// <summary> /// Return true if is allowed /// </summary> /// <param name="targetContract">The contract that we are calling</param> /// <param name="targetMethod">The method that we are calling</param> /// <returns>Return true or false</returns> public bool IsAllowed(ContractState targetContract, string targetMethod) { if (Contract.IsHash) { if (!Contract.Hash.Equals(targetContract.Hash)) { return(false); } } else if (Contract.IsGroup) { if (targetContract.Manifest.Groups.All(p => !p.PubKey.Equals(Contract.Group))) { return(false); } } return(Methods.IsWildcard || Methods.Contains(targetMethod)); }
private bool Contract_GetStorageContext(ExecutionEngine engine) { ContractState contract = engine.EvaluationStack.Pop().GetInterface <ContractState>(); if (!contracts_created.TryGetValue(contract.ScriptHash, out UInt160 created)) { return(false); } if (!created.Equals(new UInt160(engine.CurrentContext.ScriptHash))) { return(false); } engine.EvaluationStack.Push(StackItem.FromInterface(new StorageContext { ScriptHash = contract.ScriptHash })); return(true); }
/// <summary> /// Try to update this contract with a serialization object from the API. /// </summary> /// <param name="src">The serializable source.</param> /// <param name="endedContracts">The ended contracts.</param> /// <returns>True if import successful otherwise, false.</returns> internal bool TryImport(SerializableContractListItem src, List <Contract> endedContracts) { // Note that, before a match is found, all contracts have been marked for deletion : m_markedForDeletion == true // Checks whether ID is the same if (!MatchesWith(src)) { return(false); } // Prevent deletion MarkedForDeletion = false; // Contract is from a serialized object, so populate the missing info if (string.IsNullOrEmpty(Issuer)) { PopulateContractInfo(src); } // Update if modified ContractState state = GetState(src); if (state == m_state && !NeedsAttention) { return(true); } if (state != m_state || Overdue) { // Update state m_state = state; // Update modified info UpdateContractInfo(src); } // Should we notify it to the user ? if (NeedsAttention || state == ContractState.Finished) { endedContracts.Add(this); } return(true); }
/** * add a new list item to the event log tab */ private void AddEventLog_Row(UInt160 scriptHash, string eventType, string eventMessage) { ContractState contract = Blockchain.Default.GetContract(scriptHash); if (contract == null) { return; } DateTime localDateTime = DateTime.Now; listView4.Items.Add(new ListViewItem(new[] { new ListViewItem.ListViewSubItem { Name = "Time", Text = localDateTime.ToString() }, new ListViewItem.ListViewSubItem { Name = "Block", Text = Blockchain.Default.Height.ToString() }, new ListViewItem.ListViewSubItem { Name = "Script Hash", Text = scriptHash.ToString() }, new ListViewItem.ListViewSubItem { Name = "Name", Text = contract.Name.ToString() }, new ListViewItem.ListViewSubItem { Name = "Type", Text = eventType }, new ListViewItem.ListViewSubItem { Name = "Message", Text = eventMessage } }, -1)); }
public void updateStatus() { foreach (ListViewItem Item in listView1.Items) { if (!UInt160.TryParse(Item.Name, out ignore)) { continue; } script_hash = UInt160.Parse(Item.Name); ContractState contract = Blockchain.Default.GetContract(script_hash); if (contract != null) { Item.SubItems[2].Text = contract.Name; Item.SubItems[2].Font = SystemFonts.DefaultFont; Item.SubItems[4].Text = "Found! ツ"; Item.SubItems[4].ForeColor = Color.Green; } } }
private bool CheckDynamicInvoke(OpCode nextInstruction) { if (nextInstruction == OpCode.APPCALL || nextInstruction == OpCode.TAILCALL) { for (int i = CurrentContext.InstructionPointer + 1; i < CurrentContext.InstructionPointer + 21; i++) { if (CurrentContext.Script[i] != 0) { return(true); } } // if we get this far it is a dynamic call // now look at the current executing script // to determine if it can do dynamic calls ContractState contract = script_table.GetContractState(CurrentContext.ScriptHash); return(contract.HasDynamicInvoke); } return(true); }
private bool Contract_Destroy(ExecutionEngine engine) { UInt160 hash = new UInt160(engine.CurrentContext.ScriptHash); ContractState contract = contracts.TryGet(hash); if (contract == null) { return(true); } contracts.Delete(hash); if (contract.HasStorage) { foreach (var pair in storages.Find(hash.ToArray())) { storages.Delete(pair.Key); } } return(true); }
private void Destroy(ApplicationEngine engine) { UInt160 hash = engine.CallingScriptHash; StorageKey ckey = CreateStorageKey(Prefix_Contract).Add(hash); ContractState contract = engine.Snapshot.TryGet(ckey)?.GetInteroperable <ContractState>(); if (contract is null) { return; } engine.Snapshot.Delete(ckey); foreach (var(key, _) in engine.Snapshot.Find(StorageKey.CreateSearchPrefix(contract.Id, ReadOnlySpan <byte> .Empty))) { engine.Snapshot.Delete(key); } engine.SendNotification(Hash, "Destroy", new VM.Types.Array { hash.ToArray() }); }
private void button1_Click(object sender, EventArgs e) { script_hash = UInt160.Parse(textBox1.Text); ContractState contract = Blockchain.Default.GetContract(script_hash); if (contract == null) { return; } var paramsTypes = contract.ParameterList.Select(p => (byte)p == 22 ? ContractParameterType.Array : p).ToArray(); parameters = paramsTypes.Select(p => new ContractParameter(p)).ToArray(); textBox2.Text = contract.Name; textBox3.Text = contract.CodeVersion; textBox4.Text = contract.Author; textBox5.Text = string.Join(", ", paramsTypes); button2.Enabled = parameters.Length > 0; UpdateScript(); }
public void LoadContracts() { ClientExecutor.Instance.Last(); this.contracts.Clear(); System.Numerics.BigInteger index = -1; while (true) { string[] res = ClientExecutor.Instance.Runmethod(this.Address, "getContract", index.ToString(), ParseType.Int, ParseType.Slice, ParseType.Slice); if (res == null) { ClientExecutor.Instance.LastWait(1000); continue; } index = System.Numerics.BigInteger.Parse(res[0]); if (index == -1) { break; } string pubKey = index.ToString(); string address = Utils.ParseAddress(res[1]); string data = res[2].Substring(4); byte[] keyData = new BigInteger(this.PrivKey).ToByteArrayUnsigned(); byte[] valueData = Utils.HexToByteArray(data); byte[] deccrypt = Crypto.Transform(keyData, valueData, false); string privKey = new System.Numerics.BigInteger(deccrypt).ToString(); Owner owner = ClientExecutor.Instance.GetOwner(address); string name = "invalid"; int type = 0; ContractState state = ContractState.Offline; if (owner != null) { name = owner.Name; type = owner.OwnerType; state = owner.State; } MessengerContract messenger = new MessengerContract(name, (MessagerType)type); messenger.Update(pubKey, privKey, address, state); this.contracts.Add(messenger); } this.GetGrams(); }
private void StateReader_Log(object sender, LogEventArgs e) { //MessageBox.Show(e.Message); ContractState contract = Blockchain.Default.GetContract(e.ScriptHash); if (contract == null) { return; } DateTime localDateTime = DateTime.Now; listView4.Items.Add(new ListViewItem(new[] { new ListViewItem.ListViewSubItem { Name = "Time", Text = localDateTime.ToString() }, new ListViewItem.ListViewSubItem { Name = "Block", Text = Blockchain.Default.Height.ToString() }, new ListViewItem.ListViewSubItem { Name = "Script Hash", Text = e.ScriptHash.ToString() }, new ListViewItem.ListViewSubItem { Name = "Name", Text = contract.Name.ToString() }, new ListViewItem.ListViewSubItem { Name = "Message", Text = e.Message } }, -1)); //throw new NotImplementedException(); }
protected virtual JObject GetStorage(JArray _params) { if (!int.TryParse(_params[0].AsString(), out int id)) { UInt160 script_hash = UInt160.Parse(_params[0].AsString()); ContractState contract = Blockchain.Singleton.View.Contracts.TryGet(script_hash); if (contract == null) { return(null); } id = contract.Id; } byte[] key = _params[1].AsString().HexToBytes(); StorageItem item = Blockchain.Singleton.View.Storages.TryGet(new StorageKey { Id = id, Key = key }) ?? new StorageItem(); return(item.Value?.ToHexString()); }
public Owner GetOwner(string address) { try { string[] arr = Runmethod(address, "getOwner", null, ParseType.Int, ParseType.Int, ParseType.Int, ParseType.Int, ParseType.Slice); if (arr != null && arr.Length >= 5) { string pubKey = arr[0]; ContractState state = (ContractState)int.Parse(arr[1]); int ownerType = int.Parse(arr[2]); ContractType type = (ContractType)int.Parse(arr[3]); string name = RunmethodParser.GetSliceText(arr[4]); return(new Owner(name, pubKey, address, state, type, ownerType)); } } catch (Exception e) { } return(null); }
public void FromReplica() { ContractState cs = new ContractState(); FunctionCode code; bool hasStorage; string name; string codeVersion; string author; string email; string description; setupContractStateWithValues(cs, out code, out hasStorage, out name, out codeVersion, out author, out email, out description); ((ICloneable <ContractState>)uut).FromReplica(cs); uut.Code.Should().Be(code); uut.HasStorage.Should().Be(hasStorage); uut.CodeVersion.Should().Be(codeVersion); uut.Author.Should().Be(author); uut.Email.Should().Be(email); uut.Description.Should().Be(description); }
public void Clone() { FunctionCode code; bool hasStorage; string name; string codeVersion; string author; string email; string description; setupContractStateWithValues(uut, out code, out hasStorage, out name, out codeVersion, out author, out email, out description); ContractState newCs = ((ICloneable <ContractState>)uut).Clone(); newCs.Code.Should().Be(code); newCs.HasStorage.Should().Be(hasStorage); newCs.CodeVersion.Should().Be(codeVersion); newCs.Author.Should().Be(author); newCs.Email.Should().Be(email); newCs.Description.Should().Be(description); }
/// <summary> /// Try to update this contract with a serialization object from the API. /// </summary> /// <param name="src">The serializable source.</param> /// <param name="endedContracts">The ended contracts.</param> /// <returns>True if import successful otherwise, false.</returns> internal bool TryImport(SerializableContractListItem src, List<Contract> endedContracts) { // Note that, before a match is found, all contracts have been marked for deletion : m_markedForDeletion == true // Checks whether ID is the same if (!MatchesWith(src)) return false; // Prevent deletion MarkedForDeletion = false; // Contract is from a serialized object, so populate the missing info if (String.IsNullOrEmpty(Issuer)) PopulateContractInfo(src); // Update if modified ContractState state = GetState(src); if (state == m_state && !NeedsAttention) return true; if (state != m_state || Overdue) { // Update state m_state = state; // Update modified info UpdateContractInfo(src); } // Should we notify it to the user ? if (NeedsAttention || state == ContractState.Finished) endedContracts.Add(this); return true; }