Skip to content

Commit

Permalink
Feat/dapp operations and signing (#63)
Browse files Browse the repository at this point in the history
* Sample with operation_request and signing done;

* Improved dapp sample; Extended supported networks;

* 1.0.8;
  • Loading branch information
k-karuna authored Oct 18, 2022
1 parent e7ca027 commit 97a6da1
Show file tree
Hide file tree
Showing 11 changed files with 159 additions and 38 deletions.
Binary file added .DS_Store
Binary file not shown.
Binary file added Beacon.Sdk.Sample.Dapp/.DS_Store
Binary file not shown.
8 changes: 5 additions & 3 deletions Beacon.Sdk.Sample.Dapp/Beacon.Sdk.Sample.Dapp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Serilog" Version="2.11.0-dev-01371"/>
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0"/>
<PackageReference Include="Serilog.Sinks.Console" Version="4.0.1-dev-00879"/>
<PackageReference Include="Serilog" Version="2.11.0-dev-01371" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.0.1-dev-00879" />
<PackageReference Include="Netezos" Version="2.6.2" />
<PackageReference Include="Beacon.Sdk" Version="1.0.8" />
</ItemGroup>

</Project>
1 change: 0 additions & 1 deletion Beacon.Sdk.Sample.Dapp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ internal class Program
private static async Task<int> Main(string[] args)
{
await Sample.Run();
Console.ReadLine();
return 0;
}
}
Expand Down
132 changes: 115 additions & 17 deletions Beacon.Sdk.Sample.Dapp/Sample.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,29 @@ namespace Beacon.Sdk.Sample.Dapp;

using System.Runtime.InteropServices;
using Beacon;
using Beacon.Operation;
using Beacon.Permission;
using Beacon.Sign;
using BeaconClients;
using BeaconClients.Abstract;
using Core.Domain.Services;
using Microsoft.Extensions.Logging;
using Netezos.Keys;
using Newtonsoft.Json.Linq;
using Serilog;
using Serilog.Extensions.Logging;
using Hex = Netezos.Encoding.Hex;
using ILogger = Serilog.ILogger;

public class Sample
{
const string DbPath = "dapp-sample.db";
private const string TzButtonColorsContract = "KT1RPW5kTX6WFxg8JK34rGEU24gqEEudyfvz";
private const string TokenId = "925";

private const string PayloadToSign =
"05010000008654657a6f73205369676e6564204d6573736167653a20436f6e6669726d696e67206d79206964656e7469747920617320747a31524445344a64556f37336278323363776a72393767446b6350363362344e664744206f6e206f626a6b742e636f6d2c207369673a6f5252764f6374513638726463457555394965782d72496b45516d46426652";

private DappBeaconClient BeaconDappClient { get; set; }
private ILogger Logger { get; set; }

Expand Down Expand Up @@ -45,22 +56,79 @@ public async Task Run()

string pairingRequestQrData = await BeaconDappClient.GetPairingRequestInfo();
Logger.Information("Pairing data is Is\n{Data}", pairingRequestQrData);
var activePeer = BeaconDappClient.GetActivePeer().Result;
var activePeer = await BeaconDappClient.GetActivePeer();
if (activePeer == null) return;

var permissions = await BeaconDappClient
.PermissionInfoRepository
.TryReadBySenderIdAsync(activePeer.SenderId);
if (permissions == null) return;

var permissionsString = permissions?.Scopes.Aggregate(string.Empty,
(res, scope) => res + $"{scope}, ") ?? string.Empty;

var pubKey = PubKey.FromBase58(permissions!.PublicKey);

Logger.Information("We have active peer {Peer} with permissions {Permissions} and address {Address}",
activePeer.Name, permissionsString, pubKey.Address);

var requestCommand = true;

if (activePeer != null)
while (requestCommand)
{
var permissions = BeaconDappClient
.PermissionInfoRepository
.TryReadBySenderIdAsync(activePeer.SenderId)
.Result;

var permissionsString = permissions?.Scopes.Aggregate(string.Empty,
(res, scope) => res + $"{scope}, ") ?? string.Empty;

Logger.Information("We have active peer {Peer} with permissions {Permissions}",
activePeer.Name, permissionsString);
var command = Console.ReadLine();

switch (command)
{
case "exit":
{
requestCommand = false;
break;
}
case "sign":
{
var signPayloadRequest = new SignPayloadRequest(
id: KeyPairService.CreateGuid(),
version: Constants.BeaconVersion,
senderId: BeaconDappClient.SenderId,
signingType: SignPayloadType.raw,
payload: PayloadToSign,
sourceAddress: pubKey.Address);

await BeaconDappClient.SendResponseAsync(activePeer.SenderId, signPayloadRequest);
break;
}
case "operation":
{
var operationDetails = new List<PartialTezosTransactionOperation>
{
new(
Amount: "0",
Destination: TzButtonColorsContract,
Parameters: new JObject
{
["entrypoint"] = "set_color",
["value"] = new JObject
{
["int"] = TokenId
}
})
};

var operationRequest = new OperationRequest(
type: BeaconMessageType.operation_request,
version: Constants.BeaconVersion,
id: KeyPairService.CreateGuid(),
senderId: BeaconDappClient.SenderId,
network: permissions.Network,
operationDetails: operationDetails,
sourceAddress: pubKey.Address);

await BeaconDappClient.SendResponseAsync(activePeer.SenderId, operationRequest);
break;
}
}
}

}

private async void OnBeaconDappClientMessageReceived(object? sender, BeaconMessageEventArgs e)
Expand Down Expand Up @@ -96,7 +164,7 @@ private async void OnBeaconDappClientMessageReceived(object? sender, BeaconMessa
await BeaconDappClient.SendResponseAsync(peer.SenderId, permissionRequest);
return;
}

var message = e.Request;
switch (message.Type)
{
Expand All @@ -107,15 +175,45 @@ private async void OnBeaconDappClientMessageReceived(object? sender, BeaconMessa

var permissionsString = permissionResponse.Scopes.Aggregate(string.Empty,
(res, scope) => res + $"{scope}, ");

Logger.Information("{DappName} received permissions {Permissions} from {From} with address {Address} and public key {Pk}",

Logger.Information(
"{DappName} received permissions {Permissions} from {From} with address {Address} and public key {Pk}",
BeaconDappClient.AppName,
permissionsString,
permissionResponse.AppMetadata.Name,
permissionResponse.Address,
permissionResponse.PublicKey);
break;
};
}

case BeaconMessageType.operation_response:
{
if (message is not OperationResponse operationResponse)
return;

Logger.Debug("Operation completed with transaction hash {Tx}", operationResponse.TransactionHash);
break;
}

case BeaconMessageType.sign_payload_response:
{
if (message is not SignPayloadResponse signPayloadResponse)
return;

var senderPermissions = await BeaconDappClient
.PermissionInfoRepository
.TryReadBySenderIdAsync(signPayloadResponse.SenderId);
if (senderPermissions == null) return;

var pubKey = PubKey.FromBase58(senderPermissions.PublicKey);
var payloadBytes = Hex.Parse(PayloadToSign);
var verified = pubKey.Verify(payloadBytes, signPayloadResponse.Signature);
var stringVerifyResult = verified ? "Successfully" : "Unsuccessfully";

Logger.Information("{Result} signed payload by {Sender}, signature is {Signature}",
stringVerifyResult, senderPermissions.AppMetadata.Name, signPayloadResponse.Signature);
break;
}
}
}
}
Binary file added Beacon.Sdk/.DS_Store
Binary file not shown.
3 changes: 2 additions & 1 deletion Beacon.Sdk/Beacon.Sdk.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
<Authors>Mikhail Tatarenko</Authors>
<Product>Beacon.Sdk</Product>
<Description>Beacon .NET SDK for Tezos wallet developers to seamlessly connect to multiple dApps.</Description>
<Version>1.0.7</Version>
<Version>1.0.8</Version>
<Copyright>Copyright © Baking Bad 2019-2022</Copyright>
<Nullable>enable</Nullable>
<TargetFramework>netstandard2.0</TargetFramework>
Expand All @@ -27,6 +27,7 @@
<PackageReference Include="Netezos" Version="2.4.6" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="Sodium.Core" Version="1.3.1" />
<PackageReference Include="libsodium" Version="1.0.18.2" />
<PackageReference Include="Matrix.Sdk" Version="1.0.5" />
</ItemGroup>
</Project>
5 changes: 5 additions & 0 deletions Beacon.Sdk/Beacon/Permission/NetworkType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,17 @@ namespace Beacon.Sdk.Beacon.Permission
public enum NetworkType
{
mainnet,
ghostnet, // Long running testnet
mondaynet, // Testnet, resets every monday
dailynet, // Testnet, resets every day
delphinet,
edonet,
florencenet,
granadanet,
hangzhounet,
ithacanet,
jakartanet,
kathmandunet,
custom
}
}
8 changes: 5 additions & 3 deletions Beacon.Sdk/BeaconClients/DappBeaconClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -126,15 +126,17 @@ private async Task OnP2PMessagesReceived(object? sender, P2PMessageEventArgs e)
}

foreach (string message in e.Messages)
await HandleMessage(message);
await HandleReceivedMessage(message);
}

private async Task HandleMessage(string message)
private async Task HandleReceivedMessage(string message)
{
(_, BaseBeaconMessage requestMessage) =
_requestMessageHandler.Handle(message, SenderId);

await _responseMessageHandler.Handle(requestMessage, requestMessage.SenderId);
if (requestMessage.Type == BeaconMessageType.permission_response)
await _responseMessageHandler.Handle(requestMessage, requestMessage.SenderId);

OnBeaconMessageReceived?.Invoke(this, new BeaconMessageEventArgs(requestMessage.SenderId, requestMessage));
}

Expand Down
28 changes: 15 additions & 13 deletions Beacon.Sdk/Core/Domain/RequestMessageHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,11 @@ public RequestMessageHandler(IAppMetadataRepository appMetadataRepository,
BeaconMessageType.permission_request => (ack, HandlePermissionRequest(message)),
BeaconMessageType.operation_request => (ack, HandleOperationRequest(message)),
BeaconMessageType.sign_payload_request => (ack, HandleSignPayloadRequest(message)),


// todo: remove this to response handler
BeaconMessageType.permission_response => (ack, HandlePermissionResponse(message)),
BeaconMessageType.operation_response => (ack, HandleOperationResponse(message)),
BeaconMessageType.sign_payload_response => (ack, HandleSignPayloadResponse(message)),
_ => throw new Exception("Unknown beaconMessage.Type.")
};
}
Expand All @@ -54,18 +57,17 @@ private BaseBeaconMessage HandleOperationRequest(string message)
return operationRequest;
}


private BaseBeaconMessage HandleSignPayloadRequest(string message)
{
var signPayloadRequest = _jsonSerializerService.Deserialize<SignPayloadRequest>(message);
return signPayloadRequest;
}
private BaseBeaconMessage HandleSignPayloadRequest(string message) =>
_jsonSerializerService.Deserialize<SignPayloadRequest>(message);

// todo: remove this to response handler
private BaseBeaconMessage HandlePermissionResponse(string message)
{
var permissionResponse = _jsonSerializerService.Deserialize<PermissionResponse>(message);
return permissionResponse;
}

private BaseBeaconMessage HandlePermissionResponse(string message) =>
_jsonSerializerService.Deserialize<PermissionResponse>(message);

private BaseBeaconMessage HandleOperationResponse(string message) =>
_jsonSerializerService.Deserialize<OperationResponse>(message);

private BaseBeaconMessage HandleSignPayloadResponse(string message) =>
_jsonSerializerService.Deserialize<SignPayloadResponse>(message);
}
}
12 changes: 12 additions & 0 deletions Beacon.Sdk/Core/Domain/ResponseMessageHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,14 @@ await HandlePermissionResponse(receiverId, response as PermissionResponse),
HandleDisconnectResponse(response as DisconnectMessage),
BeaconMessageType.error =>
HandleError(response as BaseBeaconError),

// todo: replace
BeaconMessageType.permission_request =>
HandlePermissionRequest(response as PermissionRequest),
BeaconMessageType.operation_request =>
HandleOperationRequest(response as OperationRequest),
BeaconMessageType.sign_payload_request =>
HandleSignPayloadRequest(response as SignPayloadRequest),

_ => throw new ArgumentException("Invalid beacon message type")
};
Expand Down Expand Up @@ -141,5 +147,11 @@ private string HandleError(BaseBeaconError response)

private string HandlePermissionRequest(PermissionRequest request) =>
_jsonSerializerService.Serialize(request);

private string HandleOperationRequest(OperationRequest request) =>
_jsonSerializerService.Serialize(request);

private string HandleSignPayloadRequest(SignPayloadRequest request) =>
_jsonSerializerService.Serialize(request);
}
}

0 comments on commit 97a6da1

Please sign in to comment.