Skip to content

Commit

Permalink
fix random date error
Browse files Browse the repository at this point in the history
  • Loading branch information
chebizarro committed Nov 18, 2024
1 parent df31c0e commit c3244d6
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 48 deletions.
34 changes: 12 additions & 22 deletions lib/core/utils/nostr_utils.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import 'dart:convert';
import 'dart:typed_data';
import 'dart:math';
import 'package:crypto/crypto.dart';
import 'package:dart_nostr/dart_nostr.dart';
import 'package:elliptic/elliptic.dart';
Expand All @@ -10,10 +10,7 @@ class NostrUtils {

// Generación de claves
static NostrKeyPairs generateKeyPair() {
var ec = getS256();
var priv = ec.generatePrivateKey();

return NostrKeyPairs(private: priv.toHex());
return NostrKeyPairs(private: generatePrivateKey());
}

static NostrKeyPairs generateKeyPairFromPrivateKey(String privateKey) {
Expand All @@ -22,7 +19,7 @@ class NostrUtils {
}

static String generatePrivateKey() {
return _instance.keysService.generatePrivateKey();
return getS256().generatePrivateKey().toHex();
}

// Codificación y decodificación de claves
Expand Down Expand Up @@ -121,6 +118,13 @@ class NostrUtils {
return digest.toString(); // Devuelve el ID como una cadena hex
}

static DateTime randomNow() {
final now = DateTime.now();
final randomSeconds =
Random().nextInt(2 * 24 * 60 * 60);
return now.subtract(Duration(seconds: randomSeconds));
}

// NIP-59 y NIP-44 funciones
static Future<NostrEvent> createNIP59Event(
String content, String recipientPubKey, String senderPrivateKey) async {
Expand All @@ -137,15 +141,13 @@ class NostrUtils {
],
);

randomNow() => DateTime(createdAt.millisecondsSinceEpoch ~/ 1000);

final encryptedContent = _encryptNIP44(
final encryptedContent = await _encryptNIP44(
jsonEncode(rumorEvent.toMap()), senderPrivateKey, '02$recipientPubKey');

final sealEvent = NostrEvent.fromPartialData(
kind: 13,
keyPairs: senderKeyPair,
content: await encryptedContent,
content: encryptedContent,
createdAt: randomNow(),
);

Expand Down Expand Up @@ -180,10 +182,6 @@ class NostrUtils {
final finalDecryptedContent = await _decryptNIP44(
rumorEvent.content ?? '', privateKey, rumorEvent.pubkey);

print(finalDecryptedContent);
print(
NostrEvent.canBeDeserialized('["EVENT", "", $finalDecryptedContent]'));

final wrap = jsonDecode(finalDecryptedContent) as Map<String, dynamic>;

return NostrEvent(
Expand All @@ -207,17 +205,9 @@ class NostrUtils {
.toList(),
),
subscriptionId: '',

);
}

static Uint8List _calculateSharedSecret(String privateKey, String publicKey) {
// Nota: Esta implementación puede necesitar ajustes dependiendo de cómo
// dart_nostr maneje la generación de secretos compartidos.
// Posiblemente necesites usar una biblioteca de criptografía adicional aquí.
final sharedPoint = generateKeyPairFromPrivateKey(privateKey).public;
return Uint8List.fromList(sha256.convert(utf8.encode(sharedPoint)).bytes);
}

static Future<String> _encryptNIP44(
String content, String privkey, String pubkey) async {
Expand Down
27 changes: 23 additions & 4 deletions lib/presentation/add_order/bloc/add_order_bloc.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mostro_mobile/data/models/enums/action.dart';
import 'package:mostro_mobile/services/mostro_service.dart';
import 'add_order_event.dart';
import 'add_order_state.dart';
Expand All @@ -9,18 +10,36 @@ class AddOrderBloc extends Bloc<AddOrderEvent, AddOrderState> {
AddOrderBloc(this.mostroService) : super(const AddOrderState()) {
on<ChangeOrderType>(_onChangeOrderType);
on<SubmitOrder>(_onSubmitOrder);
on<OrderUpdateReceived>(_onOrderUpdateReceived);
}

void _onChangeOrderType(ChangeOrderType event, Emitter<AddOrderState> emit) {
emit(state.copyWith(currentType: event.orderType));
}

void _onSubmitOrder(SubmitOrder event, Emitter<AddOrderState> emit) async {

Future<void> _onSubmitOrder(
SubmitOrder event, Emitter<AddOrderState> emit) async {
emit(state.copyWith(status: AddOrderStatus.submitting));

await mostroService.publishOrder(event.order);
final order = await mostroService.publishOrder(event.order);
add(OrderUpdateReceived(order));
}

emit(state.copyWith(status: AddOrderStatus.submitted));
void _onOrderUpdateReceived(
OrderUpdateReceived event, Emitter<AddOrderState> emit) {
switch (event.order.action) {
case Action.newOrder:
print(event.order.content!.toJson());
emit(state.copyWith(status: AddOrderStatus.submitted));
break;
case Action.outOfRangeSatsAmount:
case Action.outOfRangeFiatAmount:
print("Error! ${event.order.action.value}");
emit(state.copyWith(
status: AddOrderStatus.failure, errorMessage: "Invalid amount"));
break;
default:
break;
}
}
}
8 changes: 8 additions & 0 deletions lib/presentation/add_order/bloc/add_order_event.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import 'package:equatable/equatable.dart';
import 'package:mostro_mobile/data/models/enums/order_type.dart';
import 'package:mostro_mobile/data/models/mostro_message.dart';
import 'package:mostro_mobile/data/models/order.dart';

abstract class AddOrderEvent extends Equatable {
Expand Down Expand Up @@ -44,3 +45,10 @@ class SubmitOrder extends AddOrderEvent {
List<Object> get props =>
[fiatCode, fiatAmount, satsAmount, paymentMethod, orderType];
}

class OrderUpdateReceived extends AddOrderEvent {
final MostroMessage order;

const OrderUpdateReceived(this.order);
}

36 changes: 14 additions & 22 deletions lib/services/mostro_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import 'dart:convert';
import 'package:dart_nostr/nostr/model/event/event.dart';
import 'package:dart_nostr/nostr/model/request/filter.dart';
import 'package:mostro_mobile/core/config.dart';
import 'package:mostro_mobile/data/models/content.dart';
import 'package:mostro_mobile/data/models/mostro_message.dart';
import 'package:mostro_mobile/data/models/order.dart';
import 'package:mostro_mobile/data/models/enums/action.dart';
Expand All @@ -27,7 +28,8 @@ class MostroService {
return _nostrService.subscribeToEvents(filter);
}

Future<void> publishOrder(Order order) async {
Future<MostroMessage> publishOrder(
Order order) async {
final session = await _secureStorageManager.newSession();

final content = jsonEncode({
Expand All @@ -45,18 +47,11 @@ class MostroService {

final filter = NostrFilter(p: [session.publicKey]);

subscribeToOrders(filter).listen((event) async {
final response =
await _nostrService.decryptNIP59Event(event, session.privateKey);

final orderResponse = MostroMessage.deserialized(response.content!);

if (orderResponse.requestId != null) {
_orders[orderResponse.requestId!] = orderResponse;
_sessions[orderResponse.requestId!] = session;
session.eventId = orderResponse.requestId;
}
});
return await subscribeToOrders(filter).asyncMap((event) async {
return await _nostrService.decryptNIP59Event(event, session.privateKey);
}).map((event) {
return MostroMessage.deserialized(event.content!);
}).first;
}

Future<void> takeSellOrder(String orderId, {int? amount}) async {
Expand Down Expand Up @@ -88,7 +83,7 @@ class MostroService {
});
}

Future<void> takeBuyOrder(String orderId, {int? amount}) async {
Future<MostroMessage<Content>> takeBuyOrder(String orderId, {int? amount}) async {
final session = await _secureStorageManager.newSession();
session.eventId = orderId;

Expand All @@ -105,14 +100,11 @@ class MostroService {
await _nostrService.publishEvent(event);
final filter = NostrFilter(p: [session.publicKey]);

subscribeToOrders(filter).listen((event) async {
final response =
await _nostrService.decryptNIP59Event(event, session.privateKey);

final orderResponse = MostroMessage.deserialized(response.content!);

print(response);
});
return await subscribeToOrders(filter).asyncMap((event) async {
return await _nostrService.decryptNIP59Event(event, session.privateKey);
}).map((event) {
return MostroMessage.deserialized(event.content!);
}).first;
}

Future<void> cancelOrder(String orderId) async {
Expand Down

0 comments on commit c3244d6

Please sign in to comment.