protected internal void CallContract(UInt160 contractHash, string method, CallFlags callFlags, Array args) { if (method.StartsWith('_')) { throw new ArgumentException($"Invalid Method Name: {method}"); } if ((callFlags & ~CallFlags.All) != 0) { throw new ArgumentOutOfRangeException(nameof(callFlags)); } ContractState contract = NativeContract.ContractManagement.GetContract(Snapshot, contractHash); if (contract is null) { throw new InvalidOperationException($"Called Contract Does Not Exist: {contractHash}"); } ContractMethodDescriptor md = contract.Manifest.Abi.GetMethod(method, args.Count); if (md is null) { throw new InvalidOperationException($"Method \"{method}\" with {args.Count} parameter(s) doesn't exist in the contract {contractHash}."); } bool hasReturnValue = md.ReturnType != ContractParameterType.Void; if (!hasReturnValue) { CurrentContext.EvaluationStack.Push(StackItem.Null); } CallContractInternal(contract, md, callFlags, hasReturnValue, args); }
private static bool IsSuperCall(MethodContext context, IMethod method, CallFlags flags) { bool thiscall = (flags & CallFlags.Thiscall) != 0; bool virtcall = (flags & CallFlags.Virtcall) != 0; return(thiscall && !virtcall && IsSuperCall(context, method)); }
public ExecutionContext LoadContract(ContractState contract, string method, CallFlags callFlags, bool packParameters = false) { ContractMethodDescriptor md = contract.Manifest.Abi.GetMethod(method); if (md is null) { return(null); } ExecutionContext context = LoadScript(contract.Script, callFlags, contract.Hash, md.Offset); if (NativeContract.IsNative(contract.Hash)) { if (packParameters) { using ScriptBuilder sb = new ScriptBuilder(); sb.Emit(OpCode.DEPTH, OpCode.PACK); sb.EmitPush(md.Name); LoadScript(sb.ToArray(), CallFlags.None); } } else { // Call initialization var init = contract.Manifest.Abi.GetMethod("_initialize"); if (init != null) { LoadContext(context.Clone(init.Offset), false); } } return(context); }
private void CallContractInternal(UInt160 contractHash, string method, CallFlags flags, bool hasReturnValue, StackItem[] args) { ContractState contract = NativeContract.ContractManagement.GetContract(Snapshot, contractHash); if (contract is null) { throw new InvalidOperationException($"Called Contract Does Not Exist: {contractHash}"); } ContractMethodDescriptor md = contract.Manifest.Abi.GetMethod(method); if (md is null) { throw new InvalidOperationException($"Method {method} Does Not Exist In Contract {contractHash}"); } if (md.Safe) { flags &= ~CallFlags.WriteStates; } else { ContractState currentContract = NativeContract.ContractManagement.GetContract(Snapshot, CurrentScriptHash); if (currentContract?.CanCall(contract, method) == false) { throw new InvalidOperationException($"Cannot Call Method {method} Of Contract {contractHash} From Contract {CurrentScriptHash}"); } } CallContractInternal(contract, md, flags, hasReturnValue, args); }
private void CallContractInternal(ContractState contract, ContractMethodDescriptor method, CallFlags flags, bool hasReturnValue, StackItem[] args) { if (invocationCounter.TryGetValue(contract.Hash, out var counter)) { invocationCounter[contract.Hash] = counter + 1; } else { invocationCounter[contract.Hash] = 1; } ExecutionContextState state = CurrentContext.GetState <ExecutionContextState>(); UInt160 callingScriptHash = state.ScriptHash; CallFlags callingFlags = state.CallFlags; if (args.Length != method.Parameters.Length) { throw new InvalidOperationException($"Method {method.Name} Expects {method.Parameters.Length} Arguments But Receives {args.Length} Arguments"); } ExecutionContext context_new = LoadContract(contract, method.Name, flags & callingFlags, hasReturnValue, (ushort)args.Length); state = context_new.GetState <ExecutionContextState>(); state.CallingScriptHash = callingScriptHash; for (int i = args.Length - 1; i >= 0; i--) { context_new.EvaluationStack.Push(args[i]); } if (NativeContract.IsNative(contract.Hash)) { context_new.EvaluationStack.Push(method.Name); } }
public ExecutionContext LoadScript(Script script, CallFlags callFlags, int initialPosition = 0) { ExecutionContext context = LoadScript(script, initialPosition); context.GetState <ExecutionContextState>().CallFlags = callFlags; return(context); }
/// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>Flags</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="flags">The call flags.</param> internal CallOptions WithFlags(CallFlags flags) { var newOptions = this; newOptions.flags = flags; return(newOptions); }
private bool IsSuperCall(IMethod method, CallFlags flags) { bool thiscall = (flags & CallFlags.Thiscall) != 0; bool virtcall = (flags & CallFlags.Virtcall) != 0; return(thiscall && !virtcall && IsSuperCall(method)); }
public ExecutionContext LoadContract(ContractState contract, string method, CallFlags callFlags, bool hasReturnValue, ushort pcount) { ContractMethodDescriptor md = contract.Manifest.Abi.GetMethod(method); if (md is null) { return(null); } ExecutionContext context = LoadScript(contract.Script, pcount: pcount, rvcount: hasReturnValue ? 1 : 0, initialPosition: md.Offset, configureState: p => { p.CallFlags = callFlags; p.ScriptHash = contract.Hash; }); // Call initialization var init = contract.Manifest.Abi.GetMethod("_initialize"); if (init != null) { LoadContext(context.Clone(init.Offset)); } return(context); }
public ExecutionContext LoadScript(Script script, CallFlags callFlags, int rvcount = -1) { ExecutionContext context = LoadScript(script, rvcount); context.GetState <ExecutionContextState>().CallFlags = callFlags; return(context); }
private InteropDescriptor(string method, Func <ApplicationEngine, bool> handler, TriggerType allowedTriggers, CallFlags requiredCallFlags) { this.Method = method; this.Hash = method.ToInteropMethodHash(); this.Handler = handler; this.AllowedTriggers = allowedTriggers; this.RequiredCallFlags = requiredCallFlags; }
private void CallCore(AbcCode code, IMethod method, AbcMultiname prop, CallFlags flags) { prop = _abc.ImportConst(prop); //determines whether method belongs to base type bool super = IsSuperCall(method, flags); CallCore(code, method, prop, super); }
internal InteropDescriptor(string name, MethodInfo handler, long fixedPrice, CallFlags requiredCallFlags) { this.Name = name; this.Hash = BinaryPrimitives.ReadUInt32LittleEndian(Encoding.ASCII.GetBytes(name).Sha256()); this.Handler = handler; this.Parameters = handler.GetParameters().Select(p => new InteropParameterDescriptor(p)).ToList().AsReadOnly(); this.FixedPrice = fixedPrice; this.RequiredCallFlags = requiredCallFlags; }
public void StartClientStreaming(UnaryResponseClientHandler callback, MetadataArraySafeHandle metadataArray, CallFlags callFlags) { using (completionQueue.NewScope()) { var ctx = BatchContextSafeHandle.Create(); completionQueue.CompletionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedStatusOnClient(), context.GetReceivedMessage(), context.GetReceivedInitialMetadata())); Native.grpcsharp_call_start_client_streaming(this, ctx, metadataArray, callFlags).CheckOk(); } }
public void StartUnary(UnaryResponseClientHandler callback, byte[] payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags) { using (completionQueue.NewScope()) { var ctx = BatchContextSafeHandle.Create(); completionQueue.CompletionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedStatusOnClient(), context.GetReceivedMessage(), context.GetReceivedInitialMetadata())); Native.grpcsharp_call_start_unary(this, ctx, payload, new UIntPtr((ulong)payload.Length), writeFlags, metadataArray, callFlags) .CheckOk(); } }
internal InteropDescriptor(string name, MethodInfo handler, long fixedPrice, CallFlags requiredCallFlags, bool allowCallback) { this.Name = name; this.Hash = BitConverter.ToUInt32(Encoding.ASCII.GetBytes(name).Sha256(), 0); this.Handler = handler; this.Parameters = handler.GetParameters().Select(p => new InteropParameterDescriptor(p)).ToArray(); this.FixedPrice = fixedPrice; this.RequiredCallFlags = requiredCallFlags; this.AllowCallback = allowCallback; }
/// <summary> /// Creates a new instance of <c>CallOptions</c> struct. /// </summary> /// <param name="headers">Headers to be sent with the call.</param> /// <param name="deadline">Deadline for the call to finish. null means no deadline.</param> /// <param name="cancellationToken">Can be used to request cancellation of the call.</param> /// <param name="writeOptions">Write options that will be used for this call.</param> /// <param name="propagationToken">Context propagation token obtained from <see cref="ServerCallContext"/>.</param> /// <param name="credentials">Credentials to use for this call.</param> public CallOptions(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken), WriteOptions writeOptions = null, ContextPropagationToken propagationToken = null, CallCredentials credentials = null) { this.headers = headers; this.deadline = deadline; this.cancellationToken = cancellationToken; this.writeOptions = writeOptions; this.propagationToken = propagationToken; this.credentials = credentials; this.flags = default(CallFlags); }
/// <summary> /// Creates a new instance of <c>CallOptions</c> struct. /// </summary> /// <param name="headers">Headers to be sent with the call.</param> /// <param name="deadline">Deadline for the call to finish. null means no deadline.</param> /// <param name="cancellationToken">Can be used to request cancellation of the call.</param> /// <param name="writeOptions">Write options that will be used for this call.</param> /// <param name="propagationToken">Context propagation token obtained from <see cref="ServerCallContext"/>.</param> /// <param name="credentials">Credentials to use for this call.</param> public CallOptions(Metadata headers = null, DateTime?deadline = null, CancellationToken cancellationToken = default(CancellationToken), WriteOptions writeOptions = null, ContextPropagationToken propagationToken = null, CallCredentials credentials = null) { this.headers = headers; this.deadline = deadline; this.cancellationToken = cancellationToken; this.writeOptions = writeOptions; this.propagationToken = propagationToken; this.credentials = credentials; this.flags = default(CallFlags); }
public ExecutionContext LoadScript(Script script, CallFlags callFlags, UInt160 scriptHash = null, int initialPosition = 0) { // Create and configure context ExecutionContext context = CreateContext(script, initialPosition); var state = context.GetState <ExecutionContextState>(); state.CallFlags = callFlags; state.ScriptHash = scriptHash ?? ((byte[])script).ToScriptHash(); // Load context LoadContext(context); return(context); }
private ExecutionContext CallContractInternal(ContractState contract, ContractMethodDescriptor method, CallFlags flags, bool hasReturnValue, IReadOnlyList <StackItem> args) { if (method.Safe) { flags &= ~CallFlags.WriteStates; } else { ContractState currentContract = NativeContract.ContractManagement.GetContract(Snapshot, CurrentScriptHash); if (currentContract?.CanCall(contract, method.Name) == false) { throw new InvalidOperationException($"Cannot Call Method {method} Of Contract {contract.Hash} From Contract {CurrentScriptHash}"); } } if (invocationCounter.TryGetValue(contract.Hash, out var counter)) { invocationCounter[contract.Hash] = counter + 1; } else { invocationCounter[contract.Hash] = 1; } ExecutionContextState state = CurrentContext.GetState <ExecutionContextState>(); UInt160 callingScriptHash = state.ScriptHash; CallFlags callingFlags = state.CallFlags; if (args.Count != method.Parameters.Length) { throw new InvalidOperationException($"Method {method} Expects {method.Parameters.Length} Arguments But Receives {args.Count} Arguments"); } if (hasReturnValue ^ (method.ReturnType != ContractParameterType.Void)) { throw new InvalidOperationException("The return value type does not match."); } ExecutionContext context_new = LoadContract(contract, method, flags & callingFlags); state = context_new.GetState <ExecutionContextState>(); state.CallingScriptHash = callingScriptHash; for (int i = args.Count - 1; i >= 0; i--) { context_new.EvaluationStack.Push(args[i]); } if (NativeContract.IsNative(contract.Hash)) { context_new.EvaluationStack.Push(method.Name); } return(context_new); }
/// <summary> /// Initializes a new instance of the <see cref="Call"/> class. /// </summary> /// <param name="returnId">Identifier for the output returned by the method call.</param> /// <param name="returnType">The type of the output returned by the method call.</param> /// <param name="functionExpression">Expression representing the method call.</param> /// <param name="args">Arguments of the method being called.</param> /// <param name="flags">Flags which describe properties about the method.</param> /// <param name="location">The program location in which the method is being /// called.</param> public Call(Identifier returnId, Typ returnType, Expression functionExpression, IEnumerable <CallArg> args, CallFlags flags, Location location) : base(location) { ReturnVar = returnId; ReturnType = returnType; FunctionExpression = functionExpression; Args = args; Flags = flags; }
private dynamic dispatchEngineMethod(EngineMethod method, dynamic args) { switch (method) { case EngineMethod.create: TriggerType trigger = (TriggerType)args.trigger; long gas = long.Parse((string)args.gas); bool testMode = (bool)args.testMode; IVerifiable container = null; if (args.container != null) { container = deserializeContainer(args.container); } return(this._create(trigger, container, this.selectSnapshot(args.snapshot, false), gas, testMode)); case EngineMethod.execute: return(this._execute()); case EngineMethod.loadscript: Script script = new Script((byte[])args.script); CallFlags flag = (CallFlags)((byte)args.flag); return(this._loadScript(script, flag)); case EngineMethod.setinstructionpointer: int position = (int)args.position; return(this._setInstructionPointer(position)); 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.dispose_engine: this.disposeEngine(); return(true); default: throw new InvalidOperationException(); } }
private bool _loadContract(UInt160 hash, string method, CallFlags flags, bool packParameters) { this.isEngineInitialized(); ContractState cs = NativeContract.Management.GetContract(this.snapshot, hash); if (cs is null) { return(false); } this.engine.LoadContract(cs, method, flags, packParameters); return(true); }
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); }
sizeof(CallFlags); // CallFlags void ISerializable.Deserialize(ref MemoryReader reader) { Hash = reader.ReadSerializable <UInt160>(); Method = reader.ReadVarString(32); if (Method.StartsWith('_')) { throw new FormatException(); } ParametersCount = reader.ReadUInt16(); HasReturnValue = reader.ReadBoolean(); CallFlags = (CallFlags)reader.ReadByte(); if ((CallFlags & ~CallFlags.All) != 0) { throw new FormatException(); } }
private void Call(AbcCode code, IMethod method, AbcMultiname prop, CallFlags flags) { if (prop == null) { throw new ArgumentNullException("prop"); } CallCore(code, method, prop, flags); if (MustCoerceReturnType(method)) { var type = method.Type; EnsureType(type); code.Coerce(type, true); } }
internal static bool VerifyWitness(this IVerifiable verifiable, StoreView snapshot, UInt160 hash, Witness witness, long gas, out long fee) { fee = 0; using (ApplicationEngine engine = ApplicationEngine.Create(TriggerType.Verification, verifiable, snapshot?.Clone(), gas)) { CallFlags callFlags = !witness.VerificationScript.IsStandardContract() ? CallFlags.ReadStates : CallFlags.None; byte[] verification = witness.VerificationScript; if (verification.Length == 0) { ContractState cs = NativeContract.Management.GetContract(snapshot, hash); if (cs is null) { return(false); } if (engine.LoadContract(cs, "verify", callFlags, true) is null) { return(false); } } else { if (NativeContract.IsNative(hash)) { return(false); } if (hash != witness.ScriptHash) { return(false); } engine.LoadScript(verification, callFlags, hash, 0); } engine.LoadScript(witness.InvocationScript, CallFlags.None); if (engine.Execute() == VMState.FAULT) { return(false); } if (engine.ResultStack.Count != 1 || !engine.ResultStack.Peek().GetBoolean()) { return(false); } fee = engine.GasConsumed; } return(true); }
public override void Execute(Context context) { ProxyCallsUtils proxyCallsUtils = new ProxyCallsUtils(context); CallFlags flags = CallFlags.InvokeStatic | CallFlags.InvokeVirtual; foreach (MethodDefinition method in context.Class.Methods.ToArray()) { if (context.Engine.UntouchableMethods.Contains(method)) { continue; } for (int i = 0; i < method.Body.Instructions.Count; i++) { ByteCodeInstruction byteCodeInstruction = method.Body.Instructions[i]; MethodDefinition newMethod = null; IMethod operand = null; if (byteCodeInstruction.OpCode.Equal(ByteOpCodes.InvokeVirtual)) { operand = (IMethod)byteCodeInstruction.Operand; if (flags.HasFlag(CallFlags.InvokeVirtual)) { newMethod = proxyCallsUtils.Create(operand, byteCodeInstruction, true); } } else if (byteCodeInstruction.OpCode.Equal(ByteOpCodes.InvokeStatic)) { operand = (IMethod)byteCodeInstruction.Operand; if (flags.HasFlag(CallFlags.InvokeStatic)) { newMethod = proxyCallsUtils.Create(operand, byteCodeInstruction, false); } } if (newMethod == null) { continue; } context.Engine.UntouchableMethods.Add(newMethod); context.Class.Methods.Add(newMethod); method.Body.Instructions[i] = new ByteCodeInstruction(ByteOpCodes.InvokeStatic, new MethodReference(newMethod.Name, context.Class, newMethod.Descriptor)); } } context.Engine.UntouchableMethods.Clear(); }
protected internal void CallContract(UInt160 contractHash, string method, CallFlags callFlags, bool hasReturnValue, ushort pcount) { if (method.StartsWith('_')) { throw new ArgumentException($"Invalid Method Name: {method}"); } if ((callFlags & ~CallFlags.All) != 0) { throw new ArgumentOutOfRangeException(nameof(callFlags)); } if (pcount > CurrentContext.EvaluationStack.Count) { throw new InvalidOperationException(); } StackItem[] args = new StackItem[pcount]; for (int i = 0; i < pcount; i++) { args[i] = Pop(); } CallContractInternal(contractHash, method, callFlags, hasReturnValue, args); }
private bool _loadScript(Script script, CallFlags flags, UInt160 hash = null, int rvcount = -1, int initialPosition = 0) { this.isEngineInitialized(); if (hash == null) { this.engine.LoadScript(script, rvcount, initialPosition, p => { p.CallFlags = flags; }); return(true); } this.engine.LoadScript(script, rvcount, initialPosition, p => { p.CallFlags = flags; p.ScriptHash = hash; }); return(true); }
public void StartUnary(BatchContextSafeHandle ctx, byte[] payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags) { throw new NotImplementedException(); }
private void CallContractInternal(UInt160 contractHash, string method, Array args, CallFlags flags, ReturnTypeConvention convention) { if (method.StartsWith('_')) { throw new ArgumentException($"Invalid Method Name: {method}"); } ContractState contract = NativeContract.Management.GetContract(Snapshot, contractHash); if (contract is null) { throw new InvalidOperationException($"Called Contract Does Not Exist: {contractHash}"); } ContractMethodDescriptor md = contract.Manifest.Abi.GetMethod(method); if (md is null) { throw new InvalidOperationException($"Method {method} Does Not Exist In Contract {contractHash}"); } if (md.Safe) { flags &= ~CallFlags.WriteStates; } else { ContractState currentContract = NativeContract.Management.GetContract(Snapshot, CurrentScriptHash); if (currentContract?.CanCall(contract, method) == false) { throw new InvalidOperationException($"Cannot Call Method {method} Of Contract {contractHash} From Contract {CurrentScriptHash}"); } } CallContractInternal(contract, md, args, flags, convention); }
protected internal void CallContractEx(UInt160 contractHash, string method, Array args, CallFlags callFlags) { if ((callFlags & ~CallFlags.All) != 0) { throw new ArgumentOutOfRangeException(nameof(callFlags)); } CallContractInternal(contractHash, method, args, callFlags, ReturnTypeConvention.EnsureNotEmpty); }
public void StartDuplexStreaming(ReceivedStatusOnClientHandler callback, MetadataArraySafeHandle metadataArray, CallFlags callFlags) { using (completionQueue.NewScope()) { var ctx = BatchContextSafeHandle.Create(); completionQueue.CompletionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedStatusOnClient())); Native.grpcsharp_call_start_duplex_streaming(this, ctx, metadataArray, callFlags).CheckOk(); } }
public void StartDuplexStreaming(ReceivedStatusOnClientHandler callback, MetadataArraySafeHandle metadataArray, CallFlags callFlags) { ReceivedStatusOnClientHandler = callback; }
public void StartServerStreaming(ReceivedStatusOnClientHandler callback, byte[] payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags) { ReceivedStatusOnClientHandler = callback; }
public void StartClientStreaming(UnaryResponseClientHandler callback, MetadataArraySafeHandle metadataArray, CallFlags callFlags) { UnaryResponseClientHandler = callback; }
public void StartUnary(UnaryResponseClientHandler callback, byte[] payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags) { UnaryResponseClientHandler = callback; }
/// <summary> /// Returns new instance of <see cref="CallOptions"/> with /// <c>Flags</c> set to the value provided. Values of all other fields are preserved. /// </summary> /// <param name="flags">The call flags.</param> internal CallOptions WithFlags(CallFlags flags) { var newOptions = this; newOptions.flags = flags; return newOptions; }
public void StartUnary(BatchContextSafeHandle ctx, byte[] payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags) { Native.grpcsharp_call_start_unary(this, ctx, payload, new UIntPtr((ulong)payload.Length), writeFlags, metadataArray, callFlags) .CheckOk(); }