Skip to content

Commit

Permalink
Bring more extension methods and cleanup code
Browse files Browse the repository at this point in the history
  • Loading branch information
monoman committed Nov 23, 2019
1 parent 93733c4 commit 67ad493
Show file tree
Hide file tree
Showing 25 changed files with 80 additions and 120 deletions.
2 changes: 1 addition & 1 deletion InterlockLedger.Tags.UnitTests/EncryptedBlobTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public void NewEncryptedBlobFromStream(byte[] bytes, CipherAlgorithm algorithm,
var tag = ms.Decode<EncryptedBlob.Payload>();
Assert.AreEqual(ILTagId.EncryptedBlob, tag.TagId);
Assert.AreEqual(algorithm, tag.Value.Cipher);
var clearBlob = tag.Value.DecryptBlob(TestFakeSigner.FixedKeysInstance, c => new AES256Engine());
var clearBlob = tag.Value.DecryptBlob(TestFakeSigner.FixedKeysInstance, _ => new AES256Engine());
Assert.IsNotNull(clearBlob);
Assert.AreEqual(data.Length, clearBlob.Length);
}
Expand Down
2 changes: 0 additions & 2 deletions InterlockLedger.Tags.UnitTests/ILTagTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@

namespace InterlockLedger.Tags
{

[TestFixture]
public class ILTagTests
{
Expand Down Expand Up @@ -145,6 +144,5 @@ public ulong DeserializeFrom(byte[] bytes) {
[TestCase("The fool doth think he is wise, but the wise man knows himself to be a fool.",
ExpectedResult = new byte[] { 17, 76, 0x54, 0x68, 0x65, 0x20, 0x66, 0x6F, 0x6F, 0x6C, 0x20, 0x64, 0x6F, 0x74, 0x68, 0x20, 0x74, 0x68, 0x69, 0x6E, 0x6B, 0x20, 0x68, 0x65, 0x20, 0x69, 0x73, 0x20, 0x77, 0x69, 0x73, 0x65, 0x2C, 0x20, 0x62, 0x75, 0x74, 0x20, 0x74, 0x68, 0x65, 0x20, 0x77, 0x69, 0x73, 0x65, 0x20, 0x6D, 0x61, 0x6E, 0x20, 0x6B, 0x6E, 0x6F, 0x77, 0x73, 0x20, 0x68, 0x69, 0x6D, 0x73, 0x65, 0x6C, 0x66, 0x20, 0x74, 0x6F, 0x20, 0x62, 0x65, 0x20, 0x61, 0x20, 0x66, 0x6F, 0x6F, 0x6C, 0x2E }, TestName = "SerializeILTagString 'The fool doth ...'")]
public byte[] SerializeILTagString(string value) => new ILTagString(value).EncodedBytes;

}
}
2 changes: 1 addition & 1 deletion InterlockLedger.Tags.UnitTests/SequenceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public void DeserializeHeterogenousILTagSequence(string firstElement, ulong seco

Assert.AreEqual(2, value.Length);
Assert.AreEqual(firstElement, value[0].AsString());
Assert.AreEqual(secondElement, (value[1] as ILTagILInt).Value);
Assert.AreEqual(secondElement, (value[1] as ILTagILInt)?.Value);
}

[TestCase(null, new byte[0], new byte[] { 22, 0 }, TestName = "Deserialize a Null Sequence")]
Expand Down
1 change: 0 additions & 1 deletion InterlockLedger.Tags.UnitTests/StringExtensionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,4 @@ public void WithSuffix() {
Assert.AreEqual("file.txt", "file. ".WithSuffix("txt"));
}
}

}
4 changes: 2 additions & 2 deletions InterlockLedger.Tags/Core/Metadata/DataField.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ public static ulong AsNumber(ILTag value) {

public string Enumerated(ulong number) {
try {
if (Enumeration is null || !Enumeration.Any())
if (Enumeration is null || Enumeration.Count == 0)
return "?";
if (!EnumerationAsFlags)
return Enumeration.ContainsKey(number) ? Enumeration[number].Name : "?";
Expand Down Expand Up @@ -197,7 +197,7 @@ protected override DataField FromBytes(byte[] bytes) {
SerializationVersion = (serVersion = s.HasBytes() ? s.DecodeUShort() : (ushort)0),
Description = (serVersion > 1) ? s.DecodeString() : null,
Enumeration = (serVersion > 2) ? DecodeEnumeration(s) : null,
EnumerationAsFlags = (serVersion > 3) ? s.DecodeBool() : false
EnumerationAsFlags = (serVersion > 3) && s.DecodeBool()
};
});
}
Expand Down
6 changes: 3 additions & 3 deletions InterlockLedger.Tags/Core/Metadata/DataModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ private static ILTag DeserializePartialFromJson(DataField field, object fieldVal
: throw new InvalidDataException($"Unknown tagId {field.TagId}");

private static bool ExpandEnumeration(Dictionary<ulong, DataField.Pair> oldEnumeration, Dictionary<ulong, DataField.Pair> newEnumeration)
=> oldEnumeration == null || oldEnumeration.Count == 0 || (newEnumeration != null && newEnumeration.Take(oldEnumeration.Count).SequenceEqual(oldEnumeration));
=> oldEnumeration == null || oldEnumeration.Count == 0 || (newEnumeration?.Take(oldEnumeration.Count).SequenceEqual(oldEnumeration) == true);

private static bool FindFieldInPath(string[] parts, int part, IEnumerable<DataField> fields) {
var name = parts[part];
Expand All @@ -163,7 +163,7 @@ private static bool FindFieldInPath(string[] parts, int part, IEnumerable<DataFi
}

private static ILTag FromPartialNavigable(Dictionary<string, object> json, ulong tagId, IEnumerable<DataField> dataFields, DataModel dataModel) {
if (json is null || !json.Any())
if (json is null || json.Count == 0)
return ILTagNull.Instance;
ushort version = 0;
var isVersioned = IsVersioned(dataFields);
Expand Down Expand Up @@ -209,7 +209,7 @@ private static Dictionary<string, object> ToJson(Span<byte> bytes, ulong expecte
if (field.HasSubFields) {
json[field.Name] = ToJson(bytes, field.TagId, field.SubDataFields, ref offset);
} else {
ILTag value = DecodePartial(field.TagId, bytes, ref offset);
var value = DecodePartial(field.TagId, bytes, ref offset);
json[field.Name] = value.AsJson;
if (field.IsEnumeration && !value.IsNull)
json[$"__{field.Name}__"] = field.Enumerated(value);
Expand Down
4 changes: 2 additions & 2 deletions InterlockLedger.Tags/Core/Tags/ILTag.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public abstract class ILTag : ITag
[JsonIgnore]
public bool IsNull => TagId == ILTagId.Null;

public ulong TagId { get; private set; }
public ulong TagId { get; }

public static ILTag DeserializeFrom(Stream s) {
if (s.HasBytes()) {
Expand Down Expand Up @@ -117,7 +117,7 @@ public Stream SerializeInto(Stream s) {

private static readonly Dictionary<ulong, (Func<Stream, ILTag> fromStream, Func<object, ILTag> fromJson)> _deserializers
= new Dictionary<ulong, (Func<Stream, ILTag> fromStream, Func<object, ILTag> fromJson)> {
[ILTagId.Null] = (s => ILTagNull.Instance, o => ILTagNull.Instance),
[ILTagId.Null] = (_ => ILTagNull.Instance, _ => ILTagNull.Instance),
[ILTagId.Bool] = (s => s.ReadSingleByte() != 0 ? ILTagBool.True : ILTagBool.False, o => (bool)o ? ILTagBool.True : ILTagBool.False),
[ILTagId.Int8] = (s => new ILTagInt8(s, ILTagId.Int8), o => new ILTagInt8(Convert.ToSByte(o))),
[ILTagId.UInt8] = (s => new ILTagUInt8(s, ILTagId.UInt8), o => new ILTagUInt8(Convert.ToByte(o))),
Expand Down
2 changes: 1 addition & 1 deletion InterlockLedger.Tags/Core/Tags/ILTagAbstractDictionary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public abstract class ILTagAbstractDictionary<T> : ILTagExplicit<Dictionary<stri
public T this[string key] => Value?[key];

public override bool Equals(object obj)
=> obj is ILTag other ? EncodedBytes.SequenceEqual(other.EncodedBytes) : false;
=> obj is ILTag other && EncodedBytes.SequenceEqual(other.EncodedBytes);

public override int GetHashCode() => Value?.GetHashCode() ?? 0;

Expand Down
2 changes: 1 addition & 1 deletion InterlockLedger.Tags/Core/Tags/ILTagBool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE

namespace InterlockLedger.Tags
{
public class ILTagBool : ILTagImplicit<bool>
public sealed class ILTagBool : ILTagImplicit<bool>
{
public static readonly ILTagBool False = new ILTagBool(false);
public static readonly ILTagBool True = new ILTagBool(true);
Expand Down
2 changes: 1 addition & 1 deletion InterlockLedger.Tags/Core/Tags/ILTagNull.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE

namespace InterlockLedger.Tags
{
public class ILTagNull : ILTag
public sealed class ILTagNull : ILTag
{
public static readonly ILTagNull Instance = new ILTagNull();

Expand Down
2 changes: 1 addition & 1 deletion InterlockLedger.Tags/Core/Types/LimitedRange.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public static LimitedRange Resolve(string text) {

public bool Contains(LimitedRange other) => Contains(other.Start) && Contains(other.End);

public override bool Equals(object obj) => obj is LimitedRange && Equals((LimitedRange)obj);
public override bool Equals(object obj) => obj is LimitedRange limitedRange && Equals(limitedRange);

public bool Equals(LimitedRange other) => End == other.End && Start == other.Start;

Expand Down
2 changes: 1 addition & 1 deletion InterlockLedger.Tags/Crypto/AES256/AES256Engine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public byte[] Decrypt(byte[] cipherData, byte[] key, byte[] iv) {
throw new ArgumentNullException(nameof(cipherData));
if (key is null)
throw new ArgumentNullException(nameof(key));
return Decrypt(cipherData, readHeader: (s) => (key, iv));
return Decrypt(cipherData, readHeader: _ => (key, iv));
}

public byte[] Decrypt(byte[] cipherData, Func<MemoryStream, (byte[] key, byte[] iv)> readHeader) {
Expand Down
1 change: 0 additions & 1 deletion InterlockLedger.Tags/Crypto/Types/Algorithm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
*
******************************************************************************************************************************/


using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

Expand Down
1 change: 0 additions & 1 deletion InterlockLedger.Tags/Crypto/Types/Keys/ExportedKeyFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
*
******************************************************************************************************************************/


namespace InterlockLedger.Tags
{
public class ExportedKeyFile
Expand Down
18 changes: 9 additions & 9 deletions InterlockLedger.Tags/Crypto/Types/Keys/InterlockKey.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public InterlockKey(ISigningKey key)
: this(new InterlockKeyParts(key.Purposes, key.AppId, key.SpecificActions, key.Name, key.Description, key.CurrentPublicKey, key.Strength, key.Id)) {
}

public bool AllActions => Value.Actionable && (SpecificActions == null || !SpecificActions.Any());
public bool AllActions => Value.Actionable && SpecificActions.None();
public ulong AppId => Value.AppId;
public string Description => Value.Description;
public BaseKeyId Id => Value.Id;
Expand All @@ -42,7 +42,7 @@ public InterlockKey(ISigningKey key)
public IEnumerable<ulong> SpecificActions => Value.SpecificActions;
public ushort Version => Value.Version;

public bool CanAct(ulong appId, ulong actionId) => appId == AppId && Purposes.Contains(KeyPurpose.Action) && (SpecificActions == null || SpecificActions.Contains(actionId));
public bool CanAct(ulong appId, ulong actionId) => appId == AppId && Purposes.Contains(KeyPurpose.Action) && (SpecificActions?.Contains(actionId) != false);

public override bool Equals(object obj) => Equals(obj as InterlockKey);

Expand Down Expand Up @@ -121,19 +121,19 @@ public InterlockKeyParts(KeyPurpose[] purposes, ulong appId, IEnumerable<ulong>
AppId = appId;
Strength = strength;
SpecificActions = actionIds ?? Enumerable.Empty<ulong>();
Identity = new KeyId(TagHash.HashSha256Of(Hashable));
Identity = new KeyId(TagHash.HashSha256Of(_hashable));
Id = keyId ?? Identity;
}

public bool Actionable => Purposes.Contains(KeyPurpose.Action);

public string ToShortString() => $@"{Name.Safe().PadRight(58)} [{DisplayablePurposes}] {ActionsFor} ";
public string ToShortString() => $"{Name.Safe().PadRight(58)} [{_displayablePurposes}] {_actionsFor} ";

public override string ToString() =>
$@"-- Key '{Name}' - {Description}
++ Id: {Id}
++ using {PublicKey.Algorithm} [{PublicKey.TextualRepresentation}]
++ with purposes: {DisplayablePurposes} {ActionsFor.ToLowerInvariant()}
++ with purposes: {_displayablePurposes} {_actionsFor.ToLowerInvariant()}
++ from: {Identity}
++ with strength {Strength}";

Expand All @@ -144,11 +144,11 @@ internal ulong[] PurposesAsUlongs {
set => Purposes = value?.Select(u => (KeyPurpose)u).ToArray();
}

private string ActionsFor => Actionable ? AppAndActions() : string.Empty;
private string _actionsFor => Actionable ? AppAndActions() : string.Empty;

private string DisplayablePurposes => Purposes.ToStringAsList();
private string _displayablePurposes => Purposes.ToStringAsList();

private byte[] Hashable => PublicKey.EncodedBytes.Append(ActionsFor.UTF8Bytes()).Append(PurposesAsILInts.EncodedBytes);
private byte[] _hashable => PublicKey.EncodedBytes.Append(_actionsFor.UTF8Bytes()).Append(PurposesAsILInts.EncodedBytes);

private static ILTagILInt[] AsILInts(KeyPurpose[] purposes) => purposes?.Select(p => new ILTagILInt((ulong)p)).ToArray();

Expand All @@ -162,4 +162,4 @@ private string AppAndActions() {
return $"App #{AppId} {(actions.SafeAny() ? $"Action{plural} {actions.WithCommas(noSpaces: true)}" : "All Actions")}";
}
}
}
}
7 changes: 3 additions & 4 deletions InterlockLedger.Tags/Crypto/Types/Keys/RSA/RSAHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,13 @@
using System;
using System.IO;
using System.Security.Cryptography;
using InterlockLedger.Tags;

namespace InterlockLedger.Tags
{
public static class RSAHelper
{
public static TagRSAParameters CreateNewRSAParameters(KeyStrength strength) {
var keySize = RSAExtensions.KeySize(strength);
var keySize = strength.RSAKeySize();
using var provider = new RSACryptoServiceProvider(keySize);
return new TagRSAParameters(provider.ExportParameters(true));
}
Expand Down Expand Up @@ -57,8 +56,8 @@ public static byte[] HashAndSignBytes(byte[] dataToSign, RSAParameters key) {
if (retries-- <= 0)
throw new InterlockLedgerCryptographicException($"Failed to sign data with current parameters after {_maxRetries} retries", e);
}

}

public static bool Verify(byte[] dataToVerify, TagSignature signature, RSAParameters parameters) {
if (signature is null)
throw new ArgumentNullException(nameof(signature));
Expand All @@ -78,4 +77,4 @@ public static bool Verify(byte[] dataToVerify, TagSignature signature, RSAParame

private const int _maxRetries = 3;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,6 @@ public SigningKeyUpdatingPolicy(ulong maxSignaturesWithTheSameKey, TimeSpan maxA
}

public TimeSpan MaxAgeOfSignatureKey { get; private set; }
public ulong MaxSignaturesWithTheSameKey { get; private set; }
public ulong MaxSignaturesWithTheSameKey { get; }
}
}
2 changes: 1 addition & 1 deletion InterlockLedger.Tags/Extensions/ArrayOfByteExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public static string Chunked(this byte[] bytes, int length) {
var start = 0;
while (start < value.Length) {
var howMany = Math.Min(length, value.Length - start);
sb.Append(value.Substring(start, howMany)).Append(Environment.NewLine);
sb.Append(value, start, howMany).Append(Environment.NewLine);
start += length;
}
return sb.ToString();
Expand Down
75 changes: 0 additions & 75 deletions InterlockLedger.Tags/Extensions/IEnumerableExtensions.cs

This file was deleted.

Loading

0 comments on commit 67ad493

Please sign in to comment.