Beispiel #1
0
        protected void RegisterClientSideBaseValidationScripts()
        {
            var template =
                new ScriptTemplate(this, "ClearCanvas.ImageServer.Web.Common.WebControls.Validators.BaseValidator.js");

            template.Replace("@@CLIENTID@@", ClientID);
            template.Replace("@@INPUT_CLIENTID@@", InputControl.ClientID);
            template.Replace("@@INPUT_NORMAL_BKCOLOR@@", ColorTranslator.ToHtml(InputNormalColor));
            template.Replace("@@INPUT_INVALID_BKCOLOR@@", ColorTranslator.ToHtml(InvalidInputColor));
            template.Replace("@@INPUT_NORMAL_BORDERCOLOR@@", ColorTranslator.ToHtml(InputNormalBorderColor));
            template.Replace("@@INPUT_INVALID_BORDERCOLOR@@", ColorTranslator.ToHtml(InvalidInputBorderColor));
            template.Replace("@@INPUT_NORMAL_CSS@@", InputNormalCSS);
            template.Replace("@@INPUT_INVALID_CSS@@", InvalidInputCSS);
            template.Replace("@@CLIENT_EVALUATION_CLASS@@", ClientSideOnValidateFunctionName);
            template.Replace("@@IGNORE_EMPTY_VALUE@@", IgnoreEmptyValue ? "true" : "false");

            Page.ClientScript.RegisterClientScriptBlock(GetType(), "BaseValidationScripts", template.Script, true);

            template =
                new ScriptTemplate(this,
                                   "ClearCanvas.ImageServer.Web.Common.WebControls.Validators.BaseValidator_OnClientValidation.js");

            Page.ClientScript.RegisterClientScriptBlock(GetType(), ClientSideOnValidateFunctionName, template.Script,
                                                        true);
        }
Beispiel #2
0
        public static void LoadAll()
        {
            if (File.Exists(Environment.TemplatesFolderPath + "cs.template"))
            {
                CSharp = new ScriptTemplate()
                {
                    Content    = File.ReadAllText(Environment.TemplatesFolderPath + "cs.template"),
                    TargetType = FileType.CSharp
                };
            }
            else
            {
                MessageBox.Show("Could not find file template, empty file will be created");
            }

            if (File.Exists(Environment.TemplatesFolderPath + "py.template"))
            {
                IronPython = new ScriptTemplate()
                {
                    Content    = File.ReadAllText(Environment.TemplatesFolderPath + "py.template"),
                    TargetType = FileType.IronPython
                };
            }
            else
            {
                MessageBox.Show("Could not find file template, empty file will be created");
            }
        }
        private string GetMultiSig2Of3Address(string key1, string key2, string key3)
        {
            //BIP32 bip321 = new BIP32(key1);
            //string hexKey1 = HexString.FromByteArray(bip321.eckey.pubKey);

            //BIP32 bip322 = new BIP32(key2);
            //string hexKey2 = HexString.FromByteArray(bip322.eckey.pubKey);

            //BIP32 bip323 = new BIP32(key3);
            //string hexKey3 = HexString.FromByteArray(bip323.eckey.pubKey);

            object[] addr = new object[3];
            addr[0] = key1;
            addr[1] = key2;
            addr[2] = key3;

            //string multsig = MultiSig.MultSigScript(addr);

            Script multScript = ScriptTemplate.MultiSig(addr);

            Address address = new Address(multScript.ToBytes(), Address.SCRIPT);

            byte[] test = multScript.ToBytes();

            return(address.ToString());
        }
 public override void RegisterStandardScriptTemplate(ScriptTemplate scriptTemplate)
 {
     if (!this.standardTemplates.Any(template => (template.Type == scriptTemplate.Type)))
     {
         this.standardTemplates.Add(scriptTemplate);
     }
 }
        /// <inheritdoc cref="IScriptAddressReader.GetAddressFromScriptPubKey"/>
        public string GetAddressFromScriptPubKey(Network network, Script script)
        {
            ScriptTemplate scriptTemplate = network.StandardScriptsRegistry.GetTemplateFromScriptPubKey(script);

            string destinationAddress = null;

            switch (scriptTemplate?.Type)
            {
            // Pay to PubKey can be found in outputs of staking transactions.
            case TxOutType.TX_PUBKEY:
                PubKey pubKey = PayToPubkeyTemplate.Instance.ExtractScriptPubKeyParameters(script);
                destinationAddress = pubKey.GetAddress(network).ToString();
                break;

            // Pay to PubKey hash is the regular, most common type of output.
            case TxOutType.TX_PUBKEYHASH:
                destinationAddress = script.GetDestinationAddress(network).ToString();
                break;

            case TxOutType.TX_SCRIPTHASH:
                destinationAddress = script.GetDestinationAddress(network).ToString();
                break;

            case TxOutType.TX_SEGWIT:
                destinationAddress = script.GetDestinationAddress(network).ToString();
                break;

            case TxOutType.TX_NONSTANDARD:
            case TxOutType.TX_MULTISIG:
            case TxOutType.TX_NULL_DATA:
                break;
            }

            return(destinationAddress);
        }
        /// <summary>
        /// Whether transaction inputs are standard.
        /// Check for standard transaction types.
        /// </summary>
        /// <param name="tx">Transaction to verify.</param>
        /// <param name="mapInputs">Map of previous transactions that have outputs we're spending.</param>
        /// <returns>Whether all inputs (scriptSigs) use only standard transaction forms.</returns>
        private bool AreInputsStandard(Network network, Transaction tx, MempoolCoinView mapInputs)
        {
            if (tx.IsCoinBase)
            {
                this.logger.LogTrace("(-)[IS_COINBASE]:true");
                return(true); // Coinbases don't use vin normally
            }

            foreach (TxIn txin in tx.Inputs)
            {
                TxOut          prev     = mapInputs.GetOutputFor(txin);
                ScriptTemplate template = network.StandardScriptsRegistry.GetTemplateFromScriptPubKey(prev.ScriptPubKey);
                if (template == null)
                {
                    this.logger.LogTrace("(-)[BAD_SCRIPT_TEMPLATE]:false");
                    return(false);
                }

                if (template.Type == TxOutType.TX_SCRIPTHASH)
                {
                    if (prev.ScriptPubKey.GetSigOpCount(true) > 15) //MAX_P2SH_SIGOPS
                    {
                        this.logger.LogTrace("(-)[SIG_OP_MAX]:false");
                        return(false);
                    }
                }
            }

            return(true);
        }
        public void VerifyThatColdStakeTransactionCanBeFiltered()
        {
            this.Initialize();
            this.CreateMempoolManager();

            this.coldStakingManager.CreateWallet(walletPassword, walletName1, walletPassphrase, new Mnemonic(walletMnemonic1));

            Wallet.Wallet wallet1 = this.coldStakingManager.GetWalletByName(walletName1);

            Transaction prevTran = this.AddSpendableTransactionToWallet(wallet1);

            IActionResult result = this.coldStakingController.SetupColdStaking(new SetupColdStakingRequest
            {
                HotWalletAddress  = hotWalletAddress1,
                ColdWalletAddress = coldWalletAddress2,
                WalletName        = walletName1,
                WalletAccount     = walletAccount,
                WalletPassword    = walletPassword,
                Amount            = "100",
                Fees = "0.01"
            });

            var jsonResult  = Assert.IsType <JsonResult>(result);
            var response    = Assert.IsType <SetupColdStakingResponse>(jsonResult.Value);
            var transaction = Assert.IsType <PosTransaction>(this.Network.CreateTransaction(response.TransactionHex));

            Assert.Equal("OP_DUP OP_HASH160 OP_ROT OP_IF OP_CHECKCOLDSTAKEVERIFY 90c582cb91d6b6d777c31c891d4943fed4edac3a OP_ELSE 92dfb829d31cefe6a0731f3432dea41596a278d9 OP_ENDIF OP_EQUALVERIFY OP_CHECKSIG", transaction.Outputs[1].ScriptPubKey.ToString());

            // Get the ColdStaking script template if available.
            Dictionary <string, ScriptTemplate> templates = this.coldStakingManager.GetValidStakingTemplates();
            ScriptTemplate coldStakingTemplate            = templates["ColdStaking"];

            Assert.True(coldStakingTemplate.CheckScriptPubKey(transaction.Outputs[1].ScriptPubKey));
        }
Beispiel #8
0
        /// <summary>
        /// A method that returns a script type description.
        /// </summary>
        /// <param name="template">A <see cref="ScriptTemplate"/> used for the script.</param>
        /// <returns>A string describing the script type.</returns>
        protected string GetScriptType(ScriptTemplate template)
        {
            if (template == null)
            {
                return("nonstandard");
            }
            switch (template.Type)
            {
            case TxOutType.TX_PUBKEY:
                return("pubkey");

            case TxOutType.TX_PUBKEYHASH:
                return("pubkeyhash");

            case TxOutType.TX_SCRIPTHASH:
                return("scripthash");

            case TxOutType.TX_MULTISIG:
                return("multisig");

            case TxOutType.TX_NULL_DATA:
                return("nulldata");

            case TxOutType.TX_COLDSTAKE:
                return("coldstaking");
            }

            return("nonstandard");
        }
Beispiel #9
0
    public void LoadScriptTemplateFileTest()
    {
        const string packageName = "io.github.idreamsofgame.resharp.core";
        var          content     = ScriptTemplate.LoadScriptTemplateFile("package", packageName);

        Assert.AreNotEqual(string.Empty, content);
    }
        public static string[] GetAddress(Network network, Script script)
        {
            ScriptTemplate template = NBitcoin.StandardScripts.GetTemplateFromScriptPubKey(script);

            if (template == null)
            {
                return(null);
            }

            if (template.Type == TxOutType.TX_NONSTANDARD)
            {
                return(null);
            }

            if (template.Type == TxOutType.TX_NULL_DATA)
            {
                return(null);
            }

            if (template.Type == TxOutType.TX_PUBKEY)
            {
                PubKey[] pubkeys = script.GetDestinationPublicKeys(network);
                return(new[] { pubkeys[0].GetAddress(network).ToString() });
            }

            if (template.Type == TxOutType.TX_PUBKEYHASH ||
                template.Type == TxOutType.TX_SCRIPTHASH ||
                template.Type == TxOutType.TX_SEGWIT)
            {
                BitcoinAddress bitcoinAddress = script.GetDestinationAddress(network);
                if (bitcoinAddress != null)
                {
                    return(new[] { bitcoinAddress.ToString() });
                }
            }

            if (template.Type == TxOutType.TX_MULTISIG)
            {
                // TODO;
                return(null);
            }

            if (template.Type == TxOutType.TX_COLDSTAKE)
            {
                if (ColdStakingScriptTemplate.Instance.ExtractScriptPubKeyParameters(script, out KeyId hotPubKeyHash, out KeyId coldPubKeyHash))
                {
                    // We want to index based on both the cold and hot key
                    return(new[]
                    {
                        hotPubKeyHash.GetAddress(network).ToString(),
                        coldPubKeyHash.GetAddress(network).ToString(),
                    });
                }

                return(null);
            }

            return(null);
        }
Beispiel #11
0
        protected void RegisterWebServiceInitScripts()
        {
            var template = new ScriptTemplate(GetType().Assembly,
                                              "MatrixPACS.ImageServer.Web.Common.WebControls.Validators.WebServiceValidator_Init.js");

            template.Replace("@@WEBSERVICE_URL@@", ServiceURL);
            Page.ClientScript.RegisterStartupScript(GetType(), "WebServiceInit", template.Script, true);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="method"></param>
        /// <param name="useTraditionalParameterForm"> </param>
        /// <returns></returns>
        public String CreateMethodCode(AjaxMethodItem method, Boolean useTraditionalParameterForm)
        {
            ScriptTemplate.Mode = this.ModeType;
            var script = new StringBuilder();

            ScriptTemplate.CreateMethodBody(ref script, AjaxClassItem.ClassName, method.AjaxMethod.Name, method, method.Parameters, AjaxClassItem, useTraditionalParameterForm);

            return(script.ToString());
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public StringBuilder CreateClassCode()
        {
            ScriptTemplate.Mode = this.ModeType;
            StringBuilder result = ScriptTemplate.Init(AjaxClassItem.AjaxClass.RootNameSpace);

            ScriptTemplate.AppendClass(ref result, AjaxClassItem.ClassName);

            return(result);
        }
Beispiel #14
0
        internal IEnumerable <Script> GetDestinations(Script redeemScript)
        {
            ScriptTemplate scriptTemplate = this.network.StandardScriptsRegistry.GetTemplateFromScriptPubKey(redeemScript);

            if (scriptTemplate != null)
            {
                // We need scripts suitable for matching to HDAddress.ScriptPubKey.
                switch (scriptTemplate.Type)
                {
                case TxOutType.TX_PUBKEYHASH:
                    yield return(redeemScript);

                    break;

                case TxOutType.TX_PUBKEY:
                    yield return(PayToPubkeyTemplate.Instance.ExtractScriptPubKeyParameters(redeemScript).Hash.ScriptPubKey);

                    break;

                case TxOutType.TX_SCRIPTHASH:
                    yield return(PayToScriptHashTemplate.Instance.ExtractScriptPubKeyParameters(redeemScript).ScriptPubKey);

                    break;

                case TxOutType.TX_SEGWIT:
                    TxDestination txDestination = PayToWitTemplate.Instance.ExtractScriptPubKeyParameters(this.network, redeemScript);
                    if (txDestination != null)
                    {
                        yield return(new KeyId(txDestination.ToBytes()).ScriptPubKey);
                    }
                    break;

                default:
                    if (this.scriptAddressReader is ScriptDestinationReader scriptDestinationReader)
                    {
                        foreach (TxDestination destination in scriptDestinationReader.GetDestinationFromScriptPubKey(this.network, redeemScript))
                        {
                            yield return(destination.ScriptPubKey);
                        }
                    }
                    else
                    {
                        string        address     = this.scriptAddressReader.GetAddressFromScriptPubKey(this.network, redeemScript);
                        TxDestination destination = ScriptDestinationReader.GetDestinationForAddress(address, this.network);
                        if (destination != null)
                        {
                            yield return(destination.ScriptPubKey);
                        }
                    }

                    break;
                }
            }
        }
Beispiel #15
0
        protected override void RegisterClientSideValidationExtensionScripts()
        {
            var template = new ScriptTemplate(this,
                                              "MatrixPACS.ImageServer.Web.Common.WebControls.Validators.WebServiceValidator.js");

            template.Replace("@@WEBSERVICE_OPERATION@@", ServiceOperation);
            template.Replace("@@WEBSERVICE_URL@@", ServiceURL);
            template.Replace("@@PARAMETER_FUNCTION@@", ParamsFunction);

            Page.ClientScript.RegisterClientScriptBlock(GetType(), ClientID + "_ValidatorClass", template.Script, true);
        }
Beispiel #16
0
        protected override void RegisterClientSideValidationExtensionScripts()
        {
            var template =
                new ScriptTemplate(this, "ClearCanvas.ImageServer.Web.Common.WebControls.Validators.DateValidator.js");

            template.Replace("@@CONDITION_CHECKBOX_CLIENTID@@",
                             ConditionalCheckBox != null ? ConditionalCheckBox.ClientID : "null");
            template.Replace("@@VALIDATE_WHEN_UNCHECKED@@", ValidateWhenUnchecked ? "true" : "false");
            template.Replace("@@IGNORE_EMPTY_VALUE@@", IgnoreEmptyValue ? "true" : "false");
            template.Replace("@@DATE_FORMAT@@", InputDateParser.DateFormat);
            Page.ClientScript.RegisterClientScriptBlock(GetType(), ClientID + "_ValidatorClass", template.Script, true);
        }
Beispiel #17
0
        protected override void RegisterClientSideValidationExtensionScripts()
        {
            var template =
                new ScriptTemplate(this, "ClearCanvas.ImageServer.Web.Common.WebControls.Validators.RangeValidator.js");
            template.Replace("@@CONDITION_CHECKBOX_CLIENTID@@",
                             ConditionalCheckBox != null ? ConditionalCheckBox.ClientID : "null");
            template.Replace("@@VALIDATE_WHEN_UNCHECKED@@", ValidateWhenUnchecked ? "true" : "false");
            template.Replace("@@MIN_VALUE@@", MinValue.ToString());
            template.Replace("@@MAX_VALUE@@", MaxValue.ToString());

            Page.ClientScript.RegisterClientScriptBlock(GetType(), ClientID + "_ValidatorClass", template.Script, true);
        }
Beispiel #18
0
        protected override void RegisterClientSideValidationExtensionScripts()
        {
            var template =
                new ScriptTemplate(this, "MatrixPACS.ImageServer.Web.Common.WebControls.Validators.RangeValidator.js");

            template.Replace("@@CONDITION_CHECKBOX_CLIENTID@@",
                             ConditionalCheckBox != null ? ConditionalCheckBox.ClientID : "null");
            template.Replace("@@VALIDATE_WHEN_UNCHECKED@@", ValidateWhenUnchecked ? "true" : "false");
            template.Replace("@@MIN_VALUE@@", MinValue.ToString());
            template.Replace("@@MAX_VALUE@@", MaxValue.ToString());

            Page.ClientScript.RegisterClientScriptBlock(GetType(), ClientID + "_ValidatorClass", template.Script, true);
        }
        private void DoScript(DatabaseObjectType databaseObjectType, ScriptAction scriptAction)
        {
            DbInterpreter dbInterpreter = DbInterpreterHelper.GetDbInterpreter(this.databaseType, new ConnectionInfo(), new DbInterpreterOption());

            ScriptTemplate scriptTemplate = new ScriptTemplate(dbInterpreter);

            DatabaseObjectDisplayInfo displayInfo = this.GetDisplayInfo();

            displayInfo.IsNew        = true;
            displayInfo.Content      = scriptTemplate.GetTemplateContent(databaseObjectType, scriptAction);
            displayInfo.ScriptAction = scriptAction;

            this.ShowContent(displayInfo);
        }
        protected override void RegisterClientSideValidationExtensionScripts()
        {
            var template =
                new ScriptTemplate(this,
                                   "ClearCanvas.ImageServer.Web.Common.WebControls.Validators.RegularExpressionValidator.js");
            template.Replace("@@REGULAR_EXPRESSION@@", ValidationExpression.Replace("\\", "\\\\").Replace("'", "\\'"));
            template.Replace("@@CONDITION_CHECKBOX_CLIENTID@@",
                             ConditionalCheckBox != null ? ConditionalCheckBox.ClientID : "null");
            template.Replace("@@VALIDATE_WHEN_UNCHECKED@@", ValidateWhenUnchecked ? "true" : "false");
            template.Replace("@@IGNORE_EMPTY_VALUE@@", IgnoreEmptyValue ? "true" : "false");


            Page.ClientScript.RegisterClientScriptBlock(GetType(), ClientID + "_ValidatorClass", template.Script, true);
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public String CreateFullCode(Boolean useTraditionalParameterForm)
        {
            var result = "";

            ScriptTemplate.Mode = this.ModeType;
            var script = ScriptTemplate.Init(AjaxClassItem.AjaxClass.RootNameSpace);

            ScriptTemplate.AppendClass(ref script, AjaxClassItem.ClassName);
            foreach (AjaxMethodItem method in AjaxClassItem.AjaxMethodItemCollection.Select(methodHash => methodHash.Value))
            {
                ScriptTemplate.CreateMethodBody(ref script, AjaxClassItem.ClassName, method.AjaxMethod.Name, method, method.Parameters, AjaxClassItem, useTraditionalParameterForm);
            }
            result = script.ToString();
            return(result);
        }
        protected override void RegisterClientSideValidationExtensionScripts()
        {
            var template =
                new ScriptTemplate(this,
                                   "Macro.ImageServer.Web.Common.WebControls.Validators.RegularExpressionValidator.js");

            template.Replace("@@REGULAR_EXPRESSION@@", ValidationExpression.Replace("\\", "\\\\").Replace("'", "\\'"));
            template.Replace("@@CONDITION_CHECKBOX_CLIENTID@@",
                             ConditionalCheckBox != null ? ConditionalCheckBox.ClientID : "null");
            template.Replace("@@VALIDATE_WHEN_UNCHECKED@@", ValidateWhenUnchecked ? "true" : "false");
            template.Replace("@@IGNORE_EMPTY_VALUE@@", IgnoreEmptyValue ? "true" : "false");


            Page.ClientScript.RegisterClientScriptBlock(GetType(), ClientID + "_ValidatorClass", template.Script, true);
        }
        protected override void RegisterClientSideValidationExtensionScripts()
        {
            RegisterClientSideBaseValidationScripts();

            var template =
                new ScriptTemplate(this,
                                   "MatrixPACS.ImageServer.Web.Common.WebControls.Validators.ConditionalRequiredFieldValidator.js");

            template.Replace("@@CONDITION_CHECKBOX_CLIENTID@@",
                             ConditionalCheckBox != null ? ConditionalCheckBox.ClientID : "null");
            template.Replace("@@VALIDATE_WHEN_UNCHECKED@@", ValidateWhenUnchecked ? "true" : "false");
            template.Replace("@@IGNORE_EMPTY_VALUE@@", IgnoreEmptyValue ? "true" : "false");

            Page.ClientScript.RegisterClientScriptBlock(GetType(), ClientID + "_ValidatorClass", template.Script, true);
        }
        protected virtual void CheckPubKey(Transaction transaction, List <TransactionPolicyError> errors)
        {
            if (this.CheckScriptPubKey)
            {
                foreach (Coin txout in transaction.Outputs.AsCoins())
                {
                    ScriptTemplate template = this.Network.StandardScriptsRegistry.GetTemplateFromScriptPubKey(txout.ScriptPubKey);

                    if (template == null)
                    {
                        errors.Add(new OutputPolicyError("Non-Standard scriptPubKey", (int)txout.Outpoint.N));
                    }
                }
            }
        }
        protected override void CheckPubKey(Transaction transaction, List <TransactionPolicyError> errors)
        {
            if (this.CheckScriptPubKey)
            {
                foreach (Coin txout in transaction.Outputs.AsCoins())
                {
                    ScriptTemplate template = StandardScripts.GetTemplateFromScriptPubKey(txout.ScriptPubKey);

                    if (template == null && !txout.ScriptPubKey.IsSmartContractExec())
                    {
                        errors.Add(new OutputPolicyError("Non-Standard scriptPubKey", (int)txout.Outpoint.N));
                    }
                }
            }
        }
        private void RegisterClientSideScripts()
        {
            ScriptTemplate template = new ScriptTemplate(typeof(AddFilesystemDialog).Assembly, "Macro.ImageServer.Web.Application.Pages.Admin.Configure.FileSystems.Filesystem.js");

            template.Replace("@@HW_PERCENTAGE_INPUT_CLIENTID@@", HighWatermarkTextBox.ClientID);
            template.Replace("@@HW_SIZE_CLIENTID@@", HighWatermarkSize.ClientID);
            template.Replace("@@LW_PERCENTAGE_INPUT_CLIENTID@@", LowWatermarkTextBox.ClientID);
            template.Replace("@@LW_SIZE_CLIENTID@@", LowWaterMarkSize.ClientID);
            template.Replace("@@PATH_INPUT_CLIENTID@@", PathTextBox.ClientID);
            template.Replace("@@TOTAL_SIZE_INDICATOR_CLIENTID@@", TotalSizeIndicator.ClientID);
            template.Replace("@@USED_SIZE_INDICATOR_CLIENTID@@", UsedSizeIndicator.ClientID);
            template.Replace("@@TOTAL_SIZE_CLIENTID@@", TotalSize.ClientID);
            template.Replace("@@USED_SIZE_CLIENTID@@", AvailableSize.ClientID);

            Page.ClientScript.RegisterClientScriptBlock(GetType(), ClientID + "_scripts", template.Script, true);
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            PhoneticNameRowIndicator.ImageUrl = ImageServerConstants.ImageURLs.PhoneticName;
            IdeographyNameIndicator.ImageUrl  = ImageServerConstants.ImageURLs.IdeographyName;
            var script =
                new ScriptTemplate(typeof(PersonNameInputPanel).Assembly,
                                   "Macro.ImageServer.Web.Application.Controls.PersonNameInputPanel.js");

            script.Replace("@@CLIENTID@@", ClientID);
            script.Replace("@@PHONETIC_ROW_CLIENTID@@", PhoneticRow.ClientID);
            script.Replace("@@IDEOGRAPHY_ROW_CLIENTID@@", IdeographicRow.ClientID);


            ShowOtherNameFormatButton.OnClientClick = ClientID + "_ShowOtherNameFormats(); return false;";

            Page.ClientScript.RegisterClientScriptBlock(GetType(), ClientID, script.Script, true);

            PersonGivenNameValidator.IgnoreEmptyValue = !Required;
            PersonLastNameValidator.IgnoreEmptyValue  = !Required;

            //Dynamically set all of the Validation Groups
            PersonTitle.ValidationGroup               = ValidationGroup;
            PersonTitleValidator.ValidationGroup      = ValidationGroup;
            PersonGivenName.ValidationGroup           = ValidationGroup;
            PersonGivenNameValidator.ValidationGroup  = ValidationGroup;
            PersonMiddleName.ValidationGroup          = ValidationGroup;
            PersonMiddleNameValidator.ValidationGroup = ValidationGroup;
            PersonLastName.ValidationGroup            = ValidationGroup;
            PersonLastNameValidator.ValidationGroup   = ValidationGroup;
            PersonSuffix.ValidationGroup              = ValidationGroup;
            PersonSuffixValidator.ValidationGroup     = ValidationGroup;
            PhoneticTitle.ValidationGroup             = ValidationGroup;
            PhoneticGivenName.ValidationGroup         = ValidationGroup;
            PhoneticMiddleName.ValidationGroup        = ValidationGroup;
            PhoneticLastName.ValidationGroup          = ValidationGroup;
            PhoneticSuffix.ValidationGroup            = ValidationGroup;
            IdeographicTitle.ValidationGroup          = ValidationGroup;
            IdeographicGivenName.ValidationGroup      = ValidationGroup;
            IdeographicMiddleName.ValidationGroup     = ValidationGroup;
            IdeographicLastName.ValidationGroup       = ValidationGroup;
            IdeographicSuffix.ValidationGroup         = ValidationGroup;
        }
Beispiel #28
0
        /// <summary>
        /// Takes the classless script written by the user and embeds it in the main script template.
        /// This gives the script access to the engine classes that it will require.
        /// </summary>
        /// <param name="script">The classless script.</param>
        /// <returns>The complete script.</returns>
        private String PrecompileScript(String script)
        {
            StringBuilder usings          = new StringBuilder(4096);
            String        classlessScript = String.Empty;

            script = script ?? String.Empty;

            using (StringReader sr = new StringReader(script))
            {
                // Collect all using statements from the script
                String line = null;
                while ((line = sr.ReadLine()) != null)
                {
                    // Ignore comments and whitespace
                    if (line.StartsWith("//") || line.Trim() == String.Empty)
                    {
                        continue;
                    }

                    if (!line.TrimStart().StartsWith("using "))
                    {
                        break;
                    }

                    // Collect using statement
                    usings.AppendLine(line);
                }

                // The remaining portion of the script will be kept as the actual script
                if (line != null)
                {
                    classlessScript = line + sr.ReadToEnd();
                }
            }

            // Fill in the script template with the collected information
            script = new ScriptTemplate().TransformText().Replace(ScriptManager.ScriptUsingsInsertionIdentifier, usings.ToString());
            script = script.Replace(ScriptManager.ScriptCodeInsertionIdentifier, classlessScript);

            return(script);
        }
        protected override void RegisterClientSideValidationExtensionScripts()
        {
            // Register Javascript for client-side validation
            string comparison = GreaterThan ? ">=" : "<=";
            var    template   =
                new ScriptTemplate(this,
                                   "MatrixPACS.ImageServer.Web.Common.WebControls.Validators.RangeComparisonValidator.js");

            template.Replace("@@COMPARE_INPUT_CLIENTID@@", GetControlRenderID(ControlToCompare));
            template.Replace("@@MIN_VALUE@@", MinValue.ToString());
            template.Replace("@@MAX_VALUE@@", MaxValue.ToString());
            template.Replace("@@COMPARISON_OP@@", comparison);
            template.Replace("@@CONDITION_CHECKBOX_CLIENTID@@",
                             ConditionalCheckBox != null ? ConditionalCheckBox.ClientID : "null");
            template.Replace("@@VALIDATE_WHEN_UNCHECKED@@", ValidateWhenUnchecked ? "true" : "false");
            template.Replace("@@IGNORE_EMPTY_VALUE@@", IgnoreEmptyValue ? "true" : "false");
            template.Replace("@@ERROR_MESSAGE@@", Escape(ErrorMessage));

            Platform.Log(LogLevel.Error, template.Script);

            Page.ClientScript.RegisterClientScriptBlock(GetType(), ClientID + "_ValidatorClass", template.Script, true);
        }
        private static bool GenerateMetadataEntityScript(MetadataAssetSettings settings, string entityScriptName, List <MetadataEntityRawInfo> rawInfoList)
        {
            try
            {
                entityScriptName = entityScriptName.ToTitleCase();
                var scriptTextContent = ScriptTemplate.LoadScriptTemplateFile("NewMetadataEntityScriptTemplate.txt", UnityPackageName);
                scriptTextContent = scriptTextContent.Replace(ScriptTemplate.Placeholders.Namespace, settings.EntityScriptNamespace);
                scriptTextContent = scriptTextContent.Replace(ScriptTemplate.Placeholders.ScriptName, entityScriptName);
                scriptTextContent = scriptTextContent.Replace(ScriptTemplate.Placeholders.EnumInsideOfClass, GenerateEntityScriptEnumString(rawInfoList));
                scriptTextContent = scriptTextContent.Replace(ScriptTemplate.Placeholders.Properties, GenerateEntityScriptPropertiesString(rawInfoList));

                var scriptStorePath = EditorPath.ConvertToAbsolutePath(settings.EntityScriptsStorePath, $"{entityScriptName}.cs");
                var assetPath       = EditorPath.ConvertToAssetPath(scriptStorePath);
                File.WriteAllText(scriptStorePath, scriptTextContent, new UTF8Encoding(true));
                AssetDatabase.ImportAsset(assetPath);
                return(true);
            }
            catch (Exception ex)
            {
                UnityDebug.LogError(ex.ToString());
                return(false);
            }
        }
        /// <summary>
        /// Mark an output as spent, the credit of the output will not be used to calculate the balance.
        /// The output will remain in the wallet for history (and reorg).
        /// </summary>
        /// <param name="transaction">The transaction from which details are added.</param>
        /// <param name="paidToOutputs">A list of payments made out</param>
        /// <param name="spendingTransactionId">The id of the transaction containing the output being spent, if this is a spending transaction.</param>
        /// <param name="spendingTransactionIndex">The index of the output in the transaction being referenced, if this is a spending transaction.</param>
        /// <param name="blockHeight">Height of the block.</param>
        /// <param name="blockHash">Hash of the block.</param>
        /// <param name="block">The block containing the transaction to add.</param>
        private void AddSpendingTransactionToWallet(Transaction transaction, IEnumerable <TxOut> paidToOutputs,
                                                    uint256 spendingTransactionId, int?spendingTransactionIndex, int?blockHeight = null, uint256 blockHash = null, Block block = null)
        {
            Guard.NotNull(transaction, nameof(transaction));
            Guard.NotNull(paidToOutputs, nameof(paidToOutputs));
            Guard.Assert(blockHash == (blockHash ?? block?.GetHash()));

            // Get the transaction being spent.
            TransactionData spentTransaction = this.Wallet.MultiSigAddress.Transactions.SingleOrDefault(t => (t.Id == spendingTransactionId) && (t.Index == spendingTransactionIndex));

            if (spentTransaction == null)
            {
                // Strange, why would it be null?
                this.logger.LogTrace("(-)[TX_NULL]");
                return;
            }

            // If the details of this spending transaction are seen for the first time.
            if (spentTransaction.SpendingDetails == null)
            {
                this.logger.LogTrace("Spending UTXO '{0}-{1}' is new. BlockHeight={2}", spendingTransactionId, spendingTransactionIndex, blockHeight);

                List <PaymentDetails> payments = new List <PaymentDetails>();
                foreach (TxOut paidToOutput in paidToOutputs)
                {
                    // Figure out how to retrieve the destination address.
                    string         destinationAddress = string.Empty;
                    ScriptTemplate scriptTemplate     = paidToOutput.ScriptPubKey.FindTemplate(this.network);
                    switch (scriptTemplate.Type)
                    {
                    // Pay to PubKey can be found in outputs of staking transactions.
                    case TxOutType.TX_PUBKEY:
                        PubKey pubKey = PayToPubkeyTemplate.Instance.ExtractScriptPubKeyParameters(paidToOutput.ScriptPubKey);
                        destinationAddress = pubKey.GetAddress(this.network).ToString();
                        break;

                    // Pay to PubKey hash is the regular, most common type of output.
                    case TxOutType.TX_PUBKEYHASH:
                        destinationAddress = paidToOutput.ScriptPubKey.GetDestinationAddress(this.network).ToString();
                        break;

                    case TxOutType.TX_NONSTANDARD:
                    case TxOutType.TX_SCRIPTHASH:
                        destinationAddress = paidToOutput.ScriptPubKey.GetDestinationAddress(this.network).ToString();
                        break;

                    case TxOutType.TX_MULTISIG:
                    case TxOutType.TX_NULL_DATA:
                    case TxOutType.TX_SEGWIT:
                        break;
                    }

                    payments.Add(new PaymentDetails
                    {
                        DestinationScriptPubKey = paidToOutput.ScriptPubKey,
                        DestinationAddress      = destinationAddress,
                        Amount = paidToOutput.Value
                    });
                }

                SpendingDetails spendingDetails = new SpendingDetails
                {
                    TransactionId = transaction.GetHash(),
                    Payments      = payments,
                    CreationTime  = DateTimeOffset.FromUnixTimeSeconds(block?.Header.Time ?? transaction.Time),
                    BlockHeight   = blockHeight,
                    BlockHash     = blockHash,
                    Hex           = transaction.ToHex(),
                    IsCoinStake   = transaction.IsCoinStake == false ? (bool?)null : true
                };

                spentTransaction.SpendingDetails = spendingDetails;
                spentTransaction.MerkleProof     = null;
            }
            else // If this spending transaction is being confirmed in a block.
            {
                this.logger.LogTrace("Spending transaction ID '{0}' is being confirmed, updating. BlockHeight={1}", spendingTransactionId, blockHeight);

                // Update the block height.
                if (spentTransaction.SpendingDetails.BlockHeight == null && blockHeight != null)
                {
                    spentTransaction.SpendingDetails.BlockHeight = blockHeight;
                    spentTransaction.SpendingDetails.BlockHash   = blockHash;
                }

                // Update the block time to be that of the block in which the transaction is confirmed.
                if (block != null)
                {
                    spentTransaction.SpendingDetails.CreationTime = DateTimeOffset.FromUnixTimeSeconds(block.Header.Time);
                }
            }
        }
 protected void RegisterWebServiceInitScripts()
 {
     var template = new ScriptTemplate(GetType().Assembly,
                                       "ClearCanvas.ImageServer.Web.Common.WebControls.Validators.WebServiceValidator_Init.js");
     template.Replace("@@WEBSERVICE_URL@@", ServiceURL);
     Page.ClientScript.RegisterStartupScript(GetType(), "WebServiceInit", template.Script, true);
 }
Beispiel #33
0
        protected override void RegisterClientSideValidationExtensionScripts()
        {
            // Register Javascript for client-side validation
            string comparison = GreaterThan ? ">=" : "<=";
            Platform.Log(LogLevel.Error, "RegisterClientSideValidationExtensionScripts = {0}", ErrorMessage); 
            var template =
                new ScriptTemplate(this,
                                   "ClearCanvas.ImageServer.Web.Common.WebControls.Validators.RangeComparisonValidator.js");
            template.Replace("@@COMPARE_INPUT_CLIENTID@@", GetControlRenderID(ControlToCompare));
            template.Replace("@@MIN_VALUE@@", MinValue.ToString());
            template.Replace("@@MAX_VALUE@@", MaxValue.ToString());
            template.Replace("@@COMPARISON_OP@@", comparison);
            template.Replace("@@CONDITION_CHECKBOX_CLIENTID@@",
                             ConditionalCheckBox != null ? ConditionalCheckBox.ClientID : "null");
            template.Replace("@@VALIDATE_WHEN_UNCHECKED@@", ValidateWhenUnchecked ? "true" : "false");
            template.Replace("@@IGNORE_EMPTY_VALUE@@", IgnoreEmptyValue ? "true" : "false");
            template.Replace("@@ERROR_MESSAGE@@", ErrorMessage);

            Platform.Log(LogLevel.Error, template.Script);

            Page.ClientScript.RegisterClientScriptBlock(GetType(), ClientID + "_ValidatorClass", template.Script, true);
        }
        protected override void RegisterClientSideValidationExtensionScripts()
        {
            var template = new ScriptTemplate(this,
                                              "ClearCanvas.ImageServer.Web.Common.WebControls.Validators.WebServiceValidator.js");
            template.Replace("@@WEBSERVICE_OPERATION@@", ServiceOperation);
            template.Replace("@@WEBSERVICE_URL@@", ServiceURL);
            template.Replace("@@PARAMETER_FUNCTION@@", ParamsFunction);

            Page.ClientScript.RegisterClientScriptBlock(GetType(), ClientID + "_ValidatorClass", template.Script, true);
        }
Beispiel #35
0
        protected void RegisterClientSideBaseValidationScripts()
        {
            var template =
                new ScriptTemplate(this, "ClearCanvas.ImageServer.Web.Common.WebControls.Validators.BaseValidator.js");
            template.Replace("@@CLIENTID@@", ClientID);
            template.Replace("@@INPUT_CLIENTID@@", InputControl.ClientID);
            template.Replace("@@INPUT_NORMAL_BKCOLOR@@", ColorTranslator.ToHtml(InputNormalColor));
            template.Replace("@@INPUT_INVALID_BKCOLOR@@", ColorTranslator.ToHtml(InvalidInputColor));
            template.Replace("@@INPUT_NORMAL_BORDERCOLOR@@", ColorTranslator.ToHtml(InputNormalBorderColor));
            template.Replace("@@INPUT_INVALID_BORDERCOLOR@@", ColorTranslator.ToHtml(InvalidInputBorderColor));
            template.Replace("@@INPUT_NORMAL_CSS@@", InputNormalCSS);
            template.Replace("@@INPUT_INVALID_CSS@@", InvalidInputCSS);
            template.Replace("@@CLIENT_EVALUATION_CLASS@@", ClientSideOnValidateFunctionName);
            template.Replace("@@IGNORE_EMPTY_VALUE@@", IgnoreEmptyValue ? "true" : "false");

            Page.ClientScript.RegisterClientScriptBlock(GetType(), "BaseValidationScripts", template.Script, true);

            template =
                new ScriptTemplate(this,
                                   "ClearCanvas.ImageServer.Web.Common.WebControls.Validators.BaseValidator_OnClientValidation.js");

            Page.ClientScript.RegisterClientScriptBlock(GetType(), ClientSideOnValidateFunctionName, template.Script,
                                                        true);
        }
        /// <summary>
        /// Whether transaction inputs are standard.
        /// Check for standard transaction types.
        /// </summary>
        /// <seealso>https://github.com/bitcoin/bitcoin/blob/febf3a856bcfb8fef2cb4ddcb8d1e0cab8a22580/src/policy/policy.cpp#L156</seealso>
        /// <param name="tx">Transaction to verify.</param>
        /// <param name="mapInputs">Map of previous transactions that have outputs we're spending.</param>
        /// <returns>Whether all inputs (scriptSigs) use only standard transaction forms.</returns>
        private bool AreInputsStandard(Network network, Transaction tx, MempoolCoinView mapInputs)
        {
            if (tx.IsCoinBase)
            {
                this.logger.LogTrace("(-)[IS_COINBASE]:true");
                return(true); // Coinbases don't use vin normally.
            }

            for (int i = 0; i < tx.Inputs.Count; i++)
            {
                TxIn           txin     = tx.Inputs[i];
                TxOut          prev     = mapInputs.GetOutputFor(txin);
                ScriptTemplate template = network.StandardScriptsRegistry.GetTemplateFromScriptPubKey(prev.ScriptPubKey);
                if (template == null) // i.e. the TX_NONSTANDARD case
                {
                    this.logger.LogTrace("(-)[BAD_SCRIPT_TEMPLATE]:false");
                    return(false);
                }

                /* Check transaction inputs to mitigate two potential denial-of-service attacks:
                 *
                 * 1. scriptSigs with extra data stuffed into them, not consumed by scriptPubKey (or P2SH script)
                 * 2. P2SH scripts with a crazy number of expensive CHECKSIG/CHECKMULTISIG operations
                 *
                 * Why bother? To avoid denial-of-service attacks; an attacker can submit a standard HASH... OP_EQUAL transaction,
                 * which will get accepted into blocks. The redemption script can be anything; an attacker could use a very
                 * expensive-to-check-upon-redemption script like:
                 *   DUP CHECKSIG DROP ... repeated 100 times... OP_1
                 */
                if (template.Type == TxOutType.TX_SCRIPTHASH)
                {
                    // Convert the scriptSig into a stack, so we can inspect the redeemScript.
                    var ctx = new ScriptEvaluationContext(this.network)
                    {
                        ScriptVerify = ScriptVerify.None
                    };

                    if (!ctx.EvalScript(txin.ScriptSig, tx, i)) // TODO: Check the semantics of SigVersion::BASE from original code
                    {
                        return(false);
                    }

                    // TODO: Investigate why IsEmpty is failing to return true when there is nothing on the stack. It is possible that nowhere else in the codebase is using IsEmpty on an IEnumerable
                    if (ctx.Stack.IsEmpty() || ctx.Stack.Count == 0)
                    {
                        return(false);
                    }

                    // Get redeemScript from stack.
                    var redeemScript = new Script(ctx.Stack.Top(-1));

                    // TODO: Move this into a network-specific rule so that it only applies to Strax (the Cirrus validator already allows non-standard transactions)
                    if (redeemScript.GetSigOpCount(true, this.network) > MaxP2SHSigOps)
                    {
                        this.logger.LogTrace("(-)[SIG_OP_MAX]:false");
                        return(false);
                    }
                }
            }

            return(true);
        }
Beispiel #37
0
 private string GetScriptType(ScriptTemplate template)
 {
     if(template == null)
         return "nonstandard";
     switch(template.Type)
     {
         case TxOutType.TX_PUBKEY:
             return "pubkey";
         case TxOutType.TX_PUBKEYHASH:
             return "pubkeyhash";
         case TxOutType.TX_SCRIPTHASH:
             return "scripthash";
         case TxOutType.TX_MULTISIG:
             return "multisig";
         case TxOutType.TX_NULL_DATA:
             return "nulldata";
     }
     return "nonstandard";
 }