Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce MigrateAgentAvatar action #2439

Merged
merged 5 commits into from
Mar 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
203 changes: 203 additions & 0 deletions .Lib9c.Tests/Action/MigrateAgentAvatarTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
namespace Lib9c.Tests.Action
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Bencodex.Types;
using Libplanet.Action;
using Libplanet.Action.State;
using Libplanet.Crypto;
using Libplanet.Types.Assets;
using Nekoyume;
using Nekoyume.Action;
using Nekoyume.Action.Loader;
using Nekoyume.Model.State;
using Nekoyume.Module;
using Nekoyume.TableData;
using Xunit;
using static Lib9c.SerializeKeys;

public class MigrateAgentAvatarTest
{
private readonly TableSheets _tableSheets;

public MigrateAgentAvatarTest()
{
var sheets = TableSheetsImporter.ImportSheets();
sheets[nameof(CharacterSheet)] = string.Join(
Environment.NewLine,
"id,_name,size_type,elemental_type,hp,atk,def,cri,hit,spd,lv_hp,lv_atk,lv_def,lv_cri,lv_hit,lv_spd,attack_range,run_speed",
"100010,전사,S,0,300,20,10,10,90,70,12,0.8,0.4,0,3.6,2.8,2,3");
_tableSheets = new TableSheets(sheets);
}

[Theory]
[InlineData(1, false)]
[InlineData(1, true)]
[InlineData(2, false)]
[InlineData(2, true)]
public void MigrateAgentAvatar(int legacyAvatarVersion, bool alreadyMigrated)
{
var avatarIndex = 1;
var agentAddress = new PrivateKey().Address;
var agentState = new AgentState(agentAddress);
var avatarAddress = agentAddress.Derive(string.Format(CultureInfo.InvariantCulture, CreateAvatar.DeriveFormat, avatarIndex));
agentState.avatarAddresses.Add(avatarIndex, avatarAddress);

var inventoryAddress = avatarAddress.Derive(LegacyInventoryKey);
var questListAddress = avatarAddress.Derive(LegacyQuestListKey);
var worldInformationAddress = avatarAddress.Derive(LegacyWorldInformationKey);

var weekly = new WeeklyArenaState(0);
var gameConfigState = new GameConfigState();
gameConfigState.Set(_tableSheets.GameConfigSheet);
var currency = Currency.Legacy("NCG", 2, null);

var avatarState = new AvatarState(
avatarAddress,
agentAddress,
456,
_tableSheets.GetAvatarSheets(),
gameConfigState,
default);

MockWorldState mock = new MockWorldState()
.SetState(
ReservedAddresses.LegacyAccount,
GoldCurrencyState.Address,
new GoldCurrencyState(currency, 0).Serialize())
.SetState(
ReservedAddresses.LegacyAccount,
weekly.address,
weekly.Serialize())
.SetState(
ReservedAddresses.LegacyAccount,
Addresses.GoldDistribution,
new List())
.SetState(
ReservedAddresses.LegacyAccount,
gameConfigState.address,
gameConfigState.Serialize());

switch (legacyAvatarVersion)
{
case 1:
mock = mock
.SetState(
ReservedAddresses.LegacyAccount,
agentAddress,
SerializeLegacyAgent(agentState))
.SetState(
ReservedAddresses.LegacyAccount,
avatarAddress,
MigrationAvatarState.LegacySerializeV1(avatarState));
break;
case 2:
mock = mock
.SetState(
ReservedAddresses.LegacyAccount,
agentAddress,
SerializeLegacyAgent(agentState))
.SetState(
ReservedAddresses.LegacyAccount,
avatarAddress,
MigrationAvatarState.LegacySerializeV2(avatarState))
.SetState(
ReservedAddresses.LegacyAccount,
inventoryAddress,
avatarState.inventory.Serialize())
.SetState(
ReservedAddresses.LegacyAccount,
worldInformationAddress,
avatarState.questList.Serialize())
.SetState(
ReservedAddresses.LegacyAccount,
questListAddress,
avatarState.questList.Serialize());
break;
default:
throw new ArgumentException($"Invalid legacy avatar version: {legacyAvatarVersion}");
}

if (alreadyMigrated)
{
mock = mock
.SetState(
Addresses.Agent,
agentAddress,
agentState.SerializeList())
.SetState(
Addresses.Avatar,
avatarAddress,
avatarState.SerializeList())
.SetState(
Addresses.Inventory,
avatarAddress,
avatarState.inventory.Serialize())
.SetState(
Addresses.WorldInformation,
avatarAddress,
avatarState.worldInformation.Serialize())
.SetState(
Addresses.QuestList,
avatarAddress,
avatarState.questList.Serialize());
}

IAction action = new MigrateAgentAvatar
{
AgentAddresses = new List<Address> { agentAddress },
};

var plainValue = action.PlainValue;
var actionLoader = new NCActionLoader();
action = actionLoader.LoadAction(123, plainValue);

var states = new World(mock);
IWorld nextState = action.Execute(
new ActionContext()
{
PreviousState = states,
Miner = default,
Signer = new Address("e2D18a50472e93d3165c478DefA69fa149214E72"),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this equals to agentAddress?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is equal to MigrateAgentAvatar.Operator, which is defined as private.

}
);

Assert.Null(nextState.GetLegacyState(agentAddress));
Assert.Null(nextState.GetLegacyState(avatarAddress));
Assert.Null(nextState.GetLegacyState(inventoryAddress));
Assert.Null(nextState.GetLegacyState(worldInformationAddress));
Assert.Null(nextState.GetLegacyState(questListAddress));

Assert.NotNull(nextState.GetAccount(Addresses.Agent).GetState(agentAddress));
Assert.NotNull(nextState.GetAccount(Addresses.Avatar).GetState(avatarAddress));
Assert.NotNull(nextState.GetAccount(Addresses.Inventory).GetState(avatarAddress));
Assert.NotNull(nextState.GetAccount(Addresses.WorldInformation).GetState(avatarAddress));
Assert.NotNull(nextState.GetAccount(Addresses.QuestList).GetState(avatarAddress));
}

private static IValue SerializeLegacyAgent(AgentState agentState)
{
var innerDict = new Dictionary<IKey, IValue>
{
[(Text)"avatarAddresses"] = new Dictionary(
agentState.avatarAddresses.Select(kv =>
new KeyValuePair<IKey, IValue>(
new Binary(BitConverter.GetBytes(kv.Key)),
kv.Value.Serialize()
)
)
),
[(Text)"unlockedOptions"] = new List(),
[(Text)LegacyAddressKey] = agentState.address.Serialize(),
};
if (agentState.MonsterCollectionRound > 0)
{
innerDict.Add((Text)MonsterCollectionRoundKey, agentState.MonsterCollectionRound.Serialize());
}

return new Dictionary(innerDict);
}
}
}
123 changes: 123 additions & 0 deletions Lib9c/Action/MigrateAgentAvatar.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Bencodex.Types;
using Libplanet.Action;
using Libplanet.Action.State;
using Libplanet.Crypto;
using Nekoyume.Module;
using Serilog;
using static Lib9c.SerializeKeys;

namespace Nekoyume.Action
{
[ActionType(TypeIdentifier)]
public class MigrateAgentAvatar : ActionBase
{
public const string TypeIdentifier = "migrate_agent_avatar";

private static readonly Address Operator =
new Address("e2D18a50472e93d3165c478DefA69fa149214E72");

public List<Address> AgentAddresses;

public MigrateAgentAvatar()
{
}

public override IValue PlainValue => Dictionary.Empty
.Add("type_id", TypeIdentifier)
.Add(
"values",
Dictionary.Empty.Add(
"agent_addresses",
new List(AgentAddresses.Select(address => address.Bencoded))));

public override void LoadPlainValue(IValue plainValue)
{
var asDict = (Dictionary)((Dictionary)plainValue)["values"];
AgentAddresses = ((List)asDict["agent_addresses"]).Select(v => new Address(v)).ToList();
}

public override IWorld Execute(IActionContext context)
{
context.UseGas(1);

#if !LIB9C_DEV_EXTENSIONS && !UNITY_EDITOR
if (context.Signer != Operator)
{
throw new Exception("Migration action must be signed by given operator.");
}
#endif

var states = context.PreviousState;
var migrationStarted = DateTimeOffset.UtcNow;
Log.Debug("Migrating agent/avatar states in block index #{Index} started", context.BlockIndex);

const int maxAvatarCount = 3;
var avatarAddresses = Enumerable
.Range(0, AgentAddresses.Count * maxAvatarCount)
.Select(i => AgentAddresses[i / maxAvatarCount]
.Derive(
string.Format(CultureInfo.InvariantCulture, CreateAvatar.DeriveFormat, i % maxAvatarCount)))
.ToList();

foreach (var address in AgentAddresses)
{
// Try migrating if not already migrated
var started = DateTimeOffset.UtcNow;
Log.Debug("Migrating agent {Address}", address);
if (states.GetAccountState(Addresses.Agent).GetState(address) is null)
{
Log.Debug("Getting agent {Address}", address);
var agentState = states.GetAgentState(address);
if (agentState is null) continue;
Log.Debug("Setting agent {Address} to modern account", address);
states = states.SetAgentState(address, agentState);
}

// Delete AgentState in Legacy
Log.Debug("Deleting agent {Address} from legacy account", address);
states = states.SetLegacyState(address, null);
Log.Debug(
"Migrating agent {Address} finished in: {Elapsed} ms",
address,
(DateTimeOffset.UtcNow - started).Milliseconds);
}

foreach (var address in avatarAddresses)
{
var started = DateTimeOffset.UtcNow;
Log.Debug("Migrating avatar {Address}", address);
// Try migrating if not already migrated
if (states.GetAccountState(Addresses.Avatar).GetState(address) is null)
{
Log.Debug("Getting avatar {Address}", address);
var avatarState = states.GetAvatarState(address);
if (avatarState is null) continue;
Log.Debug("Setting avatar {Address} to modern account", address);
states = states.SetAvatarState(address, avatarState);
}

// Delete AvatarState in Legacy
Log.Debug("Deleting avatar {Address} from legacy account", address);
states = states.SetLegacyState(address, null);
states = states.SetLegacyState(address.Derive(LegacyInventoryKey), null);
states = states.SetLegacyState(address.Derive(LegacyQuestListKey), null);
states = states.SetLegacyState(address.Derive(LegacyWorldInformationKey), null);
Log.Debug(
"Migrating avatar {Address} finished in: {Elapsed} ms",
address,
(DateTimeOffset.UtcNow - started).Milliseconds);
}

Log.Debug(
"Migrating {Count} agents in block index #{Index} finished in: {Elapsed} ms",
AgentAddresses.Count,
context.BlockIndex,
(DateTimeOffset.UtcNow - migrationStarted).Milliseconds);
return states;
}
}
}
Loading