From a901a825a189e6533162d3b56850918363cf7738 Mon Sep 17 00:00:00 2001 From: redDwarf03 <68340133+redDwarf03@users.noreply.github.com> Date: Sun, 4 Jun 2023 11:48:00 +0200 Subject: [PATCH] Log display management (#80) * add logs activation property on Service classes --- lib/src/services/address_service.dart | 14 +- lib/src/services/api_service.dart | 141 +++++++++++++++--- lib/src/services/graph_ql_client_logger.dart | 11 +- lib/src/services/hosting_service.dart | 145 ------------------- lib/src/services/oracle_service.dart | 22 ++- lib/src/utils/logs.dart | 10 +- pubspec.lock | 2 +- 7 files changed, 162 insertions(+), 183 deletions(-) delete mode 100644 lib/src/services/hosting_service.dart diff --git a/lib/src/services/address_service.dart b/lib/src/services/address_service.dart index 1964a70f..cc27f910 100644 --- a/lib/src/services/address_service.dart +++ b/lib/src/services/address_service.dart @@ -6,11 +6,17 @@ import 'package:archethic_lib_dart/src/utils/crypto.dart' as crypto import 'package:archethic_lib_dart/src/utils/utils.dart'; class AddressService { - AddressService(this.endpoint); + AddressService( + this.endpoint, { + this.logsActivation = true, + }); /// [endpoint] is the HTTP URL to a Archethic node (acting as welcome node) String? endpoint; + /// [logsActivation] manage log activation + final bool logsActivation; + /// Get the last address from seed /// @param {String} seed TransactionChain seed Future lastAddressFromSeed(String seed) async { @@ -29,8 +35,10 @@ class AddressService { return {}; } - final transactionMap = await ApiService(endpoint!) - .getLastTransaction(addresses, request: ' address '); + final transactionMap = await ApiService( + endpoint!, + logsActivation: logsActivation, + ).getLastTransaction(addresses, request: ' address '); final lastAddressMap = {}; transactionMap.forEach((String key, Transaction value) { diff --git a/lib/src/services/api_service.dart b/lib/src/services/api_service.dart index bc4b3724..f1e4dc81 100644 --- a/lib/src/services/api_service.dart +++ b/lib/src/services/api_service.dart @@ -31,8 +31,10 @@ import 'package:graphql/client.dart'; import 'package:http/http.dart' as http; class ApiService { - ApiService(this.endpoint) - : _client = GraphQLClient( + ApiService( + this.endpoint, { + this.logsActivation = true, + }) : _client = GraphQLClient( link: HttpLink('$endpoint/api'), cache: GraphQLCache(), defaultPolicies: DefaultPolicies( @@ -55,25 +57,37 @@ class ApiService { /// [endpoint] is the HTTP URL to a Archethic node (acting as welcome node) final String endpoint; + /// [logsActivation] manage log activation + final bool logsActivation; + /// Send a transaction to the network /// @param {Object} tx Transaction to send Future sendTx(Transaction transaction) async { final completer = Completer(); var transactionStatus = const TransactionStatus(); - log('sendTx: requestHttp.body=${transaction.convertToJSON()}'); + log( + 'sendTx: requestHttp.body=${transaction.convertToJSON()}', + logsActivation: logsActivation, + ); try { final responseHttp = await http.post( Uri.parse('$endpoint/api/transaction'), body: transaction.convertToJSON(), headers: kRequestHeaders, ); - log('sendTx: responseHttp.body=${responseHttp.body}'); + log( + 'sendTx: responseHttp.body=${responseHttp.body}', + logsActivation: logsActivation, + ); transactionStatus = transactionStatusFromJson(responseHttp.body); completer.complete(transactionStatus); } catch (e) { - log(e.toString()); + log( + e.toString(), + logsActivation: logsActivation, + ); } return completer.future; @@ -97,7 +111,12 @@ class ApiService { } body.write(' } $fragment'); - final result = await _client.withLogger('getLastTransaction').query( + final result = await _client + .withLogger( + 'getLastTransaction', + logsActivation: logsActivation, + ) + .query( QueryOptions( document: gql(body.toString()), parserFn: (data) { @@ -141,9 +160,17 @@ class ApiService { Future getStorageNoncePublicKey() async { const body = 'query {sharedSecrets {storageNoncePublicKey}}'; - log('getStorageNoncePublicKey: requestHttp.body=$body'); + log( + 'getStorageNoncePublicKey: requestHttp.body=$body', + logsActivation: logsActivation, + ); - final result = await _client.withLogger('getStorageNoncePublicKey').query( + final result = await _client + .withLogger( + 'getStorageNoncePublicKey', + logsActivation: logsActivation, + ) + .query( QueryOptions( document: gql(body), parserFn: (object) => SharedSecrets.fromJson(object), @@ -176,7 +203,12 @@ class ApiService { } body.write(' } $fragment'); - final result = await _client.withLogger('fetchBalance').query( + final result = await _client + .withLogger( + 'fetchBalance', + logsActivation: logsActivation, + ) + .query( QueryOptions( document: gql(body.toString()), parserFn: (object) { @@ -230,7 +262,10 @@ class ApiService { return removeAliasPrefix(contentMap) ?? {}; } catch (e) { - log('getTransactionContent: error=$e'); + log( + 'getTransactionContent: error=$e', + logsActivation: logsActivation, + ); rethrow; } } @@ -262,7 +297,12 @@ class ApiService { }); body.write('} $fragment'); - final result = await _client.withLogger('getTransactionChain').query( + final result = await _client + .withLogger( + 'getTransactionChain', + logsActivation: logsActivation, + ) + .query( QueryOptions( document: gql(body.toString()), parserFn: (object) { @@ -296,7 +336,12 @@ class ApiService { const body = 'query {nodes {authorized available averageAvailability firstPublicKey geoPatch ip lastPublicKey networkPatch port rewardAddress authorizationDate enrollmentDate}}'; - final result = await _client.withLogger('getNodeList').query( + final result = await _client + .withLogger( + 'getNodeList', + logsActivation: logsActivation, + ) + .query( QueryOptions( document: gql(body), parserFn: (json) => NodesResponseData.fromJson(json).nodes!, @@ -325,7 +370,12 @@ class ApiService { final body = 'query { networkTransactions(type: "$type", page: $page) { $request } }'; - final result = await _client.withLogger('networkTransactions').query( + final result = await _client + .withLogger( + 'networkTransactions', + logsActivation: logsActivation, + ) + .query( QueryOptions( document: gql(body), parserFn: (json) { @@ -375,7 +425,12 @@ class ApiService { } body.write(' } $fragment'); - final result = await _client.withLogger('getTransactionInputs').query( + final result = await _client + .withLogger( + 'getTransactionInputs', + logsActivation: logsActivation, + ) + .query( QueryOptions( document: gql(body.toString()), parserFn: (json) { @@ -424,7 +479,12 @@ class ApiService { ); } body.write('} $fragment'); - final result = await _client.withLogger('getTransaction').query( + final result = await _client + .withLogger( + 'getTransaction', + logsActivation: logsActivation, + ) + .query( QueryOptions( document: gql(body.toString()), parserFn: (json) { @@ -453,13 +513,19 @@ class ApiService { /// Get transaction fees /// @param {Object} tx Transaction to estimate fees Future getTransactionFee(Transaction transaction) async { - log('getTransactionFee: requestHttp.body=${transaction.convertToJSON()}'); + log( + 'getTransactionFee: requestHttp.body=${transaction.convertToJSON()}', + logsActivation: logsActivation, + ); final responseHttp = await http.post( Uri.parse('$endpoint/api/transaction_fee'), body: transaction.convertToJSON(), headers: kRequestHeaders, ); - log('getTransactionFee: responseHttp.body=${responseHttp.body}'); + log( + 'getTransactionFee: responseHttp.body=${responseHttp.body}', + logsActivation: logsActivation, + ); return TransactionFee.fromJson(json.decode(responseHttp.body)); } @@ -491,7 +557,10 @@ class ApiService { return removeAliasPrefix>(ownershipsMap) ?? {}; } catch (e) { - log('getTransactionOwnerships: error=$e'); + log( + 'getTransactionOwnerships: error=$e', + logsActivation: logsActivation, + ); } return {}; @@ -604,7 +673,10 @@ class ApiService { final aesKey = ecDecrypt(authorizedPublicKey.encryptedSecretKey, keypair.privateKey); final keychainAddress = aesDecrypt(ownership.secret, aesKey); - log('keychainAddress (getKeychain): ${uint8ListToHex(keychainAddress)}'); + log( + 'keychainAddress (getKeychain): ${uint8ListToHex(keychainAddress)}', + logsActivation: logsActivation, + ); final lastTransactionKeychainMap = await getLastTransaction( [uint8ListToHex(keychainAddress)], @@ -660,13 +732,19 @@ class ApiService { 'origin_public_key': originPublicKey!, 'certificate': certificate! }); + log( + 'addOriginKey: requestHttp.body=$body', + logsActivation: logsActivation, + ); final responseHttp = await http.post( Uri.parse('$endpoint/api/origin_key'), body: body, headers: kRequestHeaders, ); - log('addOriginKey: requestHttp.body=$body'); - log('addOriginKey: responseHttp.body=${responseHttp.body}'); + log( + 'addOriginKey: responseHttp.body=${responseHttp.body}', + logsActivation: logsActivation, + ); return originKeyResponseFromJson(responseHttp.body).toString(); } @@ -690,7 +768,12 @@ class ApiService { } body.write(' } $fragment'); - final result = await _client.withLogger('getToken').query( + final result = await _client + .withLogger( + 'getToken', + logsActivation: logsActivation, + ) + .query( QueryOptions( document: gql(body.toString()), parserFn: (json) { @@ -721,7 +804,12 @@ class ApiService { Future> getNearestEndpoints() async { const body = 'query { nearestEndpoints { ip, port } }'; - final result = await _client.withLogger('getNearestEndpoints').query( + final result = await _client + .withLogger( + 'getNearestEndpoints', + logsActivation: logsActivation, + ) + .query( QueryOptions( document: gql(body), parserFn: (json) => @@ -743,7 +831,12 @@ class ApiService { Future
getGenesisAddress(String address) async { final body = 'query { genesisAddress (address:"$address") }'; - final result = await _client.withLogger('getGenesisAddress').query( + final result = await _client + .withLogger( + 'getGenesisAddress', + logsActivation: logsActivation, + ) + .query( QueryOptions( document: gql(body), parserFn: (json) => diff --git a/lib/src/services/graph_ql_client_logger.dart b/lib/src/services/graph_ql_client_logger.dart index 7ab9591d..f26907b2 100644 --- a/lib/src/services/graph_ql_client_logger.dart +++ b/lib/src/services/graph_ql_client_logger.dart @@ -1,14 +1,16 @@ import 'dart:convert'; -import 'dart:developer'; +import 'package:archethic_lib_dart/src/utils/logs.dart'; import 'package:gql/language.dart' show printNode; import 'package:graphql/client.dart'; extension GraphQLClientWithLogger on GraphQLClient { /// Proxyfies a [GraphQLClient] with a [GraphQLClientLogger]. - GraphQLClient withLogger(String logName) => GraphQLClientLogger( + GraphQLClient withLogger(String logName, {bool logsActivation = true}) => + GraphQLClientLogger( client: this, logName: logName, + logsActivation: logsActivation, ); } @@ -17,9 +19,11 @@ class GraphQLClientLogger implements GraphQLClient { GraphQLClientLogger({ required this.client, required this.logName, + this.logsActivation = true, }); final GraphQLClient client; final String logName; + final bool logsActivation; final JsonEncoder _jsonEncoder = const JsonEncoder.withIndent(' '); @@ -86,6 +90,7 @@ class GraphQLClientLogger implements GraphQLClient { log( '${DateTime.now()} requestHttp.body=${printNode(options.document)}', name: logName, + logsActivation: logsActivation, ); final result = await client.query(options); @@ -94,11 +99,13 @@ class GraphQLClientLogger implements GraphQLClient { log( '${DateTime.now()} responseHttp.error=${_jsonEncoder.convert(result.exception?.toJson)}', name: logName, + logsActivation: logsActivation, ); } log( '${DateTime.now()} responseHttp.body=${_jsonEncoder.convert(result.data)}', name: logName, + logsActivation: logsActivation, ); return result; diff --git a/lib/src/services/hosting_service.dart b/lib/src/services/hosting_service.dart deleted file mode 100644 index 40dc630c..00000000 --- a/lib/src/services/hosting_service.dart +++ /dev/null @@ -1,145 +0,0 @@ -// Dart imports: - -//import 'package:archive/archive.dart'; - -class HostingService { - String? endpoint; -/* - HostingService(this.endpoint); - - /// [endpoint] is the HTTP URL to a Archethic node (acting as welcome node) - - /// Files List in an archive - List filesInArchive = List.empty(growable: true); - - String _getSeed(String seed, String fileName, - {String curve = 'ed25519', String hashAlgo = 'sha256'}) { - crypto.Hmac hmac = crypto.Hmac(crypto.sha256, seed.codeUnits); - crypto.Digest digest = hmac.convert(fileName.codeUnits); - Uint8List _seed = Uint8List.fromList(digest.bytes); - return uint8ListToHex(_seed); - } - - void deployWebSite(String seed, String originPrivateKey, Archive archive, - {String curve = 'ed25519', String hashAlgo = 'sha256'}) async { - List files = []; - List seeds = []; - List addresses = []; - List arrayFiles = []; - List arrayAddress = []; -*/ - /* for (var file in archive.files) { - if (file.isFile) { - print(file.name); - String _seed = - _getSeed(seed, file.name, curve: curve, hashAlgo: hashAlgo); - seeds.add(_seed); - String _address = - deriveAddress(_seed, 0, curve: curve, hashAlgo: hashAlgo); - addresses.add(_address); - print('address: ' + _address); - try { - Transaction txn = - Transaction(type: 'transfer', data: Transaction.initData()) - .addUCOTransfer(_address, toBigInt(1)) - .build(seed, 0) - .originSign(originPrivateKey); - - TransactionStatus transactionStatus = - await ApiService(endpoint).sendTx(txn); - // await ApiService(endpoint).waitConfirmations(txn.address!, - // (nbConfirmations) { - // print(nbConfirmations); - // }); - - print(transactionStatus.status); - } catch (e) { - print('e: ' + e.toString()); - } - } - }*/ -/* - for (int i = 0; i < archive.files.length; i++) { - crypto.Hmac hmac = crypto.Hmac(crypto.sha256, Uint8List.fromList(hexToUint8List(seed)); - crypto.Digest digest = hmac.convert(archive.files[i].name.codeUnits); - Uint8List _seed = Uint8List.fromList(digest.bytes); - String _address = deriveAddress(uint8ListToHex(_seed), 0, - curve: curve, hashAlgo: hashAlgo); - addresses.add(_address); - } - - Transaction txn = - Transaction(type: 'transfer', data: Transaction.initData()); - - for (int i = 0; i < addresses.length; i++) { - txn.addUCOTransfer(addresses[i], toBigInt(1)); - } - txn.build(seed, 0).originSign(originPrivateKey); - try { - TransactionStatus transactionStatus = - await ApiService(endpoint).sendTx(txn); - // await ApiService(endpoint).waitConfirmations(txn.address!, - // (nbConfirmations) { - // print(nbConfirmations); - // }); - - print(transactionStatus.status); - } catch (e) { - print('e: ' + e.toString()); - } - - for (var file in archive.files) {} -/* - Transaction txBuilder = - Transaction(type: 'hosting', data: Transaction.initData()); - txBuilder.setContent(files[i]); - Transaction lastTransaction = - await ApiService(endpoint).getLastTransaction(_address); - int index = lastTransaction.chainLength!; - Transaction transaction = - txBuilder.build(seed, index).originSign(originPrivateKey); - TransactionStatus sendFolder = - await ApiService(endpoint).sendTx(transaction); - if (sendFolder.status == 'ok') { - print(files[i]); - print(endpoint! + - '/api/last_transaction/' + - _address + - '/content?mime=' + - 'TOTOOTOTOT____MIME'); - arrayFiles - .add(uint8ListToHex(files[i]).substring(files[i].indexOf('/') + 1)); - arrayAddress.add(_address); - } - } - - for (int i = 0; i < arrayFiles.length; i++) { - if (arrayFiles[i] == 'index.html') { - crypto.Hmac hmac = crypto.Hmac(crypto.sha256, Uint8List.fromList(hexToUint8List(seed)); - crypto.Digest digest = hmac.convert('folder' + 'index.html'); - Uint8List _seed = Uint8List.fromList(digest.bytes); - String _address = AddressService(endpoint).deriveAddress( - uint8ListToHex(_seed), 0, - curve: curve, hashAlgo: hashAlgo); - Transaction txBuilder = - Transaction(type: 'hosting', data: Transaction.initData()); - txBuilder.setContent(files[i]); - Transaction lastTransaction = - await ApiService(endpoint).getLastTransaction(_address); - int index = lastTransaction.chainLength!; - Transaction transaction = - txBuilder.build(seed, index).originSign(originPrivateKey); - TransactionStatus sendFolder = - await ApiService(endpoint).sendTx(transaction); - if (sendFolder.status == 'ok') { - print('Check your website at-'); - print(endpoint! + - '/api/last_transaction/' + - _address + - '/content?mime=' + - 'TOTOOTOTOT____MIME'); - } - } - }*/ - }*/ -} diff --git a/lib/src/services/oracle_service.dart b/lib/src/services/oracle_service.dart index 52312971..b8b8586f 100644 --- a/lib/src/services/oracle_service.dart +++ b/lib/src/services/oracle_service.dart @@ -1,20 +1,21 @@ /// SPDX-License-Identifier: AGPL-3.0-or-later import 'dart:async'; -// Project imports: import 'package:archethic_lib_dart/src/model/oracle_chain/oracle_uco_price.dart'; import 'package:archethic_lib_dart/src/model/response/oracle_data_response.dart'; import 'package:archethic_lib_dart/src/model/uco.dart'; import 'package:archethic_lib_dart/src/utils/logs.dart'; -// Package imports: import 'package:http/http.dart' as http show post; class OracleService { - OracleService(this.endpoint); + OracleService(this.endpoint, {this.logsActivation = true}); /// [endpoint] is the HTTP URL to a Archethic node (acting as welcome node) String? endpoint; + /// [logsActivation] manage log activation + final bool logsActivation; + /// return a value of Oracle Uco_Price in {OracleUcoPrice} from a timestamp /// if timestamp = 0 or not precised, the last price is returned /// @param {int} timestamp @@ -36,13 +37,19 @@ class OracleService { '{"query": "query { oracleData(timestamp: $timestamp) { timestamp services { uco { eur, usd } } } }"}'; } - log('getOracleData: requestHttp.body=$body'); + log( + 'getOracleData: requestHttp.body=$body', + logsActivation: logsActivation, + ); final responseHttp = await http.post( Uri.parse('${endpoint!}/api'), body: body, headers: requestHeaders, ); - log('getOracleData: responseHttp.body=${responseHttp.body}'); + log( + 'getOracleData: responseHttp.body=${responseHttp.body}', + logsActivation: logsActivation, + ); if (responseHttp.statusCode == 200) { final oracleDataResponse = oracleDataResponseFromJson(responseHttp.body); @@ -59,7 +66,10 @@ class OracleService { } } } catch (e) { - log('getOracleData: error=$e'); + log( + 'getOracleData: error=$e', + logsActivation: logsActivation, + ); } completer.complete(oracleUcoPrice); diff --git a/lib/src/utils/logs.dart b/lib/src/utils/logs.dart index 9325f5bd..3e0282a1 100644 --- a/lib/src/utils/logs.dart +++ b/lib/src/utils/logs.dart @@ -3,6 +3,12 @@ // Dart imports: import 'dart:developer' as dev; -void log(String message) { - dev.log('${DateTime.now()} $message'); +void log(String message, {bool logsActivation = true, String name = ''}) { + if (logsActivation) { + if (name.isEmpty) { + dev.log('${DateTime.now()} $message'); + } else { + dev.log('${DateTime.now()} $message', name: name); + } + } } diff --git a/pubspec.lock b/pubspec.lock index 955e40fb..60f13d6b 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -754,4 +754,4 @@ packages: source: hosted version: "3.1.1" sdks: - dart: ">=2.19.0 <3.0.0" + dart: ">=2.19.0 <4.0.0"