Skip to content

Commit

Permalink
Merge pull request #2589 from moreal/bump-lib9c
Browse files Browse the repository at this point in the history
Bump lib9c
  • Loading branch information
moreal authored Sep 23, 2024
2 parents 04a6875 + bc75b9e commit 2b3dfb4
Show file tree
Hide file tree
Showing 14 changed files with 63 additions and 538 deletions.
2 changes: 1 addition & 1 deletion Lib9c
Submodule Lib9c updated 90 files
+0 −4 .Lib9c.Tests/Action/ActionEvaluationTest.cs
+0 −83 .Lib9c.Tests/Action/ActivateAccountTest.cs
+0 −69 .Lib9c.Tests/Action/AddActivatedAccountTest.cs
+46 −20 .Lib9c.Tests/Action/BattleArenaTest.cs
+3 −0 .Lib9c.Tests/Action/ExceptionTest.cs
+2 −2 .Lib9c.Tests/Action/Garages/BulkUnloadFromGaragesTest.cs
+343 −0 .Lib9c.Tests/Action/JoinArenaTest.cs
+1 −1 .Lib9c.Tests/Action/MigrateMonsterCollectionTest.cs
+1 −1 .Lib9c.Tests/Action/Scenario/StakeAndClaimScenarioTest.cs
+0 −140 .Lib9c.Tests/Action/Snapshot/TransferAsset0SnapshotTest.cs
+0 −73 .Lib9c.Tests/Action/Snapshot/transfer_asset.PlainValue.verified.txt
+0 −12 .Lib9c.Tests/Action/Snapshot/transfer_asset.TransferCrystal.diff.verified.txt
+0 −12 .Lib9c.Tests/Action/Snapshot/transfer_asset.TransferWithMemo.diff.verified.txt
+0 −258 .Lib9c.Tests/Action/Stake0Test.cs
+1 −1 .Lib9c.Tests/Action/Stake2Test.cs
+1 −1 .Lib9c.Tests/Action/StakeTest.cs
+75 −0 .Lib9c.Tests/AddressesTest.cs
+29 −0 .Lib9c.Tests/Extensions/BencodexTypesExtensionsTest.cs
+46 −0 .Lib9c.Tests/Model/Arena/ArenaParticipantTest.cs
+1 −1 .Lib9c.Tests/Model/State/LazyStateTest.cs
+9 −4 .Lib9c.Tests/Policy/BlockPolicySourceTest.cs
+0 −4 .Lib9c.Tests/Policy/BlockPolicyTest.cs
+181 −89 .Lib9c.Tests/Util/InitializeUtil.cs
+12 −0 .config/dotnet-tools.json
+1 −2 .github/workflows/publish-docs.yml
+113 −0 CONTRIBUTING.md
+1 −0 Lib9c.sln.DotSettings
+0 −92 Lib9c/Action/ActivateAccount.cs
+0 −64 Lib9c/Action/AddActivatedAccount.cs
+2 −2 Lib9c/Action/AdventureBoss/ExploreAdventureBoss.cs
+2 −2 Lib9c/Action/AdventureBoss/SweepAdventureBoss.cs
+151 −88 Lib9c/Action/BattleArena.cs
+2 −2 Lib9c/Action/EventDungeonBattle.cs
+27 −0 Lib9c/Action/Exceptions/Arena/AlreadyJoinedArenaException.cs
+2 −2 Lib9c/Action/HackAndSlash.cs
+2 −12 Lib9c/Action/HackAndSlashSweep.cs
+139 −33 Lib9c/Action/JoinArena.cs
+2 −12 Lib9c/Action/Raid.cs
+1 −1 Lib9c/Action/Stake.cs
+0 −134 Lib9c/Action/Stake0.cs
+0 −138 Lib9c/Action/TransferAsset0.cs
+76 −53 Lib9c/Addresses.cs
+7 −6 Lib9c/Arena/ArenaHelper.cs
+27 −0 Lib9c/Exceptions/BencodexTypesExtensions.cs
+41 −0 Lib9c/Exceptions/UnsupportedStateException.cs
+6 −4 Lib9c/Helper/AvatarStateExtensions.cs
+0 −5 Lib9c/Model/ActivationKey.cs
+151 −0 Lib9c/Model/Arena/ArenaParticipant.cs
+1 −1 Lib9c/Model/State/ActivatedAccountsState.cs
+1 −1 Lib9c/Model/State/AdminState.cs
+4 −8 Lib9c/Model/State/AgentState.cs
+1 −1 Lib9c/Model/State/AuthorizedMinersState.cs
+17 −12 Lib9c/Model/State/AvatarState.cs
+2 −2 Lib9c/Model/State/CombinationSlotState.cs
+2 −2 Lib9c/Model/State/CreditsState.cs
+1 −1 Lib9c/Model/State/GameConfigState.cs
+1 −1 Lib9c/Model/State/GoldBalanceState.cs
+1 −1 Lib9c/Model/State/GoldCurrencyState.cs
+1 −1 Lib9c/Model/State/MonsterCollectionState.cs
+3 −3 Lib9c/Model/State/MonsterCollectionState0.cs
+1 −6 Lib9c/Model/State/PendingActivationState.cs
+1 −1 Lib9c/Model/State/RankingMapState.cs
+1 −1 Lib9c/Model/State/RankingState.cs
+1 −1 Lib9c/Model/State/RankingState0.cs
+1 −1 Lib9c/Model/State/RankingState1.cs
+1 −1 Lib9c/Model/State/RedeemCodeState.cs
+1 −1 Lib9c/Model/State/ShardedShopState.cs
+1 −1 Lib9c/Model/State/ShardedShopStateV2.cs
+1 −1 Lib9c/Model/State/ShopState.cs
+3 −3 Lib9c/Model/State/StakeState.cs
+5 −3 Lib9c/Model/State/State.cs
+1 −1 Lib9c/Model/State/WeeklyArenaState.cs
+77 −0 Lib9c/Module/ArenaModule.cs
+6 −0 Lib9c/Module/LegacyModule.cs
+51 −6 README.md
+27 −2 docs/README.md
+17 −0 docs/articles/currencies/mead.md
+2 −0 docs/articles/currencies/toc.yml
+202 −0 docs/articles/system/adventure.md
+31 −0 docs/articles/system/agent.md
+201 −0 docs/articles/system/arena.md
+40 −0 docs/articles/system/avatar/avatar.md
+30 −0 docs/articles/system/avatar/inventory.md
+31 −0 docs/articles/system/avatar/quest-list.md
+9 −0 docs/articles/system/avatar/toc.yml
+30 −0 docs/articles/system/avatar/world-information.md
+9 −0 docs/articles/system/toc.yml
+11 −4 docs/articles/toc.yml
+4 −2 docs/docfx.json
+4 −0 docs/filter.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,38 +26,6 @@ public ActionCommandTest()
_command = new ActionCommand(_console);
}

[Theory]
[InlineData(true, -1)]
[InlineData(false, 0)]
public void ActivateAccount(bool invalid, int expectedCode)
{
var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 };
var privateKey = new PrivateKey();
(ActivationKey activationKey, PendingActivationState _) = ActivationKey.Create(privateKey, nonce);
string invitationCode = invalid ? "invalid_code" : activationKey.Encode();
var filePath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());
var resultCode = _command.ActivateAccount(invitationCode, ByteUtil.Hex(nonce), filePath);
Assert.Equal(expectedCode, resultCode);

if (resultCode == 0)
{
var rawAction = Convert.FromBase64String(File.ReadAllText(filePath));
var decoded = (List)_codec.Decode(rawAction);
string type = (Text)decoded[0];
Assert.Equal(nameof(Nekoyume.Action.ActivateAccount), type);

Dictionary plainValue = (Dictionary)decoded[1];
var action = new ActivateAccount();
action.LoadPlainValue(plainValue);
Assert.Equal(activationKey.PrivateKey.Sign(nonce), action.Signature);
Assert.Equal(activationKey.PendingAddress, action.PendingAddress);
}
else
{
Assert.Contains("hexWithSlash seems invalid. [invalid_code]", _console.Error.ToString());
}
}

[Theory]
[InlineData(10, 0, "transfer asset test1.")]
[InlineData(100, 0, "transfer asset test2.")]
Expand Down
14 changes: 0 additions & 14 deletions NineChronicles.Headless.Executable.Tests/Commands/TxCommandTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,20 +31,6 @@ public TxCommandTest()
_blockHash = BlockHash.FromHashDigest(default);
}

[Theory]
[InlineData(1)]
[InlineData(2)]
public void Sign_ActivateAccount(int txNonce)
{
var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 };
(ActivationKey activationKey, PendingActivationState _) =
ActivationKey.Create(_privateKey, nonce);
var filePath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());
var actionCommand = new ActionCommand(_console);
actionCommand.ActivateAccount(activationKey.Encode(), ByteUtil.Hex(nonce), filePath);
Assert_Tx(txNonce, filePath, false);
}

[Theory]
[InlineData(1, false)]
[InlineData(10, true)]
Expand Down
43 changes: 0 additions & 43 deletions NineChronicles.Headless.Executable/Commands/ActionCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,49 +33,6 @@ public void Help([FromService] ICoconaHelpMessageBuilder helpMessageBuilder)
_console.Error.WriteLine(helpMessageBuilder.BuildAndRenderForCurrentContext());
}

[Command(Description = "Create ActivateAccount action.")]
public int ActivateAccount(
[Argument("INVITATION-CODE", Description = "An invitation code.")]
string invitationCode,
[Argument("NONCE", Description = "A hex-encoded nonce for activation.")]
string nonceEncoded,
[Argument("PATH", Description = "A file path of base64 encoded action.")]
string? filePath = null
)
{
try
{
ActivationKey activationKey = ActivationKey.Decode(invitationCode);
byte[] nonce = ByteUtil.ParseHex(nonceEncoded);
Nekoyume.Action.ActivateAccount action = activationKey.CreateActivateAccount(nonce);
var list = new List(
new[]
{
(Text) nameof(Nekoyume.Action.ActivateAccount),
action.PlainValue
}
);

byte[] raw = Codec.Encode(list);
string encoded = Convert.ToBase64String(raw);
if (filePath is null)
{
_console.Out.Write(encoded);
}
else
{
File.WriteAllText(filePath, encoded);
}

return 0;
}
catch (Exception e)
{
_console.Error.WriteLine(e);
return -1;
}
}

[Command(Description = "Lists all actions' type ids.")]
public IOrderedEnumerable<string?> List(
[Option(
Expand Down
1 change: 0 additions & 1 deletion NineChronicles.Headless.Executable/Commands/TxCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@ public void Sign(
ActionBase action = type switch
{
nameof(ActivateAccount) => new ActivateAccount(),
nameof(Stake) => new Stake(),
nameof(ClaimStakeReward) => new ClaimStakeReward(),
nameof(TransferAsset) => new TransferAsset(),
Expand Down
19 changes: 0 additions & 19 deletions NineChronicles.Headless.Tests/GraphTypes/ActionQueryTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -582,25 +582,6 @@ public async Task TransferAssets(bool exc)
}
}

[Fact]
public async Task ActivateAccount()
{
var activationCode = _activationKey.Encode();
var signature = _activationKey.PrivateKey.Sign(_nonce);

var query = $"{{ activateAccount(activationCode: \"{activationCode}\") }}";
var queryResult = await ExecuteQueryAsync<ActionQuery>(query, standaloneContext: _standaloneContext);

Assert.Null(queryResult.Errors);
var data = (Dictionary<string, object>)((ExecutionNode)queryResult.Data!).ToValue()!;
var plainValue = _codec.Decode(ByteUtil.ParseHex((string)data["activateAccount"]));
Assert.IsType<Dictionary>(plainValue);
var actionBase = DeserializeNCAction(plainValue);
var action = Assert.IsType<ActivateAccount>(actionBase);

Assert.Equal(signature, action.Signature);
}

[Theory]
[InlineData(-1, "ab", null, null, null, null, false)]
[InlineData(0, "ab", null, null, null, null, true)]
Expand Down
73 changes: 0 additions & 73 deletions NineChronicles.Headless.Tests/GraphTypes/StandaloneMutationTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -114,40 +114,6 @@ public async Task RevokePrivateKey()
Assert.Equal(address.ToString(), revokedPrivateKeyAddress);
}

[Fact]
public async Task ActivateAccount()
{
var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 };
var privateKey = new PrivateKey();
(ActivationKey activationKey, PendingActivationState pendingActivation) =
ActivationKey.Create(privateKey, nonce);
ActionBase action = new CreatePendingActivation(pendingActivation);
BlockChain.MakeTransaction(AdminPrivateKey, new[] { action });
Block block = BlockChain.ProposeBlock(
ProposerPrivateKey,
lastCommit: GenerateBlockCommit(BlockChain.Tip.Index, BlockChain.Tip.Hash, GenesisValidators));
BlockChain.Append(block, GenerateBlockCommit(block.Index, block.Hash, GenesisValidators));
AppendEmptyBlock(GenesisValidators);

var encodedActivationKey = activationKey.Encode();
var queryResult = await ExecuteQueryAsync(
$"mutation {{ activationStatus {{ activateAccount(encodedActivationKey: \"{encodedActivationKey}\") }} }}");
var data = (Dictionary<string, object>)((ExecutionNode)queryResult.Data!).ToValue()!;
block = BlockChain.ProposeBlock(
ProposerPrivateKey,
lastCommit: GenerateBlockCommit(BlockChain.Tip.Index, BlockChain.Tip.Hash, GenesisValidators));
BlockChain.Append(block, GenerateBlockCommit(block.Index, block.Hash, GenesisValidators));

var result =
(bool)((Dictionary<string, object>)
data["activationStatus"])["activateAccount"];
Assert.True(result);

Address userAddress = StandaloneContextFx.NineChroniclesNodeService!.MinerPrivateKey!.Address;
IValue? state = BlockChain.GetNextWorldState().GetLegacyState(userAddress.Derive(ActivationKey.DeriveKey));
Assert.True((Bencodex.Types.Boolean)state);
}

[Theory]
[InlineData(null, false)]
[InlineData("", false)]
Expand Down Expand Up @@ -846,45 +812,6 @@ public async Task Tx_V2()
Assert.Null(result.Errors);
}

[Fact]
public async Task Tx_ActivateAccount()
{
var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 };
var privateKey = new PrivateKey();
(ActivationKey activationKey, PendingActivationState pendingActivation) =
ActivationKey.Create(privateKey, nonce);
ActionBase action = new CreatePendingActivation(pendingActivation);
BlockChain.MakeTransaction(AdminPrivateKey, new[] { action });
Block block = BlockChain.ProposeBlock(
ProposerPrivateKey,
lastCommit: GenerateBlockCommit(BlockChain.Tip.Index, BlockChain.Tip.Hash, GenesisValidators));
BlockChain.Append(block, GenerateBlockCommit(block.Index, block.Hash, GenesisValidators));
AppendEmptyBlock(GenesisValidators);
var encodedActivationKey = activationKey.Encode();
var actionCommand = new ActionCommand(new StandardConsole());
var filePath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());
actionCommand.ActivateAccount(encodedActivationKey, ByteUtil.Hex(nonce), filePath);
var console = new StringIOConsole();
var txCommand = new TxCommand(console);
var timeStamp = DateTimeOffset.UtcNow;
txCommand.Sign(ByteUtil.Hex(privateKey.ByteArray), BlockChain.GetNextTxNonce(privateKey.Address), ByteUtil.Hex(BlockChain.Genesis.Hash.ByteArray), timeStamp.ToString(), new[] { filePath });
var output = console.Out.ToString();
output = output.Trim();
var queryResult = await ExecuteQueryAsync(
$"mutation {{ stageTx(payload: \"{output}\") }}");
var data = (Dictionary<string, object>)((ExecutionNode)queryResult.Data!).ToValue()!;
block = BlockChain.ProposeBlock(
ProposerPrivateKey,
lastCommit: GenerateBlockCommit(BlockChain.Tip.Index, BlockChain.Tip.Hash, GenesisValidators));
BlockChain.Append(block, GenerateBlockCommit(block.Index, block.Hash, GenesisValidators));

var result = (bool)data["stageTx"];
Assert.True(result);

IValue? state = BlockChain.GetNextWorldState().GetLegacyState(privateKey.Address.Derive(ActivationKey.DeriveKey));
Assert.True((Bencodex.Types.Boolean)state);
}

[Fact]
public async Task StageTransaction()
{
Expand Down
130 changes: 1 addition & 129 deletions NineChronicles.Headless.Tests/GraphTypes/StandaloneQueryTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -453,130 +453,6 @@ public async Task ConvertPrivateKey(bool compress)
Assert.Equal(privateKey.Address.ToString(), publicKeyResult["address"]);
}

[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task ActivationStatus(bool existsActivatedAccounts)
{
var adminPrivateKey = new PrivateKey();
var adminAddress = adminPrivateKey.Address;
var activatedAccounts = ImmutableHashSet<Address>.Empty;

if (existsActivatedAccounts)
{
activatedAccounts = new[] { adminAddress }.ToImmutableHashSet();
}

ValidatorSet validatorSetCandidate = new ValidatorSet(new[]
{
new Libplanet.Types.Consensus.Validator(ProposerPrivateKey.PublicKey, BigInteger.One),
}.ToList());
Block genesis =
BlockChain.ProposeGenesisBlock(
transactions: ImmutableList<Transaction>.Empty
.Add(Transaction.Create(0, ProposerPrivateKey, null,
new ActionBase[]
{
new InitializeStates(
rankingState: new RankingState0(),
shopState: new ShopState(),
gameConfigState: new GameConfigState(),
redeemCodeState: new RedeemCodeState(Bencodex.Types.Dictionary.Empty
.Add("address", RedeemCodeState.Address.Serialize())
.Add("map", Bencodex.Types.Dictionary.Empty)
),
adminAddressState: new AdminState(adminAddress, 1500000),
activatedAccountsState: new ActivatedAccountsState(activatedAccounts),
#pragma warning disable CS0618
// Use of obsolete method Currency.Legacy():
// https://github.com/planetarium/lib9c/discussions/1319
goldCurrencyState: new GoldCurrencyState(Currency.Legacy("NCG", 2, null)),
#pragma warning restore CS0618
goldDistributions: new GoldDistribution[0],
tableSheets: _sheets,
pendingActivationStates: new PendingActivationState[] { }
),
}.ToPlainValues()))
.AddRange(new IAction[]
{
new Initialize(
validatorSet: validatorSetCandidate,
states: ImmutableDictionary<Address, IValue>.Empty),
}.Select((sa, nonce) =>
Transaction.Create(nonce + 1, ProposerPrivateKey, null,
new[] { sa.PlainValue }))
),
privateKey: ProposerPrivateKey
);

var apvPrivateKey = new PrivateKey();
var apv = AppProtocolVersion.Sign(apvPrivateKey, 0);
var userPrivateKey = new PrivateKey();
var consensusPrivateKey = new PrivateKey();
var properties = new LibplanetNodeServiceProperties
{
Host = System.Net.IPAddress.Loopback.ToString(),
AppProtocolVersion = apv,
GenesisBlock = genesis,
StorePath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()),
StoreStatesCacheSize = 2,
SwarmPrivateKey = new PrivateKey(),
ConsensusPrivateKey = consensusPrivateKey,
ConsensusPort = null,
Port = null,
NoMiner = true,
Render = false,
Peers = ImmutableHashSet<BoundPeer>.Empty,
TrustedAppProtocolVersionSigners = null,
IceServers = ImmutableList<IceServer>.Empty,
ConsensusSeeds = ImmutableList<BoundPeer>.Empty,
ConsensusPeers = ImmutableList<BoundPeer>.Empty
};
var blockPolicy = new BlockPolicySource().GetPolicy();

var service = new NineChroniclesNodeService(
userPrivateKey, properties, blockPolicy, Planet.Odin, StaticActionLoaderSingleton.Instance);
StandaloneContextFx.NineChroniclesNodeService = service;
StandaloneContextFx.BlockChain = service.Swarm?.BlockChain;

var blockChain = StandaloneContextFx.BlockChain!;
AppendEmptyBlock(GenesisValidators);

var queryResult = await ExecuteQueryAsync("query { activationStatus { activated } }");
var data = (Dictionary<string, object>)((ExecutionNode)queryResult.Data!).ToValue()!;
var result = (bool)
((Dictionary<string, object>)data["activationStatus"])["activated"];

// If we don't use activated accounts, bypass check (always true).
Assert.Equal(!existsActivatedAccounts, result);

var nonce = new byte[] { 0x00, 0x01, 0x02, 0x03 };
var privateKey = new PrivateKey();
(ActivationKey activationKey, PendingActivationState pendingActivation) =
ActivationKey.Create(privateKey, nonce);
ActionBase action = new CreatePendingActivation(pendingActivation);
blockChain.MakeTransaction(adminPrivateKey, new[] { action });
Block block = blockChain.ProposeBlock(
ProposerPrivateKey,
lastCommit: GenerateBlockCommit(BlockChain.Tip.Index, BlockChain.Tip.Hash, GenesisValidators));
blockChain.Append(block, GenerateBlockCommit(block.Index, block.Hash, GenesisValidators));

action = activationKey.CreateActivateAccount(nonce);
blockChain.MakeTransaction(userPrivateKey, new[] { action });
block = blockChain.ProposeBlock(
ProposerPrivateKey,
lastCommit: GenerateBlockCommit(BlockChain.Tip.Index, BlockChain.Tip.Hash, GenesisValidators));
blockChain.Append(block, GenerateBlockCommit(block.Index, block.Hash, GenesisValidators));
AppendEmptyBlock(GenesisValidators);

queryResult = await ExecuteQueryAsync("query { activationStatus { activated } }");
data = (Dictionary<string, object>)((ExecutionNode)queryResult.Data!).ToValue()!;
result = (bool)
((Dictionary<string, object>)data["activationStatus"])["activated"];

Assert.True(result);
}

[Fact]
public async Task GoldBalance()
{
Expand Down Expand Up @@ -628,8 +504,7 @@ Transaction MakeTx(long nonce, ActionBase action)
var currency = Currency.Uncapped("NCG", 2, null);
var txs = new[]
{
MakeTx(0, new TransferAsset0(sender, recipient, new FungibleAssetValue(currency, 1, 0), memo)),
MakeTx(1, new TransferAsset(sender, recipient, new FungibleAssetValue(currency, 1, 0), memo)),
MakeTx(0, new TransferAsset(sender, recipient, new FungibleAssetValue(currency, 1, 0), memo)),
};
var block = new Domain.Model.BlockChain.Block(
blockHash,
Expand All @@ -646,9 +521,6 @@ Transaction MakeTx(long nonce, ActionBase action)
TransactionRepository.Setup(repo => repo.GetTxExecution(blockHash, txs[0].Id))
.Returns(new TxExecution(
blockHash, txs[0].Id, false, MerkleTrie.EmptyRootHash, MerkleTrie.EmptyRootHash, new List<string?>()));
TransactionRepository.Setup(repo => repo.GetTxExecution(blockHash, txs[1].Id))
.Returns(new TxExecution(
blockHash, txs[1].Id, false, MerkleTrie.EmptyRootHash, MerkleTrie.EmptyRootHash, new List<string?>()));

var blockHashHex = ByteUtil.Hex(block.Hash.ToByteArray());
var result =
Expand Down
Loading

0 comments on commit 2b3dfb4

Please sign in to comment.