/// <summary> /// /// </summary> /// <param name="contact"></param> /// <returns></returns> internal static OracleResponse GetContactDetailsFromT4A(Entity contact, string connString, ITracingService tracingService) { //TODO: Clean this //Create a connection to Oracle //string connString = "User Id=ECAS; password=blu3fob$;" + //"Data Source=oltp-scan01-dt.educ.gov.bc.ca:1521/oltpd.world; Pooling=false;"; tracingService.Trace("Starting the GetContactDetailsFromT4A"); OracleResponse oracleResponse = new OracleResponse(); OracleConnection conn = new OracleConnection(); conn.ConnectionString = connString; OracleCommand objCmd = new OracleCommand(); objCmd.Connection = conn; objCmd.CommandText = ConfigEntity.ORACLE_COMMAND_TEXT; //Fetch from T4A the Supplier Number and SiteNumber objCmd.CommandType = CommandType.StoredProcedure; objCmd.Parameters.Add(ConfigEntity.StoredProcedureParams.PARTY_ID, OracleDbType.Double).Value = int.Parse(contact[Contact.PARTY_ID].ToString()); objCmd.Parameters.Add(ConfigEntity.StoredProcedureParams.SUPPLIER_NO, OracleDbType.Varchar2, 100).Direction = ParameterDirection.Output; objCmd.Parameters.Add(ConfigEntity.StoredProcedureParams.SITE_NO, OracleDbType.Char, 3).Direction = ParameterDirection.Output; objCmd.Parameters.Add(ConfigEntity.StoredProcedureParams.STATUS_CODE, OracleDbType.Varchar2, 100).Direction = ParameterDirection.Output; objCmd.Parameters.Add(ConfigEntity.StoredProcedureParams.STATUS_T4A, OracleDbType.Varchar2, 100).Direction = ParameterDirection.Output; objCmd.Parameters.Add(ConfigEntity.StoredProcedureParams.TRANSACTION_MESSAGE, OracleDbType.Varchar2, 2000).Direction = ParameterDirection.Output; objCmd.Parameters.Add(ConfigEntity.StoredProcedureParams.TRANSACTION_CODE, OracleDbType.Varchar2, 100).Direction = ParameterDirection.Output; try { tracingService.Trace("Opening Connection"); conn.Open(); tracingService.Trace("Connection Opened"); objCmd.ExecuteNonQuery(); tracingService.Trace("Query Executed"); oracleResponse.ContactId = contact.Id; oracleResponse.SupplierNumber = objCmd.Parameters[ConfigEntity.StoredProcedureParams.SUPPLIER_NO].Value.ToString(); oracleResponse.SiteNumber = objCmd.Parameters[ConfigEntity.StoredProcedureParams.SITE_NO].Value.ToString(); oracleResponse.StatusCode = objCmd.Parameters[ConfigEntity.StoredProcedureParams.STATUS_CODE].Value.ToString(); oracleResponse.StatusT4A = objCmd.Parameters[ConfigEntity.StoredProcedureParams.STATUS_T4A].Value.ToString(); oracleResponse.TranactionCode = objCmd.Parameters[ConfigEntity.StoredProcedureParams.TRANSACTION_CODE].Value.ToString(); oracleResponse.TransactionMessage = objCmd.Parameters[ConfigEntity.StoredProcedureParams.TRANSACTION_MESSAGE].Value.ToString(); tracingService.Trace("Populated Oracle Response"); } catch (Exception ex) { throw new InvalidPluginExecutionException(OperationStatus.Failed, new StringBuilder().Append(Strings.STORED_PROCEDURE_EXCEPTION) .Append(ConfigEntity.ORACLE_COMMAND_TEXT).AppendLine(" Exception:\n").AppendLine(ex.Message).ToString()); } finally { tracingService.Trace("Closing connection"); conn.Close(); tracingService.Trace("Connection closed"); } return(oracleResponse); }
private ContractTask Finish(ApplicationEngine engine) { if (engine.InvocationStack.Count != 2) { throw new InvalidOperationException(); } if (engine.GetInvocationCounter() != 1) { throw new InvalidOperationException(); } Transaction tx = (Transaction)engine.ScriptContainer; OracleResponse response = tx.GetAttribute <OracleResponse>(); if (response == null) { throw new ArgumentException("Oracle response was not found"); } OracleRequest request = GetRequest(engine.Snapshot, response.Id); if (request == null) { throw new ArgumentException("Oracle request was not found"); } engine.SendNotification(Hash, "OracleResponse", new VM.Types.Array(engine.ReferenceCounter) { response.Id, request.OriginalTxid.ToArray() }); StackItem userData = BinarySerializer.Deserialize(request.UserData, engine.Limits, engine.ReferenceCounter); return(engine.CallFromNativeContract(Hash, request.CallbackContract, request.CallbackMethod, request.Url, userData, (int)response.Code, response.Result)); }
} //End of Execute /// <summary> /// /// </summary> /// <param name="v"></param> /// <returns></returns> private Entity GetUpdatedContact(OracleResponse oracleResponse, IOrganizationService service, ITracingService tracingService) { Entity contact = new Entity(Contact.ENTITY_NAME); tracingService.Trace(string.Format("Hi! ORACLEResponse.StatusT4A = {0}", oracleResponse.StatusT4A)); if (oracleResponse.StatusT4A == OracleResponse.T4A_STATUS.OK) { tracingService.Trace(string.Format("oracleResponse.ContactId = {0}", oracleResponse.ContactId)); tracingService.Trace(string.Format("oracleResponse.SiteNumber = {0}", oracleResponse.SupplierNumber)); tracingService.Trace(string.Format("oracleResponse.SiteNumber = {0}", oracleResponse.SiteNumber)); contact[Contact.ID] = oracleResponse.ContactId; contact[Contact.SUPPLIER_NUMBER] = oracleResponse.SupplierNumber; contact[Contact.SUPPLIER_SITE_NUMBER] = oracleResponse.SiteNumber; contact[Contact.SUPPLIER_STATUS] = new OptionSetValue(Contact.SUPPLIER_STATUSES.SUPPLIER_VERIFIED); tracingService.Trace("Contact populated"); return(contact); } else { //TODO: //Log Error. Handle the bad request here tracingService.Trace("Going to Log the Integration error now"); //Helper.LogIntegrationError(service, Strings.T4A_FER_ERROR, Helper.GetFormatedDescription(contact, ErrorType.CONTACT_ERROR, IntegrationErrorCodes.FETCH_SUPPLIER, Strings.PARTY_ID_MISSING_DESCRIPTION), // IntegrationErrorCodes.FETCH_SUPPLIER.GetIntValue(), new EntityReference(Contact.ENTITY_NAME, contact.Id)); Helper.LogIntegrationError(service, "T4A returned FER", "FER Description", IntegrationErrorCodes.FETCH_SUPPLIER.GetIntValue(), new EntityReference(Contact.ENTITY_NAME, oracleResponse.ContactId)); contact[Contact.ID] = oracleResponse.ContactId; contact[Contact.SUPPLIER_STATUS] = new OptionSetValue(Contact.SUPPLIER_STATUSES.T4A_ERROR_OCCURRED); service.Update(contact); return(null); } }
public async Task <UInt256> SubmitOracleResponseAsync(OracleResponse response, ECPoint[] oracleNodes) { var jsonTx = await rpcClient.RpcSendAsync("expresscreateoracleresponsetx", response.ToJson()).ConfigureAwait(false); var tx = Convert.FromBase64String(jsonTx.AsString()).AsSerializable <Transaction>(); ExpressOracle.SignOracleResponseTransaction(chain, tx, oracleNodes); return(await SubmitTransactionAsync(tx)); }
/// <summary> /// Determines whether the specified account has witnessed the current transaction. /// </summary> /// <param name="hash">The hash of the account.</param> /// <returns><see langword="true"/> if the account has witnessed the current transaction; otherwise, <see langword="false"/>.</returns> protected internal bool CheckWitnessInternal(UInt160 hash) { if (hash.Equals(CallingScriptHash)) return true; if (ScriptContainer is Transaction tx) { Signer[] signers; OracleResponse response = tx.GetAttribute<OracleResponse>(); if (response is null) { signers = tx.Signers; } else { OracleRequest request = NativeContract.Oracle.GetRequest(Snapshot, response.Id); signers = NativeContract.Ledger.GetTransaction(Snapshot, request.OriginalTxid).Signers; } Signer signer = signers.FirstOrDefault(p => p.Account.Equals(hash)); if (signer is null) return false; if (signer.Scopes == WitnessScope.Global) return true; if (signer.Scopes.HasFlag(WitnessScope.CalledByEntry)) { if (CallingScriptHash == null || CallingScriptHash == EntryScriptHash) return true; } if (signer.Scopes.HasFlag(WitnessScope.CustomContracts)) { if (signer.AllowedContracts.Contains(CurrentScriptHash)) return true; } if (signer.Scopes.HasFlag(WitnessScope.CustomGroups)) { // Check allow state callflag ValidateCallFlags(CallFlags.ReadStates); var contract = NativeContract.ContractManagement.GetContract(Snapshot, CallingScriptHash); // check if current group is the required one if (contract.Manifest.Groups.Select(p => p.PubKey).Intersect(signer.AllowedGroups).Any()) return true; } return false; } // Check allow state callflag ValidateCallFlags(CallFlags.ReadStates); // only for non-Transaction types (Block, etc) var hashes_for_verifying = ScriptContainer.GetScriptHashesForVerifying(Snapshot); return hashes_for_verifying.Contains(hash); }
public void TestCreateOracleResponseTx() { var snapshot = Blockchain.Singleton.GetSnapshot(); var executionFactor = NativeContract.Policy.GetExecFeeFactor(snapshot); Assert.AreEqual(executionFactor, (uint)30); var feePerByte = NativeContract.Policy.GetFeePerByte(snapshot); Assert.AreEqual(feePerByte, (uint)1000); OracleRequest request = new OracleRequest { OriginalTxid = UInt256.Zero, GasForResponse = 100000000 * 1, Url = "https://127.0.0.1/test", Filter = "", CallbackContract = UInt160.Zero, CallbackMethod = "callback", UserData = System.Array.Empty <byte>() }; byte Prefix_Transaction = 11; snapshot.Add(NativeContract.Ledger.CreateStorageKey(Prefix_Transaction, request.OriginalTxid), new StorageItem(new TransactionState() { BlockIndex = 1, Transaction = new Transaction() { ValidUntilBlock = 1 } })); OracleResponse response = new OracleResponse() { Id = 1, Code = OracleResponseCode.Success, Result = new byte[] { 0x00 } }; ECPoint[] oracleNodes = new ECPoint[] { ECCurve.Secp256r1.G }; var tx = OracleService.CreateResponseTx(snapshot, request, response, oracleNodes); Assert.AreEqual(167, tx.Size); Assert.AreEqual(2216640, tx.NetworkFee); Assert.AreEqual(97783360, tx.SystemFee); // case (2) The size of attribute exceed the maximum limit request.GasForResponse = 0_10000000; response.Result = new byte[10250]; tx = OracleService.CreateResponseTx(snapshot, request, response, oracleNodes); Assert.AreEqual(166, tx.Size); Assert.AreEqual(OracleResponseCode.InsufficientFunds, response.Code); Assert.AreEqual(2215640, tx.NetworkFee); Assert.AreEqual(7784360, tx.SystemFee); }
private UInt256 GetOriginalTxid(ApplicationEngine engine) { Transaction tx = (Transaction)engine.ScriptContainer; OracleResponse response = tx.GetAttribute <OracleResponse>(); if (response is null) { return(tx.Hash); } OracleRequest request = GetRequest(engine.Snapshot, response.Id); return(request.OriginalTxid); }
/// <summary> /// Determines whether the specified account has witnessed the current transaction. /// </summary> /// <param name="hash">The hash of the account.</param> /// <returns><see langword="true"/> if the account has witnessed the current transaction; otherwise, <see langword="false"/>.</returns> protected internal bool CheckWitnessInternal(UInt160 hash) { if (hash.Equals(CallingScriptHash)) { return(true); } if (ScriptContainer is Transaction tx) { Signer[] signers; OracleResponse response = tx.GetAttribute <OracleResponse>(); if (response is null) { signers = tx.Signers; } else { OracleRequest request = NativeContract.Oracle.GetRequest(Snapshot, response.Id); signers = NativeContract.Ledger.GetTransaction(Snapshot, request.OriginalTxid).Signers; } Signer signer = signers.FirstOrDefault(p => p.Account.Equals(hash)); if (signer is null) { return(false); } foreach (WitnessRule rule in signer.GetAllRules()) { if (rule.Condition.Match(this)) { return(rule.Action == WitnessRuleAction.Allow); } } return(false); } // Check allow state callflag ValidateCallFlags(CallFlags.ReadStates); // only for non-Transaction types (Block, etc) var hashes_for_verifying = ScriptContainer.GetScriptHashesForVerifying(Snapshot); return(hashes_for_verifying.Contains(hash)); }
public JObject?ExpressCreateOracleResponseTx(JArray @params) { var jsonResponse = @params[0]; var response = new OracleResponse { Id = (ulong)jsonResponse["id"].AsNumber(), Code = (OracleResponseCode)jsonResponse["code"].AsNumber(), Result = Convert.FromBase64String(jsonResponse["result"].AsString()) }; using var snapshot = neoSystem.GetSnapshot(); var height = NativeContract.Ledger.CurrentIndex(snapshot) + 1; var oracleNodes = NativeContract.RoleManagement.GetDesignatedByRole(snapshot, Role.Oracle, height); var request = NativeContract.Oracle.GetRequest(snapshot, response.Id); var tx = ExpressOracle.CreateResponseTx(snapshot, request, response, oracleNodes, neoSystem.Settings); return(tx == null ? null : Convert.ToBase64String(tx.ToArray())); }
private void Finish(ApplicationEngine engine) { Transaction tx = (Transaction)engine.ScriptContainer; OracleResponse response = tx.GetAttribute <OracleResponse>(); if (response == null) { throw new ArgumentException("Oracle response was not found"); } OracleRequest request = GetRequest(engine.Snapshot, response.Id); if (request == null) { throw new ArgumentException("Oracle request was not found"); } StackItem userData = BinarySerializer.Deserialize(request.UserData, engine.MaxStackSize, engine.MaxItemSize, engine.ReferenceCounter); engine.CallFromNativeContract(null, request.CallbackContract, request.CallbackMethod, request.Url, userData, (int)response.Code, response.Result); }
public async Task <UInt256> SubmitOracleResponseAsync(OracleResponse response, IReadOnlyList <ECPoint> oracleNodes) { if (disposedValue) { throw new ObjectDisposedException(nameof(OfflineNode)); } using var snapshot = neoSystem.GetSnapshot(); var height = NativeContract.Ledger.CurrentIndex(snapshot) + 1; var request = NativeContract.Oracle.GetRequest(snapshot, response.Id); var tx = ExpressOracle.CreateResponseTx(snapshot, request, response, oracleNodes, ProtocolSettings); if (tx == null) { throw new Exception("Failed to create Oracle Response Tx"); } ExpressOracle.SignOracleResponseTransaction(ProtocolSettings, chain, tx, oracleNodes); return(await SubmitTransactionAsync(tx)); }
private void Finish(ApplicationEngine engine) { Transaction tx = (Transaction)engine.ScriptContainer; OracleResponse response = tx.GetAttribute <OracleResponse>(); if (response == null) { throw new ArgumentException("Oracle response was not found"); } OracleRequest request = GetRequest(engine.Snapshot, response.Id); if (request == null) { throw new ArgumentException("Oracle request was not found"); } engine.SendNotification(Hash, "OracleResponse", new VM.Types.Array { response.Id, request.OriginalTxid.ToArray() }); StackItem userData = BinarySerializer.Deserialize(request.UserData, engine.Limits.MaxStackSize, engine.Limits.MaxItemSize, engine.ReferenceCounter); engine.CallFromNativeContract(() => { }, request.CallbackContract, request.CallbackMethod, request.Url, userData, (int)response.Code, response.Result); }
protected override void Execute(CodeActivityContext executionContext) { //Create the tracing service ITracingService tracingService = executionContext.GetExtension <ITracingService>(); //Create the context IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>(); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); tracingService.Trace("Loaded UpsertSupplierWorkflow"); tracingService.Trace("CREATING Contact object with the input values"); tracingService.Trace("Checkpoint 1"); Contact contact = new Contact(); int partyid = PartyID.Get <int>(executionContext); tracingService.Trace("Starting assigning attribute variables."); contact.First_Name = FirstName.Get <string>(executionContext).ToString(); tracingService.Trace("First Name Populated"); tracingService.Trace(string.Format("Setting party id = {0}", partyid)); contact.Party_Id = partyid; tracingService.Trace("Party ID populated"); contact.Last_Name = LastName.Get <string>(executionContext).ToString(); tracingService.Trace("Last Name Populated"); contact.Payment_Method = PaymentMethod.Get <string>(executionContext).ToString(); tracingService.Trace("Payment Method Populated"); contact.SIN = SIN.Get <string>(executionContext).ToString(); tracingService.Trace("SIN Populated"); contact.Address1 = Address1.Get <string>(executionContext).ToString(); tracingService.Trace("Address1 Populated"); contact.Country_Code = Country.Get <string>(executionContext).ToString(); tracingService.Trace("Country Populated"); contact.City = City.Get <string>(executionContext).ToString(); tracingService.Trace("City Populated"); contact.Province_Code = Province.Get <string>(executionContext).ToString(); tracingService.Trace("Province Populated"); contact.Postal_Code = PostalCode.Get <string>(executionContext).ToString(); tracingService.Trace("Postal Code Populated"); tracingService.Trace("Checkpoint 2"); EntityReference contactRef = ContactReference.Get <EntityReference>(executionContext); contact.ID = contactRef.Id; tracingService.Trace("Fetching the Configs"); ////Get the configuration record for Oracle_T4A group from the configs entity and get the connection value from the record. var configs = Helper.GetSystemConfigurations(service, ConfigEntity.Group.ORACLE_T4A, string.Empty); tracingService.Trace("Fetching Connection"); string connection = Helper.GetConfigKeyValue(configs, ConfigEntity.Key.CONNECTION, ConfigEntity.Group.ORACLE_T4A); try { tracingService.Trace("Fetching Oracle Response by making call to Helper.UpsertSupplierInOracle()"); OracleResponse response = Helper.UpsertSupplierInOracle(contact, connection, tracingService); if (response.TransactionCode == OracleResponse.T4A_STATUS.OK) { tracingService.Trace("Inside OracleResponse.T4A_STATUS.OK \nRetriving and setting response values to output"); PartyID.Set(executionContext, response.PartyId); tracingService.Trace("Party ID Output Param is set"); } tracingService.Trace("Setting up transaction code and transaction message"); TransactionCode.Set(executionContext, response.TransactionCode.Trim()); TransactionMessage.Set(executionContext, response.TransactionMessage); } catch (InvalidWorkflowException ex) { Helper.LogIntegrationError(service, ErrorType.CONTACT_ERROR, IntegrationErrorCodes.UPSERT_SUPPLIER.GetIntValue(), Strings.T4A_FER_ERROR, string.Format("Error Description: {0} ", ex.Message), contactRef); } catch (Exception ex) { Helper.LogIntegrationError(service, ErrorType.CONTACT_ERROR, IntegrationErrorCodes.UPSERT_SUPPLIER.GetIntValue(), Strings.T4A_FER_ERROR, string.Format("Error Description: {0} ", ex.Message), contactRef); } }
/// <summary> /// /// </summary> /// <param name="contact"></param> /// <returns></returns> internal static OracleResponse UpsertSupplierInOracle(Contact contact, string connString, ITracingService tracingService) { tracingService.Trace("Starting the UpsertSupplierInOracle"); OracleResponse oracleResponse = new OracleResponse(); OracleConnection conn = new OracleConnection(); conn.ConnectionString = connString; OracleCommand objCmd = new OracleCommand(); objCmd.Connection = conn; objCmd.CommandText = ConfigEntity.ORACLE_COMMAND_TEXT; //Upsert Supplier in Oracle objCmd.CommandType = CommandType.StoredProcedure; objCmd.Parameters.Add(ConfigEntity.SPParams.FIRST_NAME, OracleDbType.Varchar2, 100).Value = contact.First_Name; objCmd.Parameters.Add(ConfigEntity.SPParams.LAST_NAME, OracleDbType.Varchar2, 100).Value = contact.Last_Name; objCmd.Parameters.Add(ConfigEntity.SPParams.PAYMENT_METHOD, OracleDbType.Varchar2, 10).Value = contact.Payment_Method; //EFT or CHQ // Send EFT from code objCmd.Parameters.Add(ConfigEntity.SPParams.SIN, OracleDbType.Double, 100).Value = int.Parse(contact.SIN); objCmd.Parameters.Add(ConfigEntity.SPParams.ADDRESS1, OracleDbType.Varchar2, 1000).Value = contact.Address1; objCmd.Parameters.Add(ConfigEntity.SPParams.CITY, OracleDbType.Varchar2, 2000).Value = contact.City; objCmd.Parameters.Add(ConfigEntity.SPParams.POSTAL_CODE, OracleDbType.Varchar2, 10).Value = contact.Postal_Code; objCmd.Parameters.Add(ConfigEntity.SPParams.PROVINCE_CODE, OracleDbType.Varchar2, 20).Value = contact.Province_Code; objCmd.Parameters.Add(ConfigEntity.SPParams.COUNTRY_CODE, OracleDbType.Varchar2, 10).Value = contact.Country_Code; objCmd.Parameters.Add(ConfigEntity.SPParams.VALID_FROM, OracleDbType.Date, 2000).Value = DateTime.Today.Date; //Output Params if (contact.Party_Id > 0) //If an update request than send party ID { objCmd.Parameters.Add(ConfigEntity.SPParams.PARTY_ID, OracleDbType.Double, 2000).Value = contact.Party_Id; } else //Since Party ID is -1 i.e. the create request. { objCmd.Parameters.Add(ConfigEntity.SPParams.PARTY_ID, OracleDbType.Double, 2000).Direction = ParameterDirection.InputOutput; } objCmd.Parameters.Add(ConfigEntity.SPParams.TRANSACTION_CODE, OracleDbType.Varchar2, 1000).Direction = ParameterDirection.Output; objCmd.Parameters.Add(ConfigEntity.SPParams.TRANSACTION_MESSAGE, OracleDbType.Varchar2, 2000).Direction = ParameterDirection.Output; try { tracingService.Trace("Opening Connection"); conn.Open(); tracingService.Trace("Connection Opened"); objCmd.ExecuteNonQuery(); tracingService.Trace("Query Executed"); oracleResponse.PartyId = int.Parse(objCmd.Parameters[ConfigEntity.SPParams.PARTY_ID].Value.ToString()); oracleResponse.TransactionMessage = objCmd.Parameters[ConfigEntity.SPParams.TRANSACTION_MESSAGE].Value.ToString(); oracleResponse.TransactionCode = objCmd.Parameters[ConfigEntity.SPParams.TRANSACTION_CODE].Value.ToString(); tracingService.Trace("Populated Oracle Response"); } catch (Exception ex) { throw new InvalidPluginExecutionException(OperationStatus.Failed, new StringBuilder().Append(Strings.STORED_PROCEDURE_EXCEPTION) .Append(ConfigEntity.ORACLE_COMMAND_TEXT).AppendLine(" Exception:\n").AppendLine(ex.Message).ToString()); } finally { tracingService.Trace("Closing connection"); conn.Close(); tracingService.Trace("Connection closed"); } return(oracleResponse); }
// Copied from OracleService.CreateResponseTx to avoid taking dependency on OracleService package and it's 110mb GRPC runtime public static Transaction?CreateResponseTx(DataCache snapshot, OracleRequest request, OracleResponse response, IReadOnlyList <ECPoint> oracleNodes, ProtocolSettings settings) { if (oracleNodes.Count == 0) { throw new Exception("No oracle nodes available. Have you enabled oracles via the `oracle enable` command?"); } var requestTx = NativeContract.Ledger.GetTransactionState(snapshot, request.OriginalTxid); var n = oracleNodes.Count; var m = n - (n - 1) / 3; var oracleSignContract = Contract.CreateMultiSigContract(m, oracleNodes); var tx = new Transaction() { Version = 0, Nonce = unchecked ((uint)response.Id), ValidUntilBlock = requestTx.BlockIndex + settings.MaxValidUntilBlockIncrement, Signers = new[] { new Signer { Account = NativeContract.Oracle.Hash, Scopes = WitnessScope.None }, new Signer { Account = oracleSignContract.ScriptHash, Scopes = WitnessScope.None } }, Attributes = new[] { response }, Script = OracleResponse.FixedScript, Witnesses = new Witness[2] }; Dictionary <UInt160, Witness> witnessDict = new Dictionary <UInt160, Witness> { [oracleSignContract.ScriptHash] = new Witness { InvocationScript = Array.Empty <byte>(), VerificationScript = oracleSignContract.Script, }, [NativeContract.Oracle.Hash] = new Witness { InvocationScript = Array.Empty <byte>(), VerificationScript = Array.Empty <byte>(), } }; UInt160[] hashes = tx.GetScriptHashesForVerifying(snapshot); tx.Witnesses[0] = witnessDict[hashes[0]]; tx.Witnesses[1] = witnessDict[hashes[1]]; // Calculate network fee var oracleContract = NativeContract.ContractManagement.GetContract(snapshot, NativeContract.Oracle.Hash); var engine = ApplicationEngine.Create(TriggerType.Verification, tx, snapshot.CreateSnapshot(), settings: settings); ContractMethodDescriptor md = oracleContract.Manifest.Abi.GetMethod("verify", -1); engine.LoadContract(oracleContract, md, CallFlags.None); if (engine.Execute() != Neo.VM.VMState.HALT) { return(null); } tx.NetworkFee += engine.GasConsumed; var executionFactor = NativeContract.Policy.GetExecFeeFactor(snapshot); var networkFee = executionFactor * Neo.SmartContract.Helper.MultiSignatureContractCost(m, n); tx.NetworkFee += networkFee; // Base size for transaction: includes const_header + signers + script + hashes + witnesses, except attributes int size_inv = 66 * m; int size = Transaction.HeaderSize + tx.Signers.GetVarSize() + tx.Script.GetVarSize() + Neo.IO.Helper.GetVarSize(hashes.Length) + witnessDict[NativeContract.Oracle.Hash].Size + Neo.IO.Helper.GetVarSize(size_inv) + size_inv + oracleSignContract.Script.GetVarSize(); var feePerByte = NativeContract.Policy.GetFeePerByte(snapshot); if (response.Result.Length > OracleResponse.MaxResultSize) { response.Code = OracleResponseCode.ResponseTooLarge; response.Result = Array.Empty <byte>(); } else if (tx.NetworkFee + (size + tx.Attributes.GetVarSize()) * feePerByte > request.GasForResponse) { response.Code = OracleResponseCode.InsufficientFunds; response.Result = Array.Empty <byte>(); } size += tx.Attributes.GetVarSize(); tx.NetworkFee += size * feePerByte; // Calculate system fee tx.SystemFee = request.GasForResponse - tx.NetworkFee; return(tx); }
public void Execute(IServiceProvider serviceProvider) { // Obtain the tracing service ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); // Obtain the execution context from the service provider. IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); // The InputParameters collection contains all the data passed in the message request. if (context.InputParameters.Contains(Strings.TARGET) && context.InputParameters != null) { // Obtain the target entity from the input parameters. // Obtain the organization service reference which you will need for // web service calls. IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); tracingService.Trace(Strings.LOADED_UPDATE_SUPPLIER_PLUGIN); tracingService.Trace(Strings.PLUGIN_DEPTH + context.Depth.ToString()); if (context.Depth > 2) { return; } //Fetch all contact records that have Supplier Status (OptionSet) = "New CAS User" OR "Update Requested" List <Entity> contactsToFetch = Helper.GetAllContactsForCASUpdates(service, tracingService); tracingService.Trace("Fetched the contacts"); List <Entity> updatedContacts = new List <Entity>(); Entity contactItem; tracingService.Trace("Fetching the Configs"); ////Get the configuration record for Oracle_T4A group from the configs entity and get the connection value from the record. var configs = Helper.GetSystemConfigurations(service, ConfigEntity.Group.ORACLE_T4A, string.Empty); tracingService.Trace("Fetching Connection"); string connection = Helper.GetConfigKeyValue(configs, ConfigEntity.Key.CONNECTION, ConfigEntity.Group.ORACLE_T4A); tracingService.Trace("Fetched Configs and Connection"); int partyId; string supplierNumber = string.Empty; string siteNumber = string.Empty; string statusCode = string.Empty; string statusT4A = string.Empty; string transactionMessage = string.Empty; //Iterate over the contact records to call the stored procedure and get back results from T4A SP foreach (Entity contact in contactsToFetch) { if (contact.Contains(Contact.ID)) { tracingService.Trace(string.Format("Contact ID = {0}", contact.Id)); } if (!contact.Contains(Contact.PARTY_ID)) { tracingService.Trace("Inside Party ID doesnt exists"); //Create the Error Log that party ID doesn't exist. Helper.LogIntegrationError(service, Strings.PARTY_ID_MISSING, Helper.GetFormatedDescription(contact, ErrorType.CONTACT_ERROR, IntegrationErrorCodes.FETCH_SUPPLIER, Strings.PARTY_ID_MISSING_DESCRIPTION), IntegrationErrorCodes.FETCH_SUPPLIER.GetIntValue(), new EntityReference(Contact.ENTITY_NAME, contact.Id)); tracingService.Trace("CheckPoint 100"); if (contact.Attributes.Contains(Contact.SUPPLIER_STATUS)) { tracingService.Trace("CheckPoint 200"); //Update the Contact Record with the T4A Error Occurred contact[Contact.SUPPLIER_STATUS] = new OptionSetValue(Contact.SUPPLIER_STATUSES.T4A_ERROR_OCCURRED); service.Update(contact); } tracingService.Trace("CheckPoint 300"); } else { tracingService.Trace("Since Party ID exists, getUpdatedContact"); partyId = int.Parse(contact[Contact.PARTY_ID].ToString()); tracingService.Trace("PartyID = " + partyId.ToString()); OracleResponse response = Helper.GetContactDetailsFromT4A(contact, connection, tracingService); tracingService.Trace("Got Oracle Response"); contactItem = GetUpdatedContact(response, service, tracingService); tracingService.Trace("Got Updated ContactItem"); //If the contact returned is not null, add it to the update job if (contactItem != null) { tracingService.Trace("adding contact item to the updatedContacts list"); updatedContacts.Add(contactItem); } } } try { tracingService.Trace("Sending the updatedContacts to Helper.BatchUpdateRecordsMethod"); //Update the contact records ExecuteMultipleResponse responses = Helper.BatchUpdateRecords(service, updatedContacts); tracingService.Trace("Got the responses back from Helper.BatchUpdateRecords"); // //Create the cron job singleton record Helper.CreateCronJobSingletonRecord(service, SupplierCronJob.ENTITY_NAME, SupplierCronJob.NAME, Strings.SINGLETON_RECORD); } catch (FaultException <OrganizationServiceFault> ex) { tracingService.Trace(Strings.UPDATE_SUPPLIER_PLUGIN_SHORT_ERROR, ex.ToString()); throw new InvalidPluginExecutionException(Strings.UPDATE_SUPPLIER_PLUGIN_ERROR_OCCURED, ex); } catch (Exception ex) { tracingService.Trace(Strings.UPDATE_SUPPLIER_PLUGIN_SHORT_ERROR, ex.ToString()); throw; } } //End of IF condition } //End of Execute
protected internal bool CheckWitnessInternal(UInt160 hash) { if (hash.Equals(CallingScriptHash)) { return(true); } if (ScriptContainer is Transaction tx) { Signer[] signers; OracleResponse response = tx.GetAttribute <OracleResponse>(); if (response is null) { signers = tx.Signers; } else { OracleRequest request = NativeContract.Oracle.GetRequest(Snapshot, response.Id); signers = Snapshot.GetTransaction(request.OriginalTxid).Signers; } Signer signer = signers.FirstOrDefault(p => p.Account.Equals(hash)); if (signer is null) { return(false); } if (signer.Scopes == WitnessScope.Global) { return(true); } if (signer.Scopes.HasFlag(WitnessScope.CalledByEntry)) { if (CallingScriptHash == null || CallingScriptHash == EntryScriptHash) { return(true); } } if (signer.Scopes.HasFlag(WitnessScope.CustomContracts)) { if (signer.AllowedContracts.Contains(CurrentScriptHash)) { return(true); } } if (signer.Scopes.HasFlag(WitnessScope.CustomGroups)) { // Check allow state callflag if (!CurrentContext.GetState <ExecutionContextState>().CallFlags.HasFlag(CallFlags.ReadStates)) { throw new InvalidOperationException($"Cannot call this SYSCALL without the flag AllowStates."); } var contract = NativeContract.Management.GetContract(Snapshot, CallingScriptHash); // check if current group is the required one if (contract.Manifest.Groups.Select(p => p.PubKey).Intersect(signer.AllowedGroups).Any()) { return(true); } } return(false); } // Check allow state callflag if (!CurrentContext.GetState <ExecutionContextState>().CallFlags.HasFlag(CallFlags.ReadStates)) { throw new InvalidOperationException($"Cannot call this SYSCALL without the flag AllowStates."); } // only for non-Transaction types (Block, etc) var hashes_for_verifying = ScriptContainer.GetScriptHashesForVerifying(Snapshot); return(hashes_for_verifying.Contains(hash)); }