/// <summary> /// /// This method will persist all data to files (metadata, rules, current data, report), zip the files, and then upload the .ZIP to IPFS /// /// <param name="poEngine">The instance of the Wonka engine that has just run</param> /// <param name="poEngineInitProps">Various properties of this instance of the Wonka engine</param> /// <param name="poRecord">This record holds the current snapshot of the data being addressed by the metadata (mentioned in WonkaRefEnvironment)</param> /// <param name="poReport">This report holds the verbose results of running the RuleTree</param> /// <param name="psIpfsUrl">This URL points to the IPFS node that acts as the read-only gateway</param> /// <param name="psWriteIpfsUrl">This URL points to the IPFS node that will be used to upload the Zip file of the results</param> /// <param name="psUniqueChronoLogName">This will be the unique name of the ChronoLog entry</param> /// <returns>IPFS ID of the new file</returns> /// </summary> public static async Task <string> UploadInvocationAsync(this WonkaBizRulesEngine poEngine, Wonka.Eth.Init.WonkaEthEngineInitialization poEngineInitProps, WonkaProduct poRecord, Wonka.Eth.Extensions.RuleTreeReport poReport, string psIpfsUrl, string psWriteIpfsUrl, string psUniqueChronoLogName) { string sZipIpfsUrl = ""; var RefEnv = WonkaRefEnvironment.GetInstance(); string sZipFileUrl = poEngine.ZipInvocation(poRecord, poReport, psUniqueChronoLogName); var zipBytes = File.ReadAllBytes(sZipFileUrl); using (MemoryStream zipStream = new MemoryStream(zipBytes)) { var ipfsClient = new IpfsClient(psWriteIpfsUrl); var merkleNode = await ipfsClient.FileSystem.AddFileAsync(sZipFileUrl, new Ipfs.CoreApi.AddFileOptions() { Pin = true }).ConfigureAwait(false); sZipIpfsUrl = psIpfsUrl + "/" + merkleNode.Id.Hash.ToString(); } return(sZipIpfsUrl); }
public static WonkaBizRuleSet FindRuleSet(this WonkaBizRulesEngine rulesEngine, int pnTargetRuleSetId) { WonkaBizRuleSet FoundRuleSet = new WonkaBizRuleSet(); if (rulesEngine.RuleTreeRoot.RuleSetId == pnTargetRuleSetId) { return(rulesEngine.RuleTreeRoot); } foreach (var TmpChildSet in rulesEngine.RuleTreeRoot.ChildRuleSets) { if (TmpChildSet.RuleSetId == pnTargetRuleSetId) { return(TmpChildSet); } else { FoundRuleSet = FindRuleSet(TmpChildSet, pnTargetRuleSetId); if (IsValidRuleSet(FoundRuleSet)) { break; } } } return(FoundRuleSet); }
// NOTE: This code will need to be modified in order to work correctly public static async Task <string> RegisterOnENS(this WonkaBizRulesEngine poEngine) { var durationInDays = 365; // how long we are going to rent the domain for var ourName = "supersillynameformonkeys"; // Our xxxxx.eth domain name var owner = "0x12890d2cce102216644c59dae5baed380d84830c"; // Owner of the domain var secret = "animals in the forest"; //This is the commitment secret, // it should be unique and remember it to be able to finalise your registration var account = new Nethereum.Web3.Accounts.Account("YOURPRIVATE KEY"); var web3 = new Web3(account, "https://mainnet.infura.io/v3/7238211010344719ad14a89db874158c"); var ethTLSService = new EthTLSService(web3); await ethTLSService.InitialiseAsync(); // Initialising to retrieve the controller //How much is going to cost var price = await ethTLSService.CalculateRentPriceInEtherAsync(ourName, durationInDays); Console.WriteLine(price); //Calculate the commitment that will be submitted for reservation var commitment = await ethTLSService.CalculateCommitmentAsync(ourName, owner, secret); Console.WriteLine(commitment.ToHex()); //You can now create your commitment and wait for it to be included on the chain var commitTransactionReceipt = await ethTLSService.CommitRequestAndWaitForReceiptAsync(commitment); // Once is on chain you can complete the registration var txnHash = await ethTLSService.RegisterRequestAsync(ourName, owner, durationInDays, secret, price); return(txnHash); }
public static WonkaBizRule FindRuleById(this WonkaBizRulesEngine rulesEngine, string psSoughtId) { WonkaBizRule FoundRule = new ArithmeticRule(); foreach (var TmpChildSet in rulesEngine.RuleTreeRoot.ChildRuleSets) { foreach (var TmpRule in TmpChildSet.EvaluativeRules) { if (TmpRule.DescRuleId == psSoughtId) { return(TmpRule); } } foreach (var TmpRule in TmpChildSet.AssertiveRules) { if (TmpRule.DescRuleId == psSoughtId) { return(TmpRule); } } FoundRule = FindRuleById(TmpChildSet, psSoughtId); if (FoundRule.RuleId > 0) { return(FoundRule); } } return(FoundRule); }
public AbstractWonkaOrchestrator(T poCommand, StringBuilder psRules, OrchestrationInitData poOrchInitData, string psGroveId = "", uint pnGroveIndex = 0) { msRulesContents = psRules; Init(poCommand, poOrchInitData); moInitData = poOrchInitData; moRulesEngine = new WonkaBizRulesEngine(msRulesContents, poOrchInitData.BlockchainDataSources, poOrchInitData.BlockchainCustomOpFunctions, poOrchInitData.AttributesMetadataSource, true); if (!String.IsNullOrEmpty(psGroveId) && (pnGroveIndex > 0)) { moRulesEngine.GroveId = psGroveId; moRulesEngine.GroveIndex = pnGroveIndex; } if (poOrchInitData.DefaultBlockchainDataSource != null) { moRulesEngine.DefaultSource = poOrchInitData.DefaultBlockchainDataSource.SourceId; } SerializeRulesEngineToBlockchain(); }
/// <summary> /// /// This method will provide default functionality on the retrieval delegate of each Source /// in an engine's SourceMap . /// /// <param name="poEngine">The Wonka.NET instance that represents the instance on the chain</param> /// <param name="psWeb3Url">The URL for the Ethereum client to which we want to connect</param> /// <returns>N/A</returns> /// </summary> /// public static void SetDefaultSourceRetrievalDelegates(this WonkaBizRulesEngine poEngine, string psWeb3Url = "") { if ((poEngine.SourceMap != null) && (poEngine.SourceMap.Count > 0)) { foreach (string sTmpAttrName in poEngine.SourceMap.Keys) { var TmpSource = poEngine.SourceMap[sTmpAttrName]; if (TmpSource.RetrievalDelegate == null) { if (!String.IsNullOrEmpty(TmpSource.DefaultWeb3Url) && !String.IsNullOrEmpty(psWeb3Url)) { TmpSource.DefaultWeb3Url = psWeb3Url; } if (!String.IsNullOrEmpty(TmpSource.ContractAddress)) { TmpSource.RetrievalDelegate = WonkaStorageExtensions.GetAttrValue; } else if (!String.IsNullOrEmpty(TmpSource.APIWebUrl)) { TmpSource.RetrievalDelegate = WonkaStorageExtensions.GetAttrValueViaWebMethod; } else if (!String.IsNullOrEmpty(TmpSource.SqlDatabase)) { // NOTE: Set delegate that grabs data from SQL Stored procedure } } } } }
private void SerializeRulesEngineToBlockchain() { WonkaRefEnvironment RefEnv = WonkaRefEnvironment.GetInstance(); // Creating an instance of the rules engine using our rules and the metadata moRulesEngine = new WonkaBizRulesEngine(new StringBuilder(msRulesContents), moMetadataSource); moRulesEngine.SetDefaultStdOps(this.msPassword); var contract = GetContract(); var hasRuleTreeFunction = contract.GetFunction(CONST_CONTRACT_FUNCTION_HAS_RT); // Out of gas exception // var gas = new Nethereum.Hex.HexTypes.HexBigInteger(1000000); var gas = hasRuleTreeFunction.EstimateGasAsync(this.msSenderAddress).Result; bool bTreeAlreadyExists = hasRuleTreeFunction.CallAsync <bool>(this.msSenderAddress, gas, null, this.msSenderAddress).Result; if (!bTreeAlreadyExists) { moRulesEngine.Serialize(msSenderAddress, msPassword, msSenderAddress, msContractAddress, msAbiWonka); } }
public static async Task <string> PublishRulesToIpfs(this WonkaBizRulesEngine poEngine, string psIpfsFilePath, IpfsService poIpfsService, bool pbPinFlag = true, string psIpfsGateway = CONST_INFURA_IPFS_API_GATEWAY_URL) { string sIpfsHash = ""; string sRulesXml = ""; sRulesXml = poEngine.ToXml(); if (String.IsNullOrEmpty(psIpfsFilePath)) { psIpfsFilePath = "testruletree"; } if (String.IsNullOrEmpty(sRulesXml)) { throw new Exception("ERROR! No rules XMl serialized from the rules engine."); } var IpfsNode = await poIpfsService.AddTextAsync(psIpfsGateway, sRulesXml, psIpfsFilePath, pbPinFlag).ConfigureAwait(false); sIpfsHash = IpfsNode.Hash.ToString(); return(sIpfsHash); }
public static WonkaBizRuleSet FindRuleSet(this WonkaBizRulesEngine rulesEngine, string psSoughtDescName) { WonkaBizRuleSet FoundRuleSet = new WonkaBizRuleSet(); if (rulesEngine.RuleTreeRoot.Description == psSoughtDescName) { return(rulesEngine.RuleTreeRoot); } foreach (var TmpChildSet in rulesEngine.RuleTreeRoot.ChildRuleSets) { if (TmpChildSet.Description == psSoughtDescName) { return(TmpChildSet); } else { FoundRuleSet = FindRuleSet(TmpChildSet, psSoughtDescName); if (IsValidRuleSet(FoundRuleSet)) { break; } } } return(FoundRuleSet); }
public static string ToXml(this WonkaBizRulesEngine poEngine) { var RulesWriter = new Wonka.BizRulesEngine.Writers.WonkaBizRulesXmlWriter(poEngine); return(RulesWriter.ExportXmlString()); }
public AbstractWonkaValidator(T poCommand, StringBuilder psRules, string psWeb3HttpUrl = null, bool bDeployEngineToBlockchain = false) { BlockchainEngine = new WonkaBlockchainEngine(); BlockchainEngineOwner = string.Empty; msRulesFilepath = null; msRulesContents = psRules; msWeb3HttpUrl = psWeb3HttpUrl; Init(); moRulesEngine = new WonkaBizRulesEngine(msRulesContents); }
private void SerializeRulesEngineToBlockchain(WonkaBizRulesEngine poEngine) { var contract = GetContract(); var hasRuleTreeFunction = contract.GetFunction(CONST_CONTRACT_FUNCTION_HAS_RT); var gas = hasRuleTreeFunction.EstimateGasAsync(this.msSenderAddress).Result; bool bTreeAlreadyExists = hasRuleTreeFunction.CallAsync <bool>(this.msSenderAddress, gas, null, this.msSenderAddress).Result; if (!bTreeAlreadyExists) { poEngine.Serialize(msSenderAddress, msPassword, msSenderAddress, msContractAddress, msAbiWonka); } }
public static uint CalculateMinGasEstimate(this WonkaBizRulesEngine poRulesEngine, uint pnWriteOpGasCost = CONST_GAS_PER_WRITE_OP) { uint nMinGasCost = 50000; // NOTE: Do work here // 63200 gas per op, based on gas default price // 12 ops for Validate, 18 ops Calculate if ((poRulesEngine != null) && (poRulesEngine.RuleTreeRoot != null) && (poRulesEngine.RuleTreeRoot.ChildRuleSets != null)) { poRulesEngine.RuleTreeRoot.ChildRuleSets.ForEach(x => nMinGasCost += (uint)(x.EvaluativeRules.Count * CONST_GAS_PER_READ_OP)); poRulesEngine.RuleTreeRoot.ChildRuleSets.ForEach(x => nMinGasCost += (uint)(x.AssertiveRules.Count * pnWriteOpGasCost)); } return(nMinGasCost); }
public void Execute() { // Using the metadata source, we create an instance of a defined data domain WonkaRefEnvironment RefEnv = WonkaRefEnvironment.GetInstance(); // To test whether the data domain has been created, we plan on retrieving the value // of the "AccountStatus" Attribute WonkaRefAttr AccountStsAttr = RefEnv.GetAttributeByAttrName("AccountStatus"); // Creating an instance of the rules engine using our rules and the metadata WonkaBizRulesEngine RulesEngine = new WonkaBizRulesEngine(new StringBuilder(msRulesContents), moMetadataSource); // Gets a predefined data record that will be our analog for new data coming into the system WonkaProduct NewProduct = GetNewProduct(); // Check that the data has been populated correctly on the "new" record - also, we will use // it later for comparison purposes string sStatusValueBefore = GetAttributeValue(NewProduct, AccountStsAttr); // Since the rules can reference values from different records (like O.Price for the existing // record's price and N.Price for the new record's price), we need to provide the delegate // that can pull the existing (i.e., old) record from the blockchain using a key RulesEngine.GetCurrentProductDelegate = GetOldProduct; // Validate the new record using our rules engine and its initialized RuleTree Wonka.BizRulesEngine.Reporting.WonkaBizRuleTreeReport Report = RulesEngine.Validate(NewProduct); // Now retrieve the AccountStatus value and see if the rules have altered it (which should // not be the case) string sStatusValueAfter = GetAttributeValue(NewProduct, AccountStsAttr); // We will evaluate whether or not any failures of the rules were detected during the engine's execution if (Report.OverallRuleTreeResult == ERR_CD.CD_SUCCESS) { // If successful, we will write the record back into the contract on the blockchain Serialize(NewProduct); } else if (Report.GetRuleSetFailureCount() > 0) { throw new Exception("Oh heavens to Betsy! Something bad happened!"); } else { throw new Exception("What in the world is happening?!"); } }
public RuleTreeReport ExecuteWithReport(WonkaBizRulesEngine poRulesEngine, bool pbValidateWithinTransaction) { WonkaRefEnvironment RefEnv = WonkaRefEnvironment.GetInstance(); WonkaRefAttr CurrValueAttr = RefEnv.GetAttributeByAttrName("AccountCurrValue"); WonkaRefAttr ReviewFlagAttr = RefEnv.GetAttributeByAttrName("AuditReviewFlag"); Dictionary <string, string> PrdKeys = new Dictionary <string, string>(); var contract = GetContract(); var senderAddress = moEthEngineInit.EthSenderAddress; var executeWithReportFunction = contract.GetFunction(CONST_CONTRACT_FUNCTION_EXEC_RPT); RuleTreeReport ruleTreeReport = null; if (pbValidateWithinTransaction) { var FlagSource = poRulesEngine.SourceMap[ReviewFlagAttr.AttrName]; var CurrValSource = poRulesEngine.SourceMap[CurrValueAttr.AttrName]; var executeGetLastReportFunction = contract.GetFunction(CONST_CONTRACT_FUNCTION_GET_LAST_RPT); WonkaProduct OrchContractCurrValues = poRulesEngine.AssembleCurrentProductFromChainSources(new Dictionary <string, string>(), CONST_ONLINE_TEST_CHAIN_URL); // Before invoking the RuleTree, the storage contract should have Review Flag as "" and CurrVal as "999" string sFlagBeforeOrchestrationAssignment = RetrieveValueMethod(FlagSource, ReviewFlagAttr.AttrName); string sValueBeforeOrchestrationAssignment = RetrieveValueMethod(CurrValSource, CurrValueAttr.AttrName); var EthRuleTreeReport = new Wonka.Eth.Extensions.RuleTreeReport(); poRulesEngine.ExecuteOnChain(moEthEngineInit, EthRuleTreeReport); // After invoking the RuleTree, the storage contract should have Review Flag as "???" and CurrVal as "1014" string sFlagAfterOrchestrationAssignment = RetrieveValueMethod(FlagSource, ReviewFlagAttr.AttrName); string sValueAfterOrchestrationAssignment = RetrieveValueMethod(CurrValSource, CurrValueAttr.AttrName); ruleTreeReport = executeGetLastReportFunction.CallDeserializingToObjectAsync <RuleTreeReport>().Result; } else { ruleTreeReport = executeWithReportFunction.CallDeserializingToObjectAsync <RuleTreeReport>(senderAddress).Result; } return(ruleTreeReport); }
public BasicWonkaTests() { var metadataSource = new Wonka.BizRulesEngine.Samples.WonkaBreMetadataTestSource(); _refEnvHandle = WonkaRefEnvironment.CreateInstance(false, metadataSource); using (var client = new System.Net.Http.HttpClient()) { var sIpfsUrl = String.Format("{0}/{1}", CONST_INFURA_IPFS_GATEWAY_URL, "QmXcsGDQthxbGW8C3Sx9r4tV9PGSj4MxJmtXF7dnXN5XUT"); var sRulesContents = client.GetStringAsync(sIpfsUrl).Result; _rulesEngine = new WonkaBizRulesEngine(new StringBuilder(sRulesContents), metadataSource); } _client = new Mock <IOrchestrate>(); }
public async Task <RuleTreeReport> ExecuteWithReportAsync(WonkaBizRulesEngine poRulesEngine, bool pbValidateWithinTransaction) { WonkaRefEnvironment RefEnv = WonkaRefEnvironment.GetInstance(); WonkaRefAttr CurrValueAttr = RefEnv.GetAttributeByAttrName("AccountCurrValue"); WonkaRefAttr ReviewFlagAttr = RefEnv.GetAttributeByAttrName("AuditReviewFlag"); var contract = GetContract(); var senderAddress = moEthEngineInit.EthSenderAddress; var executeWithReportFunction = contract.GetFunction(CONST_CONTRACT_FUNCTION_EXEC_RPT); RuleTreeReport ruleTreeReport = null; if (pbValidateWithinTransaction) { var FlagSource = poRulesEngine.SourceMap[ReviewFlagAttr.AttrName]; var CurrValSource = poRulesEngine.SourceMap[CurrValueAttr.AttrName]; var executeGetLastReportFunction = contract.GetFunction(CONST_CONTRACT_FUNCTION_GET_LAST_RPT); // Before invoking the RuleTree, the storage contract should have Review Flag as "" and CurrVal as "999" string sFlagBeforeOrchestrationAssignment = await RetrieveValueMethodAsync(FlagSource, ReviewFlagAttr.AttrName).ConfigureAwait(false); string sValueBeforeOrchestrationAssignment = await RetrieveValueMethodAsync(CurrValSource, CurrValueAttr.AttrName).ConfigureAwait(false); var EthRuleTreeReport = new Wonka.Eth.Extensions.RuleTreeReport(); await poRulesEngine.ExecuteOnChainAsync(moEthEngineInit, EthRuleTreeReport).ConfigureAwait(false); // After invoking the RuleTree, the storage contract should have Review Flag as "???" and CurrVal as "1014" string sFlagAfterOrchestrationAssignment = await RetrieveValueMethodAsync(FlagSource, ReviewFlagAttr.AttrName).ConfigureAwait(false); string sValueAfterOrchestrationAssignment = await RetrieveValueMethodAsync(CurrValSource, CurrValueAttr.AttrName).ConfigureAwait(false); ruleTreeReport = await executeGetLastReportFunction.CallDeserializingToObjectAsync <RuleTreeReport>().ConfigureAwait(false); } else { ruleTreeReport = await executeWithReportFunction.CallDeserializingToObjectAsync <RuleTreeReport>(senderAddress).ConfigureAwait(false); } return(ruleTreeReport); }
private static string GetCurrentBlockNum(WonkaBizRulesEngine poEngine, string psUnusedVal) { string sCurrBlockNum = string.Empty; if (EngineWeb3Accounts.ContainsKey(poEngine)) { Nethereum.Web3.Web3 EngineWeb3 = EngineWeb3Accounts[poEngine]; sCurrBlockNum = EngineWeb3.Eth.Blocks.GetBlockNumber.SendRequestAsync().Result.HexValue.ToString(); } if (sCurrBlockNum.HasHexPrefix()) { sCurrBlockNum = sCurrBlockNum.RemoveHexPrefix(); } return(sCurrBlockNum); }
public RuleTreeReport ExecuteWithReport(WonkaBizRulesEngine poRulesEngine, bool pbValidateWithinTransaction, WonkaBizSource poFlagSource) { WonkaRefEnvironment RefEnv = WonkaRefEnvironment.GetInstance(); WonkaRefAttr CurrValueAttr = RefEnv.GetAttributeByAttrName("AccountCurrValue"); WonkaRefAttr ReviewFlagAttr = RefEnv.GetAttributeByAttrName("AuditReviewFlag"); Dictionary <string, string> PrdKeys = new Dictionary <string, string>(); var contract = GetContract(); var executeWithReportFunction = contract.GetFunction(CONST_CONTRACT_FUNCTION_EXEC_RPT); RuleTreeReport ruleTreeReport = null; if (pbValidateWithinTransaction) { var executeGetLastReportFunction = contract.GetFunction(CONST_CONTRACT_FUNCTION_GET_LAST_RPT); // NOTE: Caused exception to be thrown // var gas = executeWithReportFunction.EstimateGasAsync(msSenderAddress).Result; var gas = new Nethereum.Hex.HexTypes.HexBigInteger(1000000); WonkaProduct OrchContractCurrValues = poRulesEngine.AssembleCurrentProduct(new Dictionary <string, string>()); string sFlagBeforeOrchestrationAssignment = RetrieveValueMethod(poFlagSource, ReviewFlagAttr.AttrName); string sValueBeforeOrchestrationAssignment = RetrieveValueMethod(poFlagSource, CurrValueAttr.AttrName); var receiptAddAttribute = executeWithReportFunction.SendTransactionAsync(msSenderAddress, gas, null, msSenderAddress).Result; string sFlagAfterOrchestrationAssignment = RetrieveValueMethod(poFlagSource, ReviewFlagAttr.AttrName); string sValueAfterOrchestrationAssignment = RetrieveValueMethod(poFlagSource, CurrValueAttr.AttrName); ruleTreeReport = executeGetLastReportFunction.CallDeserializingToObjectAsync <RuleTreeReport>().Result; } else { ruleTreeReport = executeWithReportFunction.CallDeserializingToObjectAsync <RuleTreeReport>(msSenderAddress).Result; } return(ruleTreeReport); }
/// <summary> /// /// This method will break apart a current RuleTree encapsulated within an instance of WonkaBizRulesEngine, taking each top level branch /// and using it to create a new RuleTree. These multiple instances of RuleTree will then form a new Grove. /// /// NOTE: UNDER CONSTRUCTION /// /// <param name="poRuleTree">The RuleTree that we are looking to turn into a Grove</param> /// <returns>The Grove that will hold the RuleTrees created from its parent</returns> /// </summary> public static WonkaBizGrove Splinter(this WonkaBizRulesEngine poRuleTree, int pnGroveId, string psGroveDesc) { WonkaBizGrove SpawnedGrove = new WonkaBizGrove(pnGroveId, psGroveDesc); if (poRuleTree.RuleTreeRoot == null) { throw new WonkaEthException("ERROR! Splinter() cannot be invoked when there is no root of the supplied RuleTree."); } if (poRuleTree.RuleTreeRoot.ChildRuleSets.Count <= 0) { throw new WonkaEthException("ERROR! Splinter() cannot be invoked when the root of the supplied RuleTree has no children."); } foreach (WonkaBizRuleSet TopChildRuleset in poRuleTree.RuleTreeRoot.ChildRuleSets) { SpawnedGrove.AddRuleTree(new WonkaBizRulesEngine(TopChildRuleset, poRuleTree)); } return(SpawnedGrove); }
public static uint CalculateMaxGasEstimate(this WonkaBizRulesEngine poRulesEngine, uint pnWriteOpGasCost = CONST_GAS_PER_WRITE_OP) { uint nMaxGasCost = 50000; if ((poRulesEngine != null) && (poRulesEngine.RuleTreeRoot != null)) { // NOTE: Do work here // 63200 gas per op, based on gas default price // 12 ops for Validate, 18 ops Calculate if (poRulesEngine.RuleTreeRoot.ChildRuleSets != null) { poRulesEngine.RuleTreeRoot.ChildRuleSets.ForEach(x => nMaxGasCost += (uint)(x.EvaluativeRules.Count * CONST_GAS_PER_READ_OP)); poRulesEngine.RuleTreeRoot.ChildRuleSets.ForEach(x => nMaxGasCost += (uint)(x.AssertiveRules.Count * pnWriteOpGasCost)); } if (poRulesEngine.AllRuleSets != null) { poRulesEngine.AllRuleSets.ForEach(x => nMaxGasCost += (uint)(x.EvaluativeRules.Count * CONST_GAS_PER_READ_OP)); foreach (WonkaBizRuleSet TempRuleSet in poRulesEngine.AllRuleSets) { foreach (WonkaBizRule TempRule in TempRuleSet.AssertiveRules) { if (TempRule.RuleType == RULE_TYPE.RT_CUSTOM_OP) { nMaxGasCost += (uint)(3 * pnWriteOpGasCost); } else { nMaxGasCost += (uint)(pnWriteOpGasCost); } } } } } return(nMaxGasCost); }
private void WonkaRibbon_Load(object sender, RibbonUIEventArgs e) { refEnvHandle = WonkaRefEnvironment.CreateInstance(false, metadataSource); WonkaRefAttr AccountIDAttr = refEnvHandle.GetAttributeByAttrName("BankAccountID"); WonkaRefAttr AccountNameAttr = refEnvHandle.GetAttributeByAttrName("BankAccountName"); WonkaRefAttr AccountStsAttr = refEnvHandle.GetAttributeByAttrName("AccountStatus"); WonkaRefAttr AccountCurrValAttr = refEnvHandle.GetAttributeByAttrName("AccountCurrValue"); WonkaRefAttr AccountTypeAttr = refEnvHandle.GetAttributeByAttrName("AccountType"); WonkaRefAttr AccountCurrencyAttr = refEnvHandle.GetAttributeByAttrName("AccountCurrency"); WonkaRefAttr RvwFlagAttr = refEnvHandle.GetAttributeByAttrName("AuditReviewFlag"); WonkaRefAttr CreationDtAttr = refEnvHandle.GetAttributeByAttrName("CreationDt"); using (var client = new System.Net.Http.HttpClient()) { wonkaRules = client.GetStringAsync(currRulesUrl).Result; } rulesEngine = new WonkaBizRulesEngine(new StringBuilder(wonkaRules)); }
/// <summary> /// /// This method will register the default set of standard operations (especially Nethereum-related ones) that can be /// invoked from within the Wonka rules engine /// /// <param name="poEngine">The target instance of an engine</param> /// <returns>None</returns> /// </summary> public static void SetDefaultStdOps(this WonkaBizRulesEngine poEngine, string psPassword, string psWeb3HttpUrl = null) { var account = new Account(psPassword); Nethereum.Web3.Web3 web3 = null; if (!String.IsNullOrEmpty(psWeb3HttpUrl)) { web3 = new Nethereum.Web3.Web3(account, psWeb3HttpUrl); } else { web3 = new Nethereum.Web3.Web3(account); } EngineWeb3Accounts[poEngine] = web3; Dictionary <STD_OP_TYPE, WonkaBizRulesEngine.RetrieveStdOpValDelegate> DefaultStdOpMap = new Dictionary <STD_OP_TYPE, WonkaBizRulesEngine.RetrieveStdOpValDelegate>(); DefaultStdOpMap[STD_OP_TYPE.STD_OP_BLOCK_NUM] = GetCurrentBlockNum; poEngine.StdOpMap = DefaultStdOpMap; }
/// <summary> /// /// After running an instance of the Wonka engine, this method will: /// /// 1.) Persist all data to files (metadata, rules, current data, report), zip the files, and then upload the .ZIP to IPFS /// 2.) Create the hash of the Zip file /// 3.) Create an entry on the ChronoLog contract (including the IPFS URL and hash of the Zip file) /// /// <param name="poEngine">The instance of the Wonka engine that has just run a RuleTree</param> /// <param name="poEngineInitProps">Various properties of this instance of the Wonka engine</param> /// <param name="poRecord">This record holds the current snapshot of the data being addressed by the metadata (mentioned in WonkaRefEnvironment)</param> /// <param name="poReport">This report holds the verbose results of running the RuleTree</param> /// <param name="psIpfsUrl">This URL points to the IPFS node that acts as the read-only gateway</param> /// <param name="psWriteIpfsUrl">This URL points to the IPFS node that will be used to upload the Zip file of the results</param> /// <param name="psChronoLogContractAddr">This address points to an instance of the ChronoLog contract</param> /// <returns>Unique name for entry in the ChronoLog contract</returns> /// </summary> public static async Task <string> StoreWonkaResultsAsync(this WonkaBizRulesEngine poEngine, Wonka.Eth.Init.WonkaEthEngineInitialization poEngineInitProps, WonkaProduct poRecord, Wonka.Eth.Extensions.RuleTreeReport poReport, string psIpfsUrl, string psWriteIpfsUrl, string psChronoLogContractAddr) { var RefEnv = WonkaRefEnvironment.GetInstance(); var signer = new EthereumMessageSigner(); var prodMsgXml = new WonkaProductMsgWriter().WriteWonkaMsg(new WonkaProductMessage(poRecord, true)); var inputSignature = signer.EncodeUTF8AndSign(prodMsgXml, new EthECKey(poEngineInitProps.EthPassword)); string sUniqueChronoLogName = "WI-" + DateTime.Now.ToUniversalTime().ToEpochTime(); string sZipIpfsUrl = await poEngine.UploadInvocationAsync(poEngineInitProps, poRecord, poReport, psIpfsUrl, psWriteIpfsUrl, sUniqueChronoLogName).ConfigureAwait(false); var addChronoLogEventFunction = new Wonka.Eth.Autogen.ChronoLog.AddChronoLogEventFunction() { UniqueName = sUniqueChronoLogName, EType = "WONKA_INVOKE", Desc = "", // Empty for now Data = "", // Empty for now Hash = inputSignature, Url = sZipIpfsUrl }; string sTrxHash = await poReport.WriteToChronoLog(poEngineInitProps, psChronoLogContractAddr, addChronoLogEventFunction).ConfigureAwait(false); return(sUniqueChronoLogName); }
/// <summary> /// /// This method will assemble the new product by iterating through each specified source /// and retrieving the data directly from the third-party storage contract on the chain. /// /// <param name="poEngine">The Wonka.NET instance that represents the instance on the chain</param> /// <param name="poKeyValues">The keys for the product whose data we wish to extract (though not yet used)</param> /// <param name="psWeb3Url">The URL for the Ethereum client to which we want to connect</param> /// <returns>Contains the assembled product data that represents the current product</returns> /// </summary> public static WonkaProduct AssembleCurrentProductFromChainSources(this WonkaBizRulesEngine poEngine, Dictionary <string, string> poKeyValues, string psWeb3Url = "") { WonkaProduct CurrentProduct = new WonkaProduct(); if ((poKeyValues != null) && (poKeyValues.Count > 0)) { // NOTE: To be determined } if (poEngine.SourceMap != null) { foreach (string sTmpAttrName in poEngine.SourceMap.Keys) { WonkaBizSource TmpSource = poEngine.SourceMap[sTmpAttrName]; WonkaRefAttr TargetAttr = poEngine.RefEnvHandle.GetAttributeByAttrName(sTmpAttrName); string sTmpValue = TmpSource.GetAttrValueFromChain(sTmpAttrName, psWeb3Url); CurrentProduct.SetAttribute(TargetAttr, sTmpValue); } } return(CurrentProduct); }
public void Execute() { // Using the metadata source, we create an instance of a defined data domain WonkaRefEnvironment RefEnv = WonkaRefEnvironment.CreateInstance(false, moMetadataSource); // To test whether the data domain has been created, we pull back one attribute WonkaRefAttr AccountStsAttr = RefEnv.GetAttributeByAttrName("AccountStatus"); // Creating an instance of the rules engine using our rules and the metadata WonkaBizRulesEngine RulesEngine = new WonkaBizRulesEngine(new StringBuilder(msRulesContents), moMetadataSource); // Gets a predefined data record that will be our analog for new data coming into the system WonkaProduct NewProduct = GetNewProduct(); // Check that the data has been populated correctly on the "new" record string sStatusValueBefore = GetAttributeValue(NewProduct, AccountStsAttr); // Since the rules can reference values from different records (like O.Price for the existing // record's price and N.Price for the new record's price), we need to provide the delegate // that can pull the existing (i.e., old) record using a key RulesEngine.GetCurrentProductDelegate = GetOldProduct; // Validate the new record using our rules engine and its initialized RuleTree Wonka.BizRulesEngine.Reporting.WonkaBizRuleTreeReport Report = RulesEngine.Validate(NewProduct); // Now retrieve the AccountStatus value and see if the rules have altered it (which should // not be the case) string sStatusValueAfter = GetAttributeValue(NewProduct, AccountStsAttr); if (Report.GetRuleSetFailureCount() > 0) { throw new Exception("Oh heavens to Betsy! Something bad happened!"); } }
/// <summary> /// /// This method will assemble the new product by iterating through each specified source /// and retrieving the data directly from the third-party storage contract on the chain. /// /// <param name="poEngine">The Wonka.NET instance that represents the instance on the chain</param> /// <param name="poKeyValues">The keys for the product whose data we wish to extract (though not yet used)</param> /// <param name="psWeb3Url">The URL for the Ethereum client to which we want to connect</param> /// <returns>Contains the assembled product data that represents the current product</returns> /// </summary> public static async Task <WonkaProduct> AssembleCurrentProductFromChainSourcesAsync(this WonkaBizRulesEngine poEngine, Dictionary <string, string> poKeyValues, string psWeb3Url = "") { WonkaProduct CurrentProduct = new WonkaProduct(); if ((poKeyValues != null) && (poKeyValues.Count > 0)) { // NOTE: To be determined } bool bSuccess = await CurrentProduct.PopulateWithDataFromChainAsync(poEngine.RefEnvHandle, poEngine.SourceMap, psWeb3Url).ConfigureAwait(false); return(CurrentProduct); }
/// <summary> /// /// This method will return an Attribute value using. /// /// NOTE: UNDER CONSTRUCTION /// /// <param name="poEngine">The Wonka.NET instance that represents the instance on the chain</param> /// <param name="poEngineSource">The address that represents the instance on the chain</param> /// <param name="pnEpochTimeToStartFrom">The time of the reports from which we want to start pulling reports</param> /// <param name="psWeb3Url">The URL for the Ethereum client to which we want to connect</param> /// <returns>Contains the array of rule reports</returns> /// </summary> public static async Task <List <Wonka.Eth.Extensions.RuleTreeReport> > GetRuleTreeReportsFromChainStorageAsync(this WonkaBizRulesEngine poEngine, Wonka.Eth.Init.WonkaEthSource poEngineSource, long pnEpochTimeToStartFrom = 0, string psWeb3Url = "") { var RuleTreeReports = new List <Wonka.Eth.Extensions.RuleTreeReport>(); // NOTE: Do work here return(RuleTreeReports); }
public WonkaBizRulesXmlReader(string psBreXmlFilepath, IMetadataRetrievable piMetadataSource = null, WonkaBizRulesEngine poRulesHostEngine = null) { if (string.IsNullOrEmpty(psBreXmlFilepath)) { throw new WonkaBizRuleException(-1, -1, "ERROR! The rules file provided is null."); } if (!File.Exists(psBreXmlFilepath)) { throw new WonkaBizRuleException(-1, -1, "ERROR! The rules file(" + psBreXmlFilepath + ") does not exist."); } this.BreXmlFilepath = psBreXmlFilepath; this.BreXmlContents = null; this.RulesHostEngine = poRulesHostEngine; this.Init(piMetadataSource); }
public WonkaBizRulesXmlReader(StringBuilder psBreXml, IMetadataRetrievable piMetadataSource = null, WonkaBizRulesEngine poRulesHostEngine = null) { if ((psBreXml == null) || (psBreXml.Length <= 0)) { throw new WonkaBizRuleException(-1, -1, "ERROR! The rules file provided is null."); } this.BreXmlFilepath = null; this.BreXmlContents = psBreXml.ToString(); this.RulesHostEngine = poRulesHostEngine; this.Init(piMetadataSource); }