public void Execute() { var adminAddress = new Address("399bddF9F7B6d902ea27037B907B2486C9910730"); var adminState = new AdminState(adminAddress, 100); var csv = TableSheetsImporter.ImportSheets()[nameof(RedeemCodeListSheet)]; var action = new AddRedeemCode { redeemCsv = csv, }; var nextState = action.Execute(new ActionContext { Signer = adminAddress, BlockIndex = 0, PreviousStates = new State() .SetState(Addresses.Admin, adminState.Serialize()) .SetState(Addresses.RedeemCode, new RedeemCodeState(new RedeemCodeListSheet()).Serialize()), }); var sheet = new RedeemCodeListSheet(); sheet.Set(csv); var expectedMap = new RedeemCodeState(sheet).Map; var redeemState = nextState.GetRedeemCodeState(); foreach (var(key, reward) in expectedMap) { Assert.Equal(reward.RewardId, redeemState.Map[key].RewardId); } }
public void Execute() { var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 }; var pubKey = new PublicKey( ByteUtil.ParseHex("02ed49dbe0f2c34d9dff8335d6dd9097f7a3ef17dfb5f048382eebc7f451a50aa1") ); var pendingActivation = new PendingActivationState(nonce, pubKey); var action = new CreatePendingActivation(pendingActivation); var adminAddress = new Address("399bddF9F7B6d902ea27037B907B2486C9910730"); var adminState = new AdminState(adminAddress, 100); var state = new State(ImmutableDictionary <Address, IValue> .Empty .Add(AdminState.Address, adminState.Serialize()) ); var actionContext = new ActionContext() { BlockIndex = 1, PreviousStates = state, Signer = adminAddress, }; var nextState = action.Execute(actionContext); Assert.Equal( pendingActivation.Serialize(), nextState.GetState(pendingActivation.address) ); }
public static Block <PolymorphicAction <ActionBase> > MineGenesisBlock( IDictionary <string, string> tableSheets, GoldDistribution[] goldDistributions, PendingActivationState[] pendingActivationStates, AdminState adminState, AuthorizedMinersState authorizedMinersState = null, IImmutableSet <Address> activatedAccounts = null, bool isActivateAdminAddress = false, IEnumerable <string> credits = null, int maximumTransactions = 100, PrivateKey privateKey = null ) { if (!tableSheets.TryGetValue(nameof(GameConfigSheet), out var csv)) { throw new KeyNotFoundException(nameof(GameConfigSheet)); } var gameConfigState = new GameConfigState(csv); var redeemCodeListSheet = new RedeemCodeListSheet(); redeemCodeListSheet.Set(tableSheets[nameof(RedeemCodeListSheet)]); if (privateKey is null) { privateKey = new PrivateKey(); } var ncg = new Currency("NCG", 2, privateKey.ToAddress()); activatedAccounts = activatedAccounts ?? ImmutableHashSet <Address> .Empty; var initialStatesAction = new InitializeStates ( rankingState: new RankingState(), shopState: new ShopState(), tableSheets: (Dictionary <string, string>)tableSheets, gameConfigState: gameConfigState, redeemCodeState: new RedeemCodeState(redeemCodeListSheet), adminAddressState: adminState, activatedAccountsState: new ActivatedAccountsState( isActivateAdminAddress ? activatedAccounts.Add(adminState.AdminAddress) : activatedAccounts), goldCurrencyState: new GoldCurrencyState(ncg), goldDistributions: goldDistributions, pendingActivationStates: pendingActivationStates, authorizedMinersState: authorizedMinersState, creditsState: credits is null ? null : new CreditsState(credits) ); var actions = new PolymorphicAction <ActionBase>[] { initialStatesAction, }; var blockAction = new BlockPolicySource(Log.Logger).GetPolicy(5000000, maximumTransactions).BlockAction; return (BlockChain <PolymorphicAction <ActionBase> > .MakeGenesisBlock( actions, privateKey : privateKey, blockAction : blockAction)); }
public void ExecuteNewTable() { var adminAddress = new Address("399bddF9F7B6d902ea27037B907B2486C9910730"); var adminState = new AdminState(adminAddress, 100); const string tableName = "TestTable"; var initStates = ImmutableDictionary <Address, IValue> .Empty .Add(AdminState.Address, adminState.Serialize()) .Add(Addresses.TableSheet.Derive(tableName), Dictionary.Empty.Add(tableName, "Initial")); var state = new State(initStates, ImmutableDictionary <(Address, Currency), FungibleAssetValue> .Empty); var action = new PatchTableSheet() { TableName = nameof(CostumeStatSheet), TableCsv = "id,costume_id,stat_type,stat\n1,40100000,ATK,100", }; var nextState = action.Execute( new ActionContext() { PreviousStates = state, Signer = adminAddress, } ); Assert.NotNull(nextState.GetSheet <CostumeStatSheet>()); }
public void CheckPermission() { var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 }; var pubKey = new PublicKey( ByteUtil.ParseHex("02ed49dbe0f2c34d9dff8335d6dd9097f7a3ef17dfb5f048382eebc7f451a50aa1") ); var pendingActivation = new PendingActivationState(nonce, pubKey); var action = new CreatePendingActivation(pendingActivation); var adminAddress = new Address("399bddF9F7B6d902ea27037B907B2486C9910730"); var adminState = new AdminState(adminAddress, 100); var state = new State(ImmutableDictionary <Address, IValue> .Empty .Add(AdminState.Address, adminState.Serialize()) ); Assert.Throws <PolicyExpiredException>( () => action.Execute(new ActionContext() { BlockIndex = 101, PreviousStates = state, Signer = adminAddress, }) ); Assert.Throws <PermissionDeniedException>( () => action.Execute(new ActionContext() { BlockIndex = 1, PreviousStates = state, Signer = default,
public void Create( [Option("private-key", new[] { 'p' }, Description = "Hex encoded private key for gensis block")] string privateKeyHex, [Option('g', Description = "/path/to/nekoyume-unity/nekoyume/Assets/AddressableAssets/TableCSV")] string gameConfigDir, [Option('d', Description = "/path/to/nekoyume-unity/nekoyume/Assets/StreamingAssets/GoldDistribution.csv")] string goldDistributedPath, [Option('a', Description = "Number of activation keys to generate")] uint activationKeyCount, [Option("adminStateConfig", Description = "Config path to create AdminState")] string adminStateConfigPath, [Option("activatedAccountsList", Description = "List of accounts to be activated")] string activatedAccountsListPath = null, [Option('m', Description = "Config path to create AuthorizedMinersState")] string authorizedMinerConfigPath = null, [Option('c', Description = "Path of a plain text file containing names for credits.")] string creditsPath = null ) { Dictionary <string, string> tableSheets = Utils.ImportSheets(gameConfigDir); Utils.CreateActivationKey( out List <PendingActivationState> pendingActivationStates, out List <ActivationKey> activationKeys, activationKeyCount); GoldDistribution[] goldDistributions = GoldDistribution .LoadInDescendingEndBlockOrder(goldDistributedPath); AdminState adminState = Utils.GetAdminState(adminStateConfigPath); AuthorizedMinersState authorizedMinersState = null; if (!(authorizedMinerConfigPath is null)) { authorizedMinersState = Utils.GetAuthorizedMinersState(authorizedMinerConfigPath); } var activatedAccounts = activatedAccountsListPath is null ? ImmutableHashSet <Address> .Empty : Utils.GetActivatedAccounts(activatedAccountsListPath); Block <PolymorphicAction <ActionBase> > block = BlockHelper.MineGenesisBlock( tableSheets, goldDistributions, pendingActivationStates.ToArray(), adminState, authorizedMinersState: authorizedMinersState, activatedAccounts: activatedAccounts, isActivateAdminAddress: activationKeyCount != 0, credits: creditsPath is null ? null : File.ReadLines(creditsPath), privateKey: new PrivateKey(ByteUtil.ParseHex(privateKeyHex)) ); ExportBlock(block, "genesis-block"); ExportKeys(activationKeys, "keys.txt"); }
public RenewAdminStateTest() { _adminPrivateKey = new PrivateKey(); _validUntil = new Random().Next(); _adminState = new AdminState(_adminPrivateKey.ToAddress(), _validUntil); _stateDelta = new State(ImmutableDictionary <Address, IValue> .Empty.Add( Addresses.Admin, _adminState.Serialize())); }
public async Task GetState() { Address adminStateAddress = AdminState.Address; var result = await ExecuteQueryAsync($"query {{ state(address: \"{adminStateAddress}\") }}"); var data = (Dictionary <string, object>)result.Data; IValue rawVal = new Codec().Decode(ByteUtil.ParseHex((string)data["state"])); AdminState adminState = new AdminState((Dictionary)rawVal); Assert.Equal(AdminAddress, adminState.AdminAddress); }
public void Serialize() { var adminStateAddress = new PrivateKey().ToAddress(); var validUntil = 100; var adminState = new AdminState(adminStateAddress, validUntil); var serialized = adminState.Serialize(); var deserialized = new AdminState((Bencodex.Types.Dictionary)serialized); Assert.Equal(adminStateAddress, deserialized.AdminAddress); Assert.Equal(validUntil, deserialized.ValidUntil); }
public void Execute() { var newValidUntil = _validUntil + 1000; var action = new RenewAdminState(newValidUntil); var stateDelta = action.Execute(new ActionContext { PreviousStates = _stateDelta, Signer = _adminPrivateKey.ToAddress(), }); var adminState = new AdminState((Bencodex.Types.Dictionary)stateDelta.GetState(Addresses.Admin)); Assert.Equal(newValidUntil, adminState.ValidUntil); Assert.NotEqual(_validUntil, adminState.ValidUntil); }
protected override void LoadPlainValueInternal(IImmutableDictionary <string, IValue> plainValue) { RankingState = new RankingState((Bencodex.Types.Dictionary)plainValue["ranking_state"]); ShopState = new ShopState((Bencodex.Types.Dictionary)plainValue["shop_state"]); TableSheetsState = new TableSheetsState((Bencodex.Types.Dictionary)plainValue["table_sheets_state"]); GameConfigState = new GameConfigState((Bencodex.Types.Dictionary)plainValue["game_config_state"]); RedeemCodeState = new RedeemCodeState((Bencodex.Types.Dictionary)plainValue["redeem_code_state"]); AdminAddressState = new AdminState((Bencodex.Types.Dictionary)plainValue["admin_address_state"]); ActivatedAccountsState = new ActivatedAccountsState( (Bencodex.Types.Dictionary)plainValue["activated_accounts_state"] ); GoldCurrencyState = new GoldCurrencyState( (Bencodex.Types.Dictionary)plainValue["gold_currency_state"] ); }
public void CheckPermission() { var adminAddress = new Address("399bddF9F7B6d902ea27037B907B2486C9910730"); var adminState = new AdminState(adminAddress, 100); var initStates = ImmutableDictionary <Address, IValue> .Empty .Add(AdminState.Address, adminState.Serialize()) .Add(TableSheetsState.Address, new TableSheetsState(new Dictionary <string, string>() { ["TestTable"] = "Initial", }).Serialize()); var state = new State(initStates, ImmutableDictionary <(Address, Currency), BigInteger> .Empty); var action = new PatchTableSheet() { TableName = "TestTable", TableCsv = "New Value", }; PolicyExpiredException exc1 = Assert.Throws <PolicyExpiredException>(() => { action.Execute( new ActionContext() { BlockIndex = 101, PreviousStates = state, Signer = adminAddress, } ); }); Assert.Equal(101, exc1.BlockIndex); PermissionDeniedException exc2 = Assert.Throws <PermissionDeniedException>(() => { action.Execute( new ActionContext() { BlockIndex = 5, PreviousStates = state, Signer = new Address("019101FEec7ed4f918D396827E1277DEda1e20D4"), } ); }); Assert.Equal(new Address("019101FEec7ed4f918D396827E1277DEda1e20D4"), exc2.Signer); }
public void SerializeWithDotNetAPI() { var adminStateAddress = new PrivateKey().ToAddress(); var validUntil = 100; var adminState = new AdminState(adminStateAddress, validUntil); var formatter = new BinaryFormatter(); using var ms = new MemoryStream(); formatter.Serialize(ms, adminState); ms.Seek(0, SeekOrigin.Begin); var deserialized = (AdminState)formatter.Deserialize(ms); Assert.Equal(adminStateAddress, deserialized.AdminAddress); Assert.Equal(validUntil, deserialized.ValidUntil); }
/// <summary> /// 验证核心 /// </summary> /// <param name="httpContext"></param> /// <returns></returns> protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) { try { var myInfo = new AdminState(httpContext).GetUserInfo(); if (myInfo == null || !(bool)myInfo.InJob) { return(false); } return(true); } catch (Exception ex) { Tools.Tool.LogHelper.WriteLog(typeof(PermissionFilterAttribute), ex, 0, ""); return(false); } }
public void CheckPermission() { var adminAddress = new Address("399bddF9F7B6d902ea27037B907B2486C9910730"); var adminState = new AdminState(adminAddress, 100); var initStates = ImmutableDictionary <Address, IValue> .Empty .Add(AdminState.Address, adminState.Serialize()); var state = new State(initStates, ImmutableDictionary <(Address, Currency), FungibleAssetValue> .Empty); var action = new AddRedeemCode { redeemCsv = "New Value", }; PolicyExpiredException exc1 = Assert.Throws <PolicyExpiredException>(() => { action.Execute( new ActionContext { BlockIndex = 101, PreviousStates = state, Signer = adminAddress, } ); }); Assert.Equal(101, exc1.BlockIndex); PermissionDeniedException exc2 = Assert.Throws <PermissionDeniedException>(() => { action.Execute( new ActionContext { BlockIndex = 5, PreviousStates = state, Signer = new Address("019101FEec7ed4f918D396827E1277DEda1e20D4"), } ); }); Assert.Equal(new Address("019101FEec7ed4f918D396827E1277DEda1e20D4"), exc2.Signer); }
/// <summary> /// 检查用户是否有该Action执行的操作权限 /// </summary> /// <param name="actionContext"></param> public override void OnActionExecuting(HttpActionContext actionContext) { //如果请求Header不包含ticket,则判断是否是匿名调用 var attr = actionContext.ActionDescriptor.GetCustomAttributes <AllowAnonymousAttribute>().OfType <AllowAnonymousAttribute>(); bool isAnonymous = attr.Any(a => a is AllowAnonymousAttribute); //是匿名用户,则继续执行;非匿名用户,抛出“未授权访问”信息 if (!isAnonymous) { //获取当前用户对象 var myInfo = new AdminState((HttpContextBase)actionContext.Request.Properties["MS_HttpContext"]).GetUserInfo(); if (myInfo == null || !(bool)myInfo.InJob) { actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); } else { actionContext.Response = new HttpResponseMessage(HttpStatusCode.OK); } } base.OnActionExecuting(actionContext); }
public void Execute() { var sw = new System.Diagnostics.Stopwatch(); sw.Start(); PendingActivationState CreatePendingActivation() { var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 }; var pubKey = new PrivateKey().PublicKey; return(new PendingActivationState(nonce, pubKey)); } PendingActivationState[] activations = Enumerable.Range(0, 5000).Select(_ => CreatePendingActivation()).ToArray(); var action = new CreatePendingActivations(activations); var adminAddress = new Address("399bddF9F7B6d902ea27037B907B2486C9910730"); var adminState = new AdminState(adminAddress, 100); var state = new State(ImmutableDictionary <Address, IValue> .Empty .Add(AdminState.Address, adminState.Serialize()) ); var actionContext = new ActionContext() { BlockIndex = 1, PreviousStates = state, Signer = adminAddress, }; var nextState = action.Execute(actionContext); foreach (PendingActivationState pa in activations) { Assert.Equal( pa.Serialize(), nextState.GetState(pa.address) ); } }
public InitializeStates( RankingState rankingState, ShopState shopState, Dictionary <string, string> tableSheets, GameConfigState gameConfigState, RedeemCodeState redeemCodeState, AdminState adminAddressState, ActivatedAccountsState activatedAccountsState, GoldCurrencyState goldCurrencyState, GoldDistribution[] goldDistributions, PendingActivationState[] pendingActivationStates, AuthorizedMinersState authorizedMinersState = null, CreditsState creditsState = null) { Ranking = (Bencodex.Types.Dictionary)rankingState.Serialize(); Shop = (Bencodex.Types.Dictionary)shopState.Serialize(); TableSheets = tableSheets; GameConfig = (Bencodex.Types.Dictionary)gameConfigState.Serialize(); RedeemCode = (Bencodex.Types.Dictionary)redeemCodeState.Serialize(); AdminAddress = (Bencodex.Types.Dictionary)adminAddressState.Serialize(); ActivatedAccounts = (Bencodex.Types.Dictionary)activatedAccountsState.Serialize(); GoldCurrency = (Bencodex.Types.Dictionary)goldCurrencyState.Serialize(); GoldDistributions = new Bencodex.Types.List( goldDistributions.Select(d => d.Serialize()).Cast <Bencodex.Types.IValue>() ); PendingActivations = new Bencodex.Types.List(pendingActivationStates.Select(p => p.Serialize())); if (!(authorizedMinersState is null)) { AuthorizedMiners = (Bencodex.Types.Dictionary)authorizedMinersState.Serialize(); } if (!(creditsState is null)) { Credits = (Bencodex.Types.Dictionary)creditsState.Serialize(); } }
public override IAccountStateDelta Execute(IActionContext context) { var states = context.PreviousStates; if (context.Rehearsal) { return(states .SetState(Addresses.Admin, MarkChanged)); } if (TryGetAdminState(context, out AdminState adminState)) { if (context.Signer != adminState.AdminAddress) { throw new PermissionDeniedException(adminState, context.Signer); } var newAdminState = new AdminState(adminState.AdminAddress, NewValidUntil); states = states.SetState(Addresses.Admin, newAdminState.Serialize()); } return(states); }
public void CheckPermission() { var action = new CreatePendingActivations(); var adminAddress = new Address("399bddF9F7B6d902ea27037B907B2486C9910730"); var adminState = new AdminState(adminAddress, 100); var state = new State(ImmutableDictionary <Address, IValue> .Empty .Add(AdminState.Address, adminState.Serialize()) ); Assert.Throws <PolicyExpiredException>( () => action.Execute(new ActionContext() { BlockIndex = 101, PreviousStates = state, Signer = adminAddress, }) ); Assert.Throws <PermissionDeniedException>( () => action.Execute(new ActionContext() { BlockIndex = 1, PreviousStates = state, Signer = default,
public void Execute(bool isAdmin, bool expire, Type exc) { var adminAddress = new Address("399bddF9F7B6d902ea27037B907B2486C9910730"); var adminState = new AdminState(adminAddress, 100); var states = new State().SetState(Addresses.Admin, adminState.Serialize()); var signer = isAdmin ? adminAddress : default; var blockIndex = expire ? 200 : 100; var action = new MigrationLegacyShop(); var avatarAddress = new Address(action.AvatarAddressesHex.First()); if (exc is null) { var agentState = new AgentState(adminAddress); var avatarState = new AvatarState( avatarAddress, adminAddress, 0, _tableSheets.GetAvatarSheets(), new GameConfigState(), default); agentState.avatarAddresses[0] = avatarAddress; var shopState = new ShopState(); var itemSubTypes = new[] { ItemSubType.Weapon, ItemSubType.FullCostume }; var random = new TestRandom(); var itemIds = new List<Guid>(); foreach (var itemSubType in itemSubTypes) { var item = (ITradableItem)ItemFactory.CreateItem(_tableSheets.ItemSheet.Values.First(r => r.ItemSubType == itemSubType), random); var shopItem = new ShopItem( adminAddress, avatarAddress, Guid.NewGuid(), new FungibleAssetValue(new Currency("NCG", 2, minter: null), 100, 0), item); shopState.Register(shopItem); itemIds.Add(item.TradableId); } states = states .SetState(Addresses.Shop, shopState.Serialize()) .SetState(adminAddress, agentState.Serialize()) .SetState(avatarAddress, avatarState.Serialize()); var nextState = action.Execute(new ActionContext { BlockIndex = blockIndex, PreviousStates = states, Signer = signer, }); var nextShopState = nextState.GetShopState(); Assert.Empty(nextShopState.Products); var nextAvatarState = nextState.GetAvatarState(avatarAddress); Assert.All(itemIds, id => nextAvatarState.inventory.HasNonFungibleItem(id)); } else { Assert.Throws(exc, () => action.Execute(new ActionContext { BlockIndex = blockIndex, PreviousStates = states, Signer = signer, })); } }
public AdminPermissionException(AdminState policy) { Policy = policy; }
public PolicyExpiredException(AdminState policy, long blockIndex) : base(policy) { BlockIndex = blockIndex; }
/// <summary> /// 验证核心 /// </summary> /// <param name="httpContext"></param> /// <returns></returns> public void OnAuthorization(AuthorizationContext filterContext) { if (filterContext == null) { throw new ArgumentNullException("filterContext"); } if (filterContext.HttpContext.Request.Url == null) { throw new ArgumentNullException("filterContext"); } //判断action,controller上是否存在AllowAnonymous标签,任何用户都可以访问 var actionAnonymous = filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), true) as IEnumerable <AllowAnonymousAttribute>; var controllerAnonymous = filterContext.Controller.GetType().GetCustomAttributes(typeof(AllowAnonymousAttribute), true) as IEnumerable <AllowAnonymousAttribute>; if ((actionAnonymous != null && actionAnonymous.Any()) || (controllerAnonymous != null && controllerAnonymous.Any())) { return; } //当前用户 Mng_User myInfo = new AdminState(filterContext.HttpContext).GetUserInfo(); if (myInfo == null || !(bool)myInfo.InJob) { filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new { Controller = "auth", action = "login", area = "" })); } else { // 判断action,controller上是否有CheckLoginAttribute标签 只要登录就可以访问 var checkLoginActionAttr = filterContext.ActionDescriptor.GetCustomAttributes(typeof(CheckLoginAttribute), true) as IEnumerable <CheckLoginAttribute>; var checkLoginControllerAttr = filterContext.Controller.GetType().GetCustomAttributes(typeof(CheckLoginAttribute), true) as IEnumerable <CheckLoginAttribute>; if ((checkLoginActionAttr != null && checkLoginActionAttr.Any()) || (checkLoginControllerAttr != null && checkLoginControllerAttr.Any())) { return; } //如果使用了权限控制标签,则优先使用标签 var permissionFilterAttribute = filterContext.ActionDescriptor.GetCustomAttributes(typeof(PermissionFilterAttribute), true) as IEnumerable <PermissionFilterAttribute>; if (permissionFilterAttribute != null && permissionFilterAttribute.Any()) { return; } //获取当前路由信息 string areaName = filterContext.RouteData.DataTokens["area"]?.ToString() ?? ""; string controllerName = filterContext.RouteData.Values["controller"].ToString(); string actionName = filterContext.RouteData.Values["action"].ToString(); //拼接Url string url = (areaName != "" ? "/" + areaName : "") + "/" + controllerName + "/" + actionName; //验证权限 bool isValid = PermissionManager.CheckPermission(myInfo, url.ToLower()); if (!isValid) { //验证不通过 if (filterContext.HttpContext.Request.IsAjaxRequest()) { filterContext.Result = new HttpUnauthorizedResult(); //Ajax请求,返回401 } else { //直接JS跳回上页,并提示 var content = new ContentResult() { Content = "<script type=\"text/javascript\">" + "window.history.go(-1);" + "alert('您没有该操作权限!');" + "</script>" }; //或者直接跳转页面 filterContext.Result = new RedirectResult("/Home/UnAuthorized");//content } } return; } }
public PermissionDeniedException(AdminState policy, Address signer) : base(policy) { Signer = signer; }
protected AdminPermissionException(SerializationInfo info, StreamingContext context) { Policy = info.GetValue <AdminState>(nameof(Policy)); }