Skip to content

Commit

Permalink
Merge pull request #29 from earlbread/cleanup-code
Browse files Browse the repository at this point in the history
Cleanup code
  • Loading branch information
earlbread authored Nov 22, 2019
2 parents 1584bb8 + 6dc18fd commit 3331f1d
Show file tree
Hide file tree
Showing 13 changed files with 83 additions and 170 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using Bencodex.Types;
using Libplanet;
using Libplanet.Action;
using UnityEngine;

namespace LibplanetUnity.Action
{
Expand Down
1 change: 0 additions & 1 deletion planet-clicker/Assets/LibplanetUnity/Action/ActionBase.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System;
using System.Collections.Immutable;
using Bencodex.Types;
using Libplanet.Action;

Expand Down
105 changes: 38 additions & 67 deletions planet-clicker/Assets/LibplanetUnity/Agent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,54 +31,59 @@ public class Agent : MonoSingleton<Agent>

private const int SwarmDialTimeout = 5000;

private const int SwarmLinger = 1 * 1000;
private const string PlayerPrefsKeyOfAgentPrivateKey = "private_key_agent";

public const string PlayerPrefsKeyOfAgentPrivateKey = "private_key_agent";
#if UNITY_EDITOR
private const string AgentStoreDirName = "planetarium_dev";
#else
private const string AgentStoreDirName = "planetarium";
#endif

private static readonly string CommandLineOptionsJsonPath = Path.Combine(Application.streamingAssetsPath, "clo.json");

private const string PeersFileName = "peers.dat";

private const string IceServersFileName = "ice_servers.dat";

private static readonly string DefaultStoragePath =
Path.Combine(Application.persistentDataPath, AgentStoreDirName);

private static IEnumerator _miner;
private static IEnumerator _swarmRunner;

private ConcurrentQueue<System.Action> _actions = new ConcurrentQueue<System.Action>();
public long BlockIndex => _blocks?.Tip?.Index ?? 0;
private PrivateKey PrivateKey { get; set; }
public Address Address { get; set; }
private static IEnumerator _swarmRunner;

public event EventHandler BootstrapStarted;
public event EventHandler PreloadStarted;
public event EventHandler<PreloadState> PreloadProcessed;
public event EventHandler PreloadEnded;
private readonly ConcurrentQueue<System.Action> _actions = new ConcurrentQueue<System.Action>();

public bool SyncSucceed { get; private set; }
private PrivateKey PrivateKey { get; set; }

private BlockChain<PolymorphicAction<ActionBase>> _blocks;

private Swarm<PolymorphicAction<ActionBase>> _swarm;

protected DefaultStore _store;
private DefaultStore _store;

private ImmutableList<Peer> _seedPeers;

private IImmutableSet<Address> _trustedPeers;

private CancellationTokenSource _cancellationTokenSource;

public Address Address { get; private set; }

public static void Initialize()
{
instance.InitAgent();
}

public IValue GetState(Address address)
{
AddressStateMap states = _blocks.GetState(address);
states.TryGetValue(address, out var value);
return value;
}

public void MakeTransaction(IEnumerable<ActionBase> gameActions)
{
var actions = gameActions.Select(gameAction => (PolymorphicAction<ActionBase>) gameAction).ToList();
Task.Run(() => MakeTransaction(actions, true));
}

private void InitAgent()
{
var options = GetOptions(CommandLineOptionsJsonPath);
Expand All @@ -97,11 +102,15 @@ private void InitAgent()
StartNullableCoroutine(_miner);
}

public void Init(PrivateKey privateKey, string path, IEnumerable<Peer> peers,
private void Init(PrivateKey privateKey, string path, IEnumerable<Peer> peers,
IEnumerable<IceServer> iceServers, string host, int? port)
{
Debug.Log(path);
var policy = GetPolicy();
var policy = new BlockPolicy<PolymorphicAction<ActionBase>>(
null,
BlockInterval,
100000,
2048);
PrivateKey = privateKey;
Address = privateKey.PublicKey.ToAddress();
_store = new DefaultStore(path, flush: false);
Expand All @@ -116,16 +125,12 @@ public void Init(PrivateKey privateKey, string path, IEnumerable<Peer> peers,
differentVersionPeerEncountered: DifferentAppProtocolVersionPeerEncountered);

_seedPeers = peers.Where(peer => peer.PublicKey != privateKey.PublicKey).ToImmutableList();
// Init SyncSucceed
SyncSucceed = true;

// FIXME: Trusted peers should be configurable
_trustedPeers = _seedPeers.Select(peer => peer.Address).ToImmutableHashSet();
_cancellationTokenSource = new CancellationTokenSource();

}

public static Options GetOptions(string jsonPath)
private static Options GetOptions(string jsonPath)
{
if (File.Exists(jsonPath))
{
Expand All @@ -139,13 +144,6 @@ public static Options GetOptions(string jsonPath)
}
}

public IValue GetState(Address address)
{
AddressStateMap states = _blocks.GetState(address);
states.TryGetValue(address, out var value);
return value;
}

public void RunOnMainThread(System.Action action)
{
_actions.Enqueue(action);
Expand Down Expand Up @@ -191,24 +189,21 @@ private static BoundPeer LoadPeer(string peerInfo)
string[] tokens = peerInfo.Split(',');
var pubKey = new PublicKey(ByteUtil.ParseHex(tokens[0]));
string host = tokens[1];
int port = int.Parse(tokens[2]);
var port = int.Parse(tokens[2]);

return new BoundPeer(pubKey, new DnsEndPoint(host, port), 0);
}

private static IEnumerable<string> LoadConfigLines(string fileName)
{
string userPath = Path.Combine(
Application.persistentDataPath,
fileName
);
string userPath = Path.Combine(Application.persistentDataPath, fileName);
string content;

if (File.Exists(userPath))
{
content = File.ReadAllText(userPath);
}
else
else
{
string assetName = Path.GetFileNameWithoutExtension(fileName);
content = Resources.Load<TextAsset>($"Config/{assetName}").text;
Expand All @@ -225,7 +220,7 @@ private static IEnumerable<string> LoadConfigLines(string fileName)

private static IEnumerable<IceServer> LoadIceServers()
{
foreach (string line in LoadConfigLines(IceServersFileName))
foreach (string line in LoadConfigLines(IceServersFileName))
{
var uri = new Uri(line);
string[] userInfo = uri.UserInfo.Split(':');
Expand Down Expand Up @@ -258,19 +253,8 @@ private Coroutine StartNullableCoroutine(IEnumerator routine)
return ReferenceEquals(routine, null) ? null : StartCoroutine(routine);
}

private IBlockPolicy<PolymorphicAction<ActionBase>> GetPolicy()
{
return new BlockPolicy<PolymorphicAction<ActionBase>>(
null,
BlockInterval,
100000,
2048
);
}

public IEnumerator CoSwarmRunner()
private IEnumerator CoSwarmRunner()
{
BootstrapStarted?.Invoke(this, null);
var bootstrapTask = Task.Run(async () =>
{
try
Expand All @@ -289,7 +273,6 @@ await _swarm.BootstrapAsync(

yield return new WaitUntil(() => bootstrapTask.IsCompleted);

PreloadStarted?.Invoke(this, null);
Debug.Log("PreloadingStarted event was invoked");

DateTimeOffset started = DateTimeOffset.UtcNow;
Expand All @@ -300,9 +283,7 @@ await _swarm.BootstrapAsync(
{
await _swarm.PreloadAsync(
TimeSpan.FromMilliseconds(SwarmDialTimeout),
new Progress<PreloadState>(state =>
PreloadProcessed?.Invoke(this, state)
),
null,
trustedStateValidators: _trustedPeers,
cancellationToken: _cancellationTokenSource.Token
);
Expand All @@ -327,9 +308,6 @@ await _swarm.PreloadAsync(
index - existingBlocks
);


PreloadEnded?.Invoke(this, null);

var swarmStartTask = Task.Run(async () =>
{
try
Expand Down Expand Up @@ -368,7 +346,6 @@ private void DifferentAppProtocolVersionPeerEncountered(object sender, Different
{
Debug.LogWarningFormat("Different Version Encountered Expected: {0} Actual : {1}",
e.ExpectedVersion, e.ActualVersion);
SyncSucceed = false;
}

private IEnumerator CoProcessActions()
Expand All @@ -383,7 +360,7 @@ private IEnumerator CoProcessActions()
}
}

public static bool WantsToQuit()
private static bool WantsToQuit()
{
return true;
}
Expand All @@ -394,12 +371,6 @@ private static void RunOnStart()
Application.wantsToQuit += WantsToQuit;
}

public void MakeTransaction(IEnumerable<ActionBase> gameActions)
{
var actions = gameActions.Select(gameAction => (PolymorphicAction<ActionBase>) gameAction).ToList();
Task.Run(() => MakeTransaction(actions, true));
}

private Transaction<PolymorphicAction<ActionBase>> MakeTransaction(
IEnumerable<PolymorphicAction<ActionBase>> actions, bool broadcast)
{
Expand All @@ -409,7 +380,7 @@ private Transaction<PolymorphicAction<ActionBase>> MakeTransaction(
return _blocks.MakeTransaction(PrivateKey, polymorphicActions);
}

public IEnumerator CoMiner()
private IEnumerator CoMiner()
{
while (true)
{
Expand Down
8 changes: 0 additions & 8 deletions planet-clicker/Assets/Plugins.meta

This file was deleted.

8 changes: 0 additions & 8 deletions planet-clicker/Assets/Plugins/Editor.meta

This file was deleted.

25 changes: 9 additions & 16 deletions planet-clicker/Assets/_Script/Action/AddCount.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using _Script.State;
using Bencodex.Types;
using Libplanet.Action;
Expand All @@ -9,7 +7,7 @@

namespace _Script.Action
{
[ActionType("store_count")]
[ActionType("add_count")]
public class AddCount : ActionBase
{
private long _count;
Expand All @@ -29,7 +27,7 @@ public AddCount(long count)
public override void LoadPlainValue(IValue plainValue)
{
var serialized = (Bencodex.Types.Dictionary)plainValue;
_count = (long) ((Integer) serialized["count"]).Value;
_count = (long)((Integer)serialized["count"]).Value;
}

public override IAccountStateDelta Execute(IActionContext ctx)
Expand All @@ -38,18 +36,13 @@ public override IAccountStateDelta Execute(IActionContext ctx)
var rankingAddress = RankingState.Address;
states.TryGetState(ctx.Signer, out Bencodex.Types.Integer currentCount);
var nextCount = currentCount + _count;

Debug.Log($"store_count: CurrentCount: {currentCount}, NextCount: {nextCount}");

RankingState rankingState;
if (states.TryGetState(rankingAddress, out Bencodex.Types.Dictionary bdict))
{
rankingState = new RankingState(bdict);
}
else
{
rankingState = new RankingState();
}
Debug.Log($"add_count: CurrentCount: {currentCount}, NextCount: {nextCount}");

var rankingState = states.TryGetState(rankingAddress, out Bencodex.Types.Dictionary bdict)
? new RankingState(bdict)
: new RankingState();

rankingState.Update(ctx.Signer, nextCount);
states = states.SetState(rankingAddress, rankingState.Serialize());
return states.SetState(ctx.Signer, (Bencodex.Types.Integer)nextCount);
Expand All @@ -58,7 +51,7 @@ public override IAccountStateDelta Execute(IActionContext ctx)
public override void Render(IActionContext ctx, IAccountStateDelta nextStates)
{
var agent = Agent.instance;
var count = (long)((Integer)nextStates.GetState(ctx.Signer));
var count = (Integer)nextStates.GetState(ctx.Signer);
var rankingState = new RankingState(
(Bencodex.Types.Dictionary)nextStates.GetState(RankingState.Address)
);
Expand Down
Loading

0 comments on commit 3331f1d

Please sign in to comment.