summaryrefslogtreecommitdiff
path: root/impls/monero.dart/lib/src/ledger.dart
blob: 166bcf47a95b5f7b26fec50f5cacdd6fbf5cccb6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import 'dart:async';
import 'dart:ffi';
import 'dart:typed_data';

import 'package:ffi/ffi.dart';
import 'package:ledger_flutter_plus/ledger_flutter_plus.dart';
import 'package:monero/monero.dart' as monero;

Timer? _ledgerExchangeTimer;
String _lastLedgerRequest = '';

void enableLedgerExchange(monero.wallet ptr, LedgerConnection connection) {
  _ledgerExchangeTimer = Timer.periodic(Duration(milliseconds: 1), (_) async {
    final ledgerRequestLength = monero.Wallet_getSendToDeviceLength(ptr);
    final ledgerRequest = monero.Wallet_getSendToDevice(ptr)
        .cast<Uint8>()
        .asTypedList(ledgerRequestLength);
    if (ledgerRequestLength > 0 && _lastLedgerRequest != ledgerRequest.join()) {
      _lastLedgerRequest = ledgerRequest.join();

      final response = await exchange(connection, ledgerRequest);

      final Pointer<Uint8> result = malloc<Uint8>(response.length);
      for (var i = 0; i < response.length; i++) {
        result.asTypedList(response.length)[i] = response[i];
      }

      monero.Wallet_setDeviceReceivedData(
          ptr, result.cast<UnsignedChar>(), response.length);

      monero.Wallet_setDeviceSendData(
          ptr, malloc<Uint8>(0).cast<UnsignedChar>(), 0);
    }
  });
}

void disableLedgerExchange() {
  _ledgerExchangeTimer?.cancel();
}

Future<Uint8List> exchange(LedgerConnection connection, Uint8List data) async =>
    connection.sendOperation<Uint8List>(ExchangeOperation(data));

class ExchangeOperation extends LedgerOperation<Uint8List> {
  final Uint8List inputData;

  ExchangeOperation(this.inputData);

  @override
  Future<Uint8List> read(ByteDataReader reader) async =>
      reader.read(reader.remainingLength);

  @override
  Future<List<Uint8List>> write(ByteDataWriter writer) async => [inputData];
}