Skip to content

Commit

Permalink
refactor check if address is pre allocated.
Browse files Browse the repository at this point in the history
  • Loading branch information
PawelPawelec-RDX committed Oct 11, 2024
1 parent 36e75c6 commit 1bb006a
Show file tree
Hide file tree
Showing 9 changed files with 159 additions and 134 deletions.
1 change: 1 addition & 0 deletions babylon-gateway.sln.DotSettings
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/UserDictionary/Words/=Bech/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=mempool/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Querier/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=radixfoundation/@EntryIndexedValue">True</s:Boolean>
Expand Down
5 changes: 5 additions & 0 deletions src/RadixDlt.NetworkGateway.Abstractions/EntityAddress.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
* permissions under this License.
*/

using RadixDlt.NetworkGateway.Abstractions.Network;
using System.Diagnostics;

namespace RadixDlt.NetworkGateway.Abstractions;
Expand All @@ -82,6 +83,8 @@ private EntityAddress(string address)

public bool IsAccount => _address.StartsWith("account_");

public bool IsIdentity => _address.StartsWith("identity_");

public bool IsResource => _address.StartsWith("resource_");

public static implicit operator string(EntityAddress ra) => ra._address;
Expand All @@ -92,4 +95,6 @@ public override string ToString()
{
return _address;
}

public DecodedRadixAddress Decode() => RadixAddressCodec.DecodeEntityAddress(_address);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/* Copyright 2021 Radix Publishing Ltd incorporated in Jersey (Channel Islands).
*
* Licensed under the Radix License, Version 1.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at:
*
* radixfoundation.org/licenses/LICENSE-v1
*
* The Licensor hereby grants permission for the Canonical version of the Work to be
* published, distributed and used under or by reference to the Licensor’s trademark
* Radix ® and use of any unregistered trade names, logos or get-up.
*
* The Licensor provides the Work (and each Contributor provides its Contributions) on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
* including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT,
* MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE.
*
* Whilst the Work is capable of being deployed, used and adopted (instantiated) to create
* a distributed ledger it is your responsibility to test and validate the code, together
* with all logic and performance of that code under all foreseeable scenarios.
*
* The Licensor does not make or purport to make and hereby excludes liability for all
* and any representation, warranty or undertaking in any form whatsoever, whether express
* or implied, to any entity or person, including any representation, warranty or
* undertaking, as to the functionality security use, value or other characteristics of
* any distributed ledger nor in respect the functioning or value of any tokens which may
* be created stored or transferred using the Work. The Licensor does not warrant that the
* Work or any use of the Work complies with any law or regulation in any territory where
* it may be implemented or used or that it will be appropriate for any specific purpose.
*
* Neither the licensor nor any current or former employees, officers, directors, partners,
* trustees, representatives, agents, advisors, contractors, or volunteers of the Licensor
* shall be liable for any direct or indirect, special, incidental, consequential or other
* losses of any kind, in tort, contract or otherwise (including but not limited to loss
* of revenue, income or profits, or loss of use or data, or loss of reputation, or loss
* of any economic or other opportunity of whatsoever nature or howsoever arising), arising
* out of or in connection with (without limitation of any use, misuse, of any ledger system
* or use made or its functionality or any performance or operation of any code or protocol
* caused by bugs or programming or logic errors or otherwise);
*
* A. any offer, purchase, holding, use, sale, exchange or transmission of any
* cryptographic keys, tokens or assets created, exchanged, stored or arising from any
* interaction with the Work;
*
* B. any failure in a transmission or loss of any token or assets keys or other digital
* artefacts due to errors in transmission;
*
* C. bugs, hacks, logic errors or faults in the Work or any communication;
*
* D. system software or apparatus including but not limited to losses caused by errors
* in holding or transmitting tokens by any third-party;
*
* E. breaches or failure of security including hacker attacks, loss or disclosure of
* password, loss of private key, unauthorised use or misuse of such passwords or keys;
*
* F. any losses including loss of anticipated savings or other benefits resulting from
* use of the Work or any changes to the Work (however implemented).
*
* You are solely responsible for; testing, validating and evaluation of all operation
* logic, functionality, security and appropriateness of using the Work for any commercial
* or non-commercial purpose and for any reproduction or redistribution by You of the
* Work. You assume all risks associated with Your use of the Work and the exercise of
* permissions under this License.
*/

namespace RadixDlt.NetworkGateway.Abstractions.Network;

public sealed record DecodedRadixAddress(string Hrp, byte[] Data, Bech32Codec.Variant Variant)
{
private const byte Secp256kPreAllocatedAccountPrefix = 209;
private const byte Secp256kPreAllocatedIdentityPrefix = 210;
private const byte Ed25519PreAllocatedAccountPrefix = 81;
private const byte Ed25519PreAllocatedIdentityPrefix = 82;

public bool IsPreAllocated() => IsPreAllocatedAccountAddress() || IsPreAllocatedIdentityAddress();

public bool IsSecp256k() => DiscriminatorByte is Secp256kPreAllocatedAccountPrefix or Secp256kPreAllocatedIdentityPrefix;

public bool IsEd25519() => DiscriminatorByte is Ed25519PreAllocatedAccountPrefix or Ed25519PreAllocatedIdentityPrefix;

public bool IsPreAllocatedAccountAddress() => DiscriminatorByte is Secp256kPreAllocatedAccountPrefix or Ed25519PreAllocatedAccountPrefix;

public bool IsPreAllocatedIdentityAddress() => DiscriminatorByte is Secp256kPreAllocatedIdentityPrefix or Ed25519PreAllocatedIdentityPrefix;

public byte DiscriminatorByte => Data[0];

public byte[] AddressBytes => Data[1..];

public override string ToString()
{
return RadixAddressCodec.Encode(Hrp, Data);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,35 +62,30 @@
* permissions under this License.
*/

// ReSharper disable CommentTypo
// ReSharper disable StringLiteralTypo
// ReSharper disable IdentifierTypo
/* The above is a fix for ReShaper not liking the work "Bech" */

using System;

namespace RadixDlt.NetworkGateway.Abstractions.Network;

public sealed record DecodedRadixAddress(string Hrp, byte[] Data, Bech32Codec.Variant Variant)
{
public byte DiscriminatorByte => Data[0];

public byte[] AddressBytes => Data[1..];

public override string ToString()
{
return RadixAddressCodec.Encode(Hrp, Data);
}
}

public static class RadixAddressCodec
{
public static string Encode(string hrp, ReadOnlySpan<byte> addressData)
{
return Bech32Codec.Encode(hrp, EncodeAddressDataInBase32(addressData), Bech32Codec.Variant.Bech32M);
}

public static DecodedRadixAddress Decode(string encoded)
public static DecodedRadixAddress DecodeEntityAddress(string encoded)
{
var decoded = Decode(encoded);

if (decoded.Data.Length != 30)
{
throw new AddressException($"Entity address is expected to be 30 bytes in length. But was {decoded.Data.Length}");
}

return decoded;
}

private static DecodedRadixAddress Decode(string encoded)
{
var (hrp, rawBase32Data, variant) = Bech32Codec.Decode(encoded);
var addressData = DecodeBase32IntoAddressData(rawBase32Data);
Expand All @@ -102,7 +97,7 @@ public static DecodedRadixAddress Decode(string encoded)

if (variant != Bech32Codec.Variant.Bech32M)
{
throw new AddressException("Only Bech32M addresses are supported");
throw new AddressException($"Only Bech32M addresses are supported, decoded variant: {variant}");
}

return new DecodedRadixAddress(hrp, addressData, variant);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
*/

using FluentValidation;
using RadixDlt.NetworkGateway.Abstractions;
using RadixDlt.NetworkGateway.Abstractions.Network;
using System;

Expand All @@ -81,7 +82,7 @@ public RadixAddressValidator(INetworkConfigurationProvider networkConfigurationP
try
{
var networkHrpSuffix = networkConfigurationProvider.GetNetworkConfiguration().GetAwaiter().GetResult().HrpSuffix;
var decodedAddress = RadixAddressCodec.Decode(address);
var decodedAddress = ((EntityAddress)address).Decode();

if (!decodedAddress.Hrp.EndsWith(networkHrpSuffix, StringComparison.OrdinalIgnoreCase))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,30 +74,28 @@ internal static class ManifestAddressesExtractor
{
internal record PresentedProof(EntityAddress AccountAddress, EntityAddress ResourceAddress);

internal record AddressWithEntityType(ToolkitModel.EntityType EntityType, EntityAddress Address);

internal record ManifestAddresses(
List<EntityAddress> PackageAddresses,
List<EntityAddress> ComponentAddresses,
List<EntityAddress> ResourceAddresses,
List<AddressWithEntityType> AccountAddresses,
List<AddressWithEntityType> AccountsRequiringAuth,
List<AddressWithEntityType> AccountsWithdrawnFrom,
List<AddressWithEntityType> AccountsDepositedInto,
List<AddressWithEntityType> IdentityAddresses,
List<AddressWithEntityType> IdentitiesRequiringAuth,
List<EntityAddress> AccountAddresses,
List<EntityAddress> AccountsRequiringAuth,
List<EntityAddress> AccountsWithdrawnFrom,
List<EntityAddress> AccountsDepositedInto,
List<EntityAddress> IdentityAddresses,
List<EntityAddress> IdentitiesRequiringAuth,
List<PresentedProof> PresentedProofs)
{
public List<EntityAddress> All() =>
PackageAddresses
.Concat(ComponentAddresses)
.Concat(ResourceAddresses)
.Concat(AccountAddresses.Select(x => x.Address))
.Concat(AccountsRequiringAuth.Select(x => x.Address))
.Concat(AccountsWithdrawnFrom.Select(x => x.Address))
.Concat(AccountsDepositedInto.Select(x => x.Address))
.Concat(IdentityAddresses.Select(x => x.Address))
.Concat(IdentitiesRequiringAuth.Select(x => x.Address))
.Concat(AccountAddresses)
.Concat(AccountsRequiringAuth)
.Concat(AccountsWithdrawnFrom)
.Concat(AccountsDepositedInto)
.Concat(IdentityAddresses)
.Concat(IdentitiesRequiringAuth)
.Concat(PresentedProofs.Select(x => x.AccountAddress))
.Concat(PresentedProofs.Select(x => x.ResourceAddress))
.Distinct()
Expand All @@ -111,10 +109,10 @@ public static ManifestAddresses ExtractAddresses(ToolkitModel.TransactionManifes
var manifestSummary = manifest.Summary(networkId);

var presentedProofs = ExtractProofs(manifestSummary.presentedProofs);
var accountsRequiringAuth = manifestSummary.accountsRequiringAuth.Select(x => new AddressWithEntityType(x.EntityType(), (EntityAddress)x.AddressString())).ToList();
var accountsWithdrawnFrom = manifestSummary.accountsWithdrawnFrom.Select(x => new AddressWithEntityType(x.EntityType(), (EntityAddress)x.AddressString())).ToList();
var accountsDepositedInto = manifestSummary.accountsDepositedInto.Select(x => new AddressWithEntityType(x.EntityType(), (EntityAddress)x.AddressString())).ToList();
var identitiesRequiringAuth = manifestSummary.identitiesRequiringAuth.Select(x => new AddressWithEntityType(x.EntityType(), (EntityAddress)x.AddressString())).ToList();
var accountsRequiringAuth = manifestSummary.accountsRequiringAuth.Select(x => (EntityAddress)x.AddressString()).ToList();
var accountsWithdrawnFrom = manifestSummary.accountsWithdrawnFrom.Select(x => (EntityAddress)x.AddressString()).ToList();
var accountsDepositedInto = manifestSummary.accountsDepositedInto.Select(x => (EntityAddress)x.AddressString()).ToList();
var identitiesRequiringAuth = manifestSummary.identitiesRequiringAuth.Select(x => (EntityAddress)x.AddressString()).ToList();

var packageAddresses = allAddresses
.Where(x => x.Key == ToolkitModel.EntityType.GlobalPackage)
Expand All @@ -137,7 +135,7 @@ public static ManifestAddresses ExtractAddresses(ToolkitModel.TransactionManifes
is ToolkitModel.EntityType.GlobalAccount
or ToolkitModel.EntityType.GlobalVirtualEd25519Account
or ToolkitModel.EntityType.GlobalVirtualSecp256k1Account)
.SelectMany(x => x.Value.Select(y => new AddressWithEntityType(y.EntityType(), (EntityAddress)y.AddressString())))
.SelectMany(x => x.Value.Select(y => (EntityAddress)y.AddressString()))
.ToList();

var identityAddresses = allAddresses
Expand All @@ -146,7 +144,7 @@ or ToolkitModel.EntityType.GlobalVirtualEd25519Account
is ToolkitModel.EntityType.GlobalIdentity
or ToolkitModel.EntityType.GlobalVirtualEd25519Identity
or ToolkitModel.EntityType.GlobalVirtualSecp256k1Identity)
.SelectMany(x => x.Value.Select(y => new AddressWithEntityType(y.EntityType(), (EntityAddress)y.AddressString())))
.SelectMany(x => x.Value.Select(y => (EntityAddress)y.AddressString()))
.ToList();

return new ManifestAddresses(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -213,9 +213,9 @@ private IEnumerable<LedgerTransactionMarker> CreateMarkersForManifestAddresses()
});
}

foreach (var addressWithEntityType in extractedAddresses.AccountsRequiringAuth)
foreach (var entityAddress in extractedAddresses.AccountsRequiringAuth)
{
if (_referencedEntities.TryGet(addressWithEntityType.Address, out var referencedEntity))
if (_referencedEntities.TryGet(entityAddress, out var referencedEntity))
{
ledgerTransactionMarkersToAdd.Add(
new ManifestAddressLedgerTransactionMarker
Expand All @@ -226,15 +226,15 @@ private IEnumerable<LedgerTransactionMarker> CreateMarkersForManifestAddresses()
EntityId = referencedEntity.DatabaseId,
});
}
else if (addressWithEntityType.EntityType is not (ToolkitModel.EntityType.GlobalVirtualEd25519Account or ToolkitModel.EntityType.GlobalVirtualSecp256k1Account))
else if (!entityAddress.Decode().IsPreAllocatedAccountAddress())
{
throw new UnreachableException($"Entity: {addressWithEntityType.Address} was not present in referenced entities dictionary.");
throw new UnreachableException($"Entity: {entityAddress} was not present in referenced entities dictionary.");
}
}

foreach (var addressWithEntityType in extractedAddresses.AccountsDepositedInto)
foreach (var entityAddress in extractedAddresses.AccountsDepositedInto)
{
if (_referencedEntities.TryGet(addressWithEntityType.Address, out var referencedEntity))
if (_referencedEntities.TryGet(entityAddress, out var referencedEntity))
{
ledgerTransactionMarkersToAdd.Add(
new ManifestAddressLedgerTransactionMarker
Expand All @@ -245,15 +245,15 @@ private IEnumerable<LedgerTransactionMarker> CreateMarkersForManifestAddresses()
EntityId = referencedEntity.DatabaseId,
});
}
else if (addressWithEntityType.EntityType is not (ToolkitModel.EntityType.GlobalVirtualEd25519Account or ToolkitModel.EntityType.GlobalVirtualSecp256k1Account))
else if (!entityAddress.Decode().IsPreAllocatedAccountAddress())
{
throw new UnreachableException($"Entity: {addressWithEntityType.Address} was not present in referenced entities dictionary.");
throw new UnreachableException($"Entity: {entityAddress} was not present in referenced entities dictionary.");
}
}

foreach (var addressWithEntityType in extractedAddresses.AccountsWithdrawnFrom)
foreach (var entityAddress in extractedAddresses.AccountsWithdrawnFrom)
{
if (_referencedEntities.TryGet(addressWithEntityType.Address, out var referencedEntity))
if (_referencedEntities.TryGet(entityAddress, out var referencedEntity))
{
ledgerTransactionMarkersToAdd.Add(
new ManifestAddressLedgerTransactionMarker
Expand All @@ -264,9 +264,9 @@ private IEnumerable<LedgerTransactionMarker> CreateMarkersForManifestAddresses()
EntityId = referencedEntity.DatabaseId,
});
}
else if (addressWithEntityType.EntityType is not (ToolkitModel.EntityType.GlobalVirtualEd25519Account or ToolkitModel.EntityType.GlobalVirtualSecp256k1Account))
else if (!entityAddress.Decode().IsPreAllocatedAccountAddress())
{
throw new UnreachableException($"Entity: {addressWithEntityType.Address} was not present in referenced entities dictionary.");
throw new UnreachableException($"Entity: {entityAddress} was not present in referenced entities dictionary.");
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ public async Task<TEntity> GetEntity<TEntity>(EntityAddress address, GatewayApiS

if (entity == null)
{
entity = await TryResolveAsPreAllocatedEntity(address);
entity = TryResolveAsPreAllocatedEntity(address);

if (entity == null)
{
Expand Down Expand Up @@ -188,7 +188,7 @@ public async Task<ICollection<Entity>> GetEntities(List<EntityAddress> addresses

foreach (var address in addresses.Except(entities.Keys))
{
var preAllocatedEntity = await TryResolveAsPreAllocatedEntity(address);
var preAllocatedEntity = TryResolveAsPreAllocatedEntity(address);

if (preAllocatedEntity != null)
{
Expand All @@ -199,14 +199,14 @@ public async Task<ICollection<Entity>> GetEntities(List<EntityAddress> addresses
return entities.Values;
}

private async Task<Entity?> TryResolveAsPreAllocatedEntity(EntityAddress address)
private static Entity? TryResolveAsPreAllocatedEntity(EntityAddress address)
{
if (await _preAllocatedEntityDataProvider.IsPreAllocatedAccountAddress(address))
if (address.IsAccount && address.Decode().IsPreAllocatedAccountAddress())
{
return new PreAllocatedAccountComponentEntity(address);
}

if (await _preAllocatedEntityDataProvider.IsPreAllocatedIdentityAddress(address))
if (address.IsIdentity && address.Decode().IsPreAllocatedIdentityAddress())
{
return new PreAllocatedIdentityEntity(address);
}
Expand Down
Loading

0 comments on commit 1bb006a

Please sign in to comment.