Skip to content

Commit

Permalink
Merge pull request #29 from peaqnetwork/feature/1201962420298456_init…
Browse files Browse the repository at this point in the history
…iate-verification-challenge

Feature/1201962420298456 initiate verification challenge
  • Loading branch information
irediaes authored Apr 1, 2022
2 parents bcb8e94 + 158103e commit 97ac256
Show file tree
Hide file tree
Showing 24 changed files with 3,658 additions and 440 deletions.
Binary file modified android/app/src/main/jniLibs/arm64-v8a/libpeaq_codec_api.so
Binary file not shown.
Binary file modified android/app/src/main/jniLibs/armeabi-v7a/libpeaq_codec_api.so
Binary file not shown.
Binary file modified android/app/src/main/jniLibs/x86_64/libpeaq_codec_api.so
Binary file not shown.
2 changes: 2 additions & 0 deletions build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Generate models
flutter pub run build_runner build --delete-conflicting-outputs
4 changes: 3 additions & 1 deletion lib/common/providers/application_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ class CEVApplicationProvider extends ChangeNotifier {
cevSharedPrefs.appProvider = this;
accountProvider.appProvider = this;
chargeProvider.appProvider = this;
peerProvider.appProvider = this;

await Future.wait([
// charmev shared preferences
Expand Down Expand Up @@ -86,8 +87,9 @@ class CEVApplicationProvider extends ChangeNotifier {
if (authenticated) {
_log.fine("navigating to home screen");
accountProvider.connectNode();
peerProvider.initLog();
// initiate the p2p connection
peerProvider.connectP2P();
// peerProvider.connectP2P();
CEVNavigator.pushReplacementRoute(CEVFadeRoute(
builder: (context) => const HomeScreen(),
duration: const Duration(milliseconds: 600),
Expand Down
70 changes: 20 additions & 50 deletions lib/common/providers/charge_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import 'package:schnorr/schnorr.dart' as scn;
import 'package:elliptic/elliptic.dart' as ec;
import 'package:substrate_sign_flutter/substrate_sign_flutter.dart' as subsign;
import 'package:scan/scan.dart';
import 'package:peaq_network_ev_charging_message_format/did_document_format.pb.dart';
import 'package:peaq_network_ev_charging_message_format/did_document_format.pbenum.dart';

class CEVChargeProvider with ChangeNotifier {
CEVChargeProvider({
Expand Down Expand Up @@ -144,8 +146,8 @@ class CEVChargeProvider with ChangeNotifier {
}
}

/// fetch provider Did details from chain state storage
fetchProviderDidDetails(String did) async {
/// fetch provider Did document from chain state storage
fetchProviderDidDocument(String did) async {
reset();
if (_providerDid == _station.did) {
generateDetails(notify: true);
Expand All @@ -160,62 +162,30 @@ class CEVChargeProvider with ChangeNotifier {

var address = did.split(":")[2];

_status = LoadingStatus.loading;
notifyListeners();

var key = "station_data";
var params = {
"address": address,
"key": key,
};

var url = Env.storageURL;

print(_dio.options.baseUrl);
var doc = await appProvider.peerProvider.fetchDidDocument(address);

var res =
await _dio.post(url, data: json.encode(params)).catchError((err) async {
if (doc.id.isEmpty) {
setStatus(LoadingStatus.error, message: Env.providerDidNotFound);
print("Err:: $err");
return err;
});

print("res data:: ${res}");
print("res data:: ${res.data}");

String hashKey = res.data ?? "";

if (hashKey.length < 64) {
setStatus(LoadingStatus.error, message: Env.storageKeyGenError);
notifyListeners();
return;
}

url = "$url/$hashKey";
var result = await _dio.get(url);

if (result.data["message"] == "STORAGE NOT FOUND") {
setStatus(LoadingStatus.error, message: "Provider Did Details not Found");
notifyListeners();
return;
}

print(result.data);

var enData = json.decode(result.data["value"]);
_status = LoadingStatus.loading;
notifyListeners();

_station.did = _providerDid;
_station.address = address;
_station.plugType = enData["plug_type"];
_station.status = enData["status"];
_station.power = enData["power"];
// _station.stopUrl = enData["stop_url"];

// if (_station.stopUrl == null) {
// setStatus(LoadingStatus.error, message: Env.stopUrlNotSet);
// } else {
// setStatus(LoadingStatus.idle, message: "");
// }

for (var i = 0; i < doc.services.length; i++) {
var service = doc.services[i];
// Get the station metadata
if (service.type == ServiceType.metadata) {
var metadata = service.metadata;
_station.plugType = metadata.plugType;
_station.status = metadata.status.toString();
_station.power = metadata.power;
break;
}
}

setStatus(LoadingStatus.idle, message: "");

Expand Down
209 changes: 199 additions & 10 deletions lib/common/providers/peer_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ import 'package:charmev/common/services/fr_bridge/bridge_generated.dart';
import 'package:charmev/common/providers/application_provider.dart';
import 'package:provider/provider.dart' as provider;
import 'package:charmev/config/env.dart';
import 'package:peaq_network_ev_charging_message_format/did_document_format.pb.dart'
as doc;
import 'package:peaq_network_ev_charging_message_format/p2p_message_format.pb.dart'
as msg;

const base = 'peaq_codec_api';
final path = Platform.isWindows
Expand Down Expand Up @@ -48,16 +52,201 @@ class CEVPeerProvider with ChangeNotifier {
bool _showNodeDropdown = false;
List<Detail> _details = [];

String _identityChallengeData = '';
String _p2pURL = '';
bool _isPeerDidDocVerified = false;
bool _isPeerAuthenticated = false;
bool _isPeerConnected = false;
bool _isPeerSubscribed = false;
doc.Document _providerDidDoc = doc.Document();

bool get isPeerDidDocVerified => _isPeerDidDocVerified;
bool get isPeerAuthenticated => _isPeerAuthenticated;
bool get isPeerConnected => _isPeerConnected;
bool get isPeerSubscribed => _isPeerSubscribed;

Future<void> initLog() async {
api.initLogger();
}

Future<void> connectP2P() async {
await api.connectP2P(
url:
"${Env.p2pURL}/12D3KooWCazx4ZLTdrA1yeTTmCy5sGW32SFejztJTGdSZwnGf5Yo");

// String s = String.fromCharCodes(data);
// var outputAsUint8List = Uint8List.fromList(s.codeUnits);
// var decoded = utf8.decode(data);
// print("P2P DATA:: $data");
// print('P2P decoded DATA:: $decoded');
// print("P2P outputAsUint8List DATA:: $outputAsUint8List");
// validate p2p URL
var splitURL = _p2pURL.trim().split("/");

if (splitURL.length != 7) {
appProvider.chargeProvider
.setStatus(LoadingStatus.error, message: "Invalid P2P URL found");
}

api.connectP2P(url: _p2pURL);
runPeriodically(getEvent);
}

Future<void> getEvent() async {
print("getEvent hitts");

var data = await api.getEvent();

var utf8Res = utf8.decode(data);
var decodedRes = json.decode(utf8Res);

print("getEvent EVENT decodedRes $decodedRes");

if (!decodedRes["error"]) {
// decode event data
List<int> docRawData = List<int>.from(decodedRes["data"]);
String docCharCode = String.fromCharCodes(docRawData);
var docOutputAsUint8List = Uint8List.fromList(docCharCode.codeUnits);

var ev = msg.Event();
ev.mergeFromBuffer(docOutputAsUint8List);
print("getEvent EVENT ev $ev");

switch (ev.eventId) {
case msg.EventType.PEER_CONNECTED:
{
_isPeerConnected = true;
break;
}
case msg.EventType.PEER_CONNECTION_FAILED:
{
_isPeerConnected = false;
appProvider.chargeProvider.setStatus(LoadingStatus.error,
message:
"Unable to Connect to Provider Peer. Please check the p2p URL on DID document is correct.");
break;
}
case msg.EventType.PEER_SUBSCRIBED:
{
_isPeerSubscribed = true;
// Authenticate peer is it's connected and subscribed
if (_isPeerConnected) {
appProvider.chargeProvider.setStatus(LoadingStatus.loading,
message: Env.authenticatingProvider);
// send identity challenge to peer for verification
_sendIdentityChallengeEvent();
}
break;
}
case msg.EventType.IDENTITY_RESPONSE:
{
_authenticatePeer(ev.identityResponseData);
break;
}
default:
{}
}
}
}

verifyPeerDidDocument() async {
print("verifyPeerDidDocument hitts");

var sig = _providerDidDoc.signature.writeToBuffer();
var providerPK = _providerDidDoc.id.split(":")[2];

var data =
await api.verifyPeerDidDocument(providerPk: providerPK, signature: sig);

var utf8Res = utf8.decode(data);
var decodedRes = json.decode(utf8Res);

if (!decodedRes["error"]) {
_isPeerDidDocVerified = true;
notifyListeners();
}
}

_verifyPeerIdentity(
String providerPK, String plainData, doc.Signature signature) async {
print("verifyPeerIdentity hitts");

var sig = signature.writeToBuffer();

var data = await api.verifyPeerIdentity(
providerPk: providerPK, plainData: plainData, signature: sig);

var utf8Res = utf8.decode(data);
var decodedRes = json.decode(utf8Res);
print("verifyPeerIdentity decodedRes:: $decodedRes");

if (!decodedRes["error"]) {
_isPeerAuthenticated = true;
notifyListeners();
}
}

_authenticatePeer(msg.IdentityResponseData data) async {
for (var i = 0; i < _providerDidDoc.verificationMethods.length; i++) {
var vm = _providerDidDoc.verificationMethods[i];

var signature = doc.Signature(
type: vm.type, issuer: vm.controller, hash: data.signature);

await _verifyPeerIdentity(vm.id, _identityChallengeData, signature);
}

if (_isPeerAuthenticated) {
await appProvider.chargeProvider.generateAndFundMultisigWallet();
// await appProvider.accountProvider
// .simulateServiceRequestedAndDeliveredEvents();
} else {
appProvider.chargeProvider.setStatus(LoadingStatus.error,
message: "Unable to Authenticate Prover Peer...");
}
}

Future<void> _sendIdentityChallengeEvent() async {
print("sendIdentityChallengeEvent hitts");
var data = await api.sendIdentityChallengeEvent();

var utf8Res = utf8.decode(data);
var decodedRes = json.decode(utf8Res);

// decode did document data
List<int> docRawData = List<int>.from(decodedRes["data"]);
String docCharCode = String.fromCharCodes(docRawData);

_identityChallengeData = docCharCode;
print("RANDOM DATA:: $_identityChallengeData");

return;
}

Future<doc.Document> fetchDidDocument(String publicKey) async {
var data = await api.fetchDidDocument(
wsUrl: Env.peaqTestnet,
publicKey: publicKey,
storageName: Env.didDocAttributeName);

String s = String.fromCharCodes(data);
var utf8Res = utf8.decode(data);
var decodedRes = json.decode(utf8Res);
var didDoc = doc.Document();

if (!decodedRes["error"]) {
// decode did document data
List<int> docRawData = List<int>.from(decodedRes["data"]);
String docCharCode = String.fromCharCodes(docRawData);
var docOutputAsUint8List = Uint8List.fromList(docCharCode.codeUnits);

didDoc.mergeFromBuffer(docOutputAsUint8List);

_providerDidDoc = didDoc;
_setP2PURL(didDoc.services);
notifyListeners();
}
return didDoc;
}

_setP2PURL(List<doc.Service> services) {
for (var i = 0; i < services.length; i++) {
var service = services[i];

if (service.type == doc.ServiceType.p2p) {
_p2pURL = service.stringData;
break;
}
}
}
}
Loading

0 comments on commit 97ac256

Please sign in to comment.