cake_wallet/cw_nano/lib/nano_wallet.dart

442 lines
13 KiB
Dart
Raw Normal View History

2023-07-25 15:21:49 +00:00
import 'dart:convert';
2023-08-08 13:49:13 +00:00
import 'dart:io';
2023-07-25 15:21:49 +00:00
2023-08-15 19:05:38 +00:00
import 'package:cw_core/cake_hive.dart';
2023-07-25 15:21:49 +00:00
import 'package:cw_core/crypto_currency.dart';
import 'package:cw_core/node.dart';
2023-07-24 16:56:20 +00:00
import 'package:cw_core/pathForWallet.dart';
2023-07-25 15:21:49 +00:00
import 'package:cw_core/pending_transaction.dart';
import 'package:cw_core/pow_node.dart';
2023-07-25 15:21:49 +00:00
import 'package:cw_core/sync_status.dart';
2023-07-27 17:02:10 +00:00
import 'package:cw_core/transaction_direction.dart';
2023-07-24 16:56:20 +00:00
import 'package:cw_core/transaction_priority.dart';
2023-07-25 15:21:49 +00:00
import 'package:cw_core/wallet_addresses.dart';
import 'package:cw_core/wallet_info.dart';
2023-07-26 17:15:22 +00:00
import 'package:cw_nano/file.dart';
2023-08-10 22:34:20 +00:00
import 'package:cw_core/nano_account.dart';
2023-07-24 20:23:09 +00:00
import 'package:cw_nano/nano_balance.dart';
2023-07-27 17:02:10 +00:00
import 'package:cw_nano/nano_client.dart';
2023-07-31 15:39:22 +00:00
import 'package:cw_nano/nano_transaction_credentials.dart';
2023-07-25 15:21:49 +00:00
import 'package:cw_nano/nano_transaction_history.dart';
import 'package:cw_nano/nano_transaction_info.dart';
2023-07-26 17:15:22 +00:00
import 'package:cw_nano/nano_util.dart';
2023-07-31 15:39:22 +00:00
import 'package:cw_nano/nano_wallet_keys.dart';
2023-07-31 13:10:33 +00:00
import 'package:cw_nano/pending_nano_transaction.dart';
2023-07-24 16:56:20 +00:00
import 'package:mobx/mobx.dart';
2023-08-10 22:34:20 +00:00
import 'package:hive/hive.dart';
2023-07-25 15:21:49 +00:00
import 'dart:async';
import 'package:cw_nano/nano_wallet_addresses.dart';
2023-07-24 16:56:20 +00:00
import 'package:cw_core/wallet_base.dart';
2023-07-31 15:39:22 +00:00
import 'package:nanodart/nanodart.dart';
2023-07-26 17:15:22 +00:00
import 'package:bip39/bip39.dart' as bip39;
2023-07-24 16:56:20 +00:00
part 'nano_wallet.g.dart';
class NanoWallet = NanoWalletBase with _$NanoWallet;
2023-07-24 20:23:09 +00:00
abstract class NanoWalletBase
extends WalletBase<NanoBalance, NanoTransactionHistory, NanoTransactionInfo> with Store {
2023-07-25 15:21:49 +00:00
NanoWalletBase({
2023-08-14 22:02:12 +00:00
required WalletInfo walletInfo,
2023-07-25 15:21:49 +00:00
required String mnemonic,
required String password,
NanoBalance? initialBalance,
}) : syncStatus = NotConnectedSyncStatus(),
_password = password,
_mnemonic = mnemonic,
2023-08-14 22:02:12 +00:00
_derivationType = walletInfo.derivationType!,
2023-07-24 16:56:20 +00:00
_isTransactionUpdating = false,
2023-07-27 17:02:10 +00:00
_client = NanoClient(),
2023-07-24 16:56:20 +00:00
walletAddresses = NanoWalletAddresses(walletInfo),
2023-07-25 15:21:49 +00:00
balance = ObservableMap<CryptoCurrency, NanoBalance>.of({
2023-07-25 17:36:24 +00:00
CryptoCurrency.nano: initialBalance ??
2023-07-25 15:21:49 +00:00
NanoBalance(currentBalance: BigInt.zero, receivableBalance: BigInt.zero)
}),
2023-07-24 16:56:20 +00:00
super(walletInfo) {
2023-07-25 15:21:49 +00:00
this.walletInfo = walletInfo;
2023-07-27 17:02:10 +00:00
transactionHistory = NanoTransactionHistory(walletInfo: walletInfo, password: password);
2023-08-15 19:05:38 +00:00
if (!CakeHive.isAdapterRegistered(NanoAccount.typeId)) {
CakeHive.registerAdapter(NanoAccountAdapter());
2023-08-10 22:34:20 +00:00
}
2023-07-24 16:56:20 +00:00
}
2023-07-25 15:21:49 +00:00
final String _mnemonic;
final String _password;
2023-07-26 17:15:22 +00:00
final DerivationType _derivationType;
2023-08-04 14:54:20 +00:00
String? _privateKey;
String? _publicAddress;
String? _seedKey;
2023-08-02 15:47:00 +00:00
String? _representativeAddress;
2023-08-01 17:48:22 +00:00
Timer? _receiveTimer;
2023-07-25 15:21:49 +00:00
2023-07-27 17:02:10 +00:00
late NanoClient _client;
2023-07-25 15:21:49 +00:00
bool _isTransactionUpdating;
2023-07-24 16:56:20 +00:00
@override
2023-08-10 22:34:20 +00:00
NanoWalletAddresses walletAddresses;
2023-07-24 16:56:20 +00:00
@override
@observable
SyncStatus syncStatus;
@override
@observable
2023-07-25 15:21:49 +00:00
late ObservableMap<CryptoCurrency, NanoBalance> balance;
2023-07-24 16:56:20 +00:00
2023-07-26 17:15:22 +00:00
// initialize the different forms of private / public key we'll need:
Future<void> init() async {
final String type = (_derivationType == DerivationType.nano) ? "standard" : "hd";
2023-08-14 22:02:12 +00:00
// our "mnemonic" is actually a seedkey:
if (!_mnemonic.contains(' ')) {
_seedKey = _mnemonic;
}
2023-08-14 22:02:12 +00:00
if (_seedKey == null) {
if (_derivationType == DerivationType.nano) {
_seedKey = bip39.mnemonicToEntropy(_mnemonic).toUpperCase();
} else {
_seedKey = await NanoUtil.hdMnemonicListToSeed(_mnemonic.split(' '));
}
}
2023-08-04 14:54:20 +00:00
_privateKey = await NanoUtil.uniSeedToPrivate(_seedKey!, 0, type);
_publicAddress = await NanoUtil.uniSeedToAddress(_seedKey!, 0, type);
this.walletInfo.address = _publicAddress!;
2023-07-26 17:15:22 +00:00
await walletAddresses.init();
2023-07-27 17:02:10 +00:00
await transactionHistory.init();
2023-07-26 17:15:22 +00:00
await save();
}
2023-07-24 20:23:09 +00:00
2023-07-24 16:56:20 +00:00
@override
2023-07-25 15:21:49 +00:00
int calculateEstimatedFee(TransactionPriority priority, int? amount) {
2023-07-26 17:15:22 +00:00
return 0; // always 0 :)
2023-07-25 15:21:49 +00:00
}
2023-07-24 16:56:20 +00:00
@override
2023-07-25 15:21:49 +00:00
Future<void> changePassword(String password) {
throw UnimplementedError("changePassword");
2023-07-24 16:56:20 +00:00
}
@override
2023-07-25 15:21:49 +00:00
void close() {
2023-07-27 17:02:10 +00:00
_client.stop();
2023-07-24 16:56:20 +00:00
}
2023-07-25 15:21:49 +00:00
@action
2023-07-24 16:56:20 +00:00
@override
2023-07-25 15:21:49 +00:00
Future<void> connectToNode({required Node node}) async {
2023-07-27 17:02:10 +00:00
try {
syncStatus = ConnectingSyncStatus();
final isConnected = _client.connect(node);
if (!isConnected) {
2023-08-01 17:48:22 +00:00
throw Exception("Nano Node connection failed");
2023-07-27 17:02:10 +00:00
}
2023-08-01 17:48:22 +00:00
try {
await _updateBalance();
2023-08-02 15:47:00 +00:00
await _updateRep();
2023-08-01 17:48:22 +00:00
await _receiveAll();
2023-08-08 12:58:08 +00:00
} catch (e) {
print(e);
}
2023-08-01 17:48:22 +00:00
2023-07-27 17:02:10 +00:00
syncStatus = ConnectedSyncStatus();
} catch (e) {
2023-08-01 17:48:22 +00:00
print(e);
2023-07-27 17:02:10 +00:00
syncStatus = FailedSyncStatus();
}
2023-07-24 16:56:20 +00:00
}
2023-08-10 22:34:20 +00:00
@override
Future<void> connectToPowNode({required PowNode node}) async {
2023-08-10 01:05:24 +00:00
_client.connectPow(node);
}
2023-07-24 16:56:20 +00:00
@override
Future<PendingTransaction> createTransaction(Object credentials) async {
2023-07-31 15:39:22 +00:00
credentials = credentials as NanoTransactionCredentials;
BigInt runningAmount = BigInt.zero;
await _updateBalance();
BigInt runningBalance = balance[currency]?.currentBalance ?? BigInt.zero;
final List<Map<String, String>> blocks = [];
String? previousHash;
for (var txOut in credentials.outputs) {
late BigInt amt;
if (txOut.sendAll) {
amt = balance[currency]?.currentBalance ?? BigInt.zero;
} else {
amt = BigInt.tryParse(
NanoUtil.getAmountAsRaw(txOut.cryptoAmount ?? "0", NanoUtil.rawPerNano)) ??
BigInt.zero;
}
2023-08-21 20:10:22 +00:00
if (balance[currency]?.currentBalance != null && amt > balance[currency]!.currentBalance) {
throw Exception("Trying to send more than entire balance!");
}
2023-07-31 15:39:22 +00:00
runningBalance = runningBalance - amt;
final block = await _client.constructSendBlock(
amountRaw: amt.toString(),
2023-08-21 20:10:22 +00:00
destinationAddress: txOut.extractedAddress ?? txOut.address,
2023-08-04 14:54:20 +00:00
privateKey: _privateKey!,
2023-07-31 15:39:22 +00:00
balanceAfterTx: runningBalance,
previousHash: previousHash,
);
previousHash = NanoBlocks.computeStateHash(
NanoAccountType.NANO,
block["account"]!,
block["previous"]!,
block["representative"]!,
BigInt.parse(block["balance"]!),
block["link"]!,
);
blocks.add(block);
runningAmount += amt;
}
try {
if (runningAmount > balance[currency]!.currentBalance || runningBalance < BigInt.zero) {
throw Exception(("Trying to send more than entire balance!"));
}
} catch (e) {
rethrow;
}
2023-07-28 14:36:50 +00:00
2023-07-31 13:10:33 +00:00
return PendingNanoTransaction(
2023-07-31 15:39:22 +00:00
amount: runningAmount,
2023-07-31 13:10:33 +00:00
fee: 0,
2023-07-31 15:39:22 +00:00
id: "",
2023-07-31 13:10:33 +00:00
nanoClient: _client,
2023-07-31 15:39:22 +00:00
blocks: blocks,
2023-07-31 13:10:33 +00:00
);
2023-07-24 16:56:20 +00:00
}
Future<void> _receiveAll() async {
2023-08-01 17:48:22 +00:00
await _updateBalance();
int blocksReceived = await this._client.confirmAllReceivable(
2023-08-04 14:54:20 +00:00
destinationAddress: _publicAddress!,
privateKey: _privateKey!,
);
if (blocksReceived > 0) {
await Future<void>.delayed(Duration(seconds: 3));
_updateBalance();
updateTransactions();
}
}
2023-07-25 15:21:49 +00:00
Future<void> updateTransactions() async {
2023-07-27 17:02:10 +00:00
try {
if (_isTransactionUpdating) {
return;
}
_isTransactionUpdating = true;
final transactions = await fetchTransactions();
2023-08-21 19:01:33 +00:00
transactionHistory.clear();
2023-07-27 17:02:10 +00:00
transactionHistory.addMany(transactions);
await transactionHistory.save();
_isTransactionUpdating = false;
} catch (_) {
_isTransactionUpdating = false;
}
2023-07-24 16:56:20 +00:00
}
@override
2023-07-25 15:21:49 +00:00
Future<Map<String, NanoTransactionInfo>> fetchTransactions() async {
2023-08-04 14:54:20 +00:00
String address = _publicAddress!;
2023-07-27 17:02:10 +00:00
final transactions = await _client.fetchTransactions(address);
final Map<String, NanoTransactionInfo> result = {};
for (var transactionModel in transactions) {
result[transactionModel.hash] = NanoTransactionInfo(
id: transactionModel.hash,
amountRaw: transactionModel.amount,
height: transactionModel.height,
2023-08-10 22:34:20 +00:00
direction: transactionModel.type == "send"
? TransactionDirection.outgoing
: TransactionDirection.incoming,
2023-07-27 17:02:10 +00:00
confirmed: transactionModel.confirmed,
date: transactionModel.date ?? DateTime.now(),
confirmations: transactionModel.confirmed ? 1 : 0,
);
}
return result;
2023-07-24 16:56:20 +00:00
}
@override
2023-07-31 15:39:22 +00:00
NanoWalletKeys get keys {
2023-08-04 14:54:20 +00:00
return NanoWalletKeys(seedKey: _seedKey!);
2023-07-25 17:36:24 +00:00
}
2023-07-24 16:56:20 +00:00
@override
2023-07-28 14:36:50 +00:00
Future<void> rescan({required int height}) async {
fetchTransactions();
_updateBalance();
return;
2023-07-24 16:56:20 +00:00
}
@override
2023-07-25 15:21:49 +00:00
Future<void> save() async {
2023-07-26 17:15:22 +00:00
await walletAddresses.updateAddressesInBox();
final path = await makePath();
await write(path: path, password: _password, data: toJSON());
await transactionHistory.save();
2023-07-24 16:56:20 +00:00
}
2023-07-25 15:21:49 +00:00
@override
String get seed => _mnemonic;
2023-08-04 14:54:20 +00:00
2023-08-04 13:33:48 +00:00
String get representative => _representativeAddress ?? "";
2023-07-24 16:56:20 +00:00
2023-07-25 15:21:49 +00:00
@action
2023-07-24 16:56:20 +00:00
@override
2023-07-25 15:21:49 +00:00
Future<void> startSync() async {
2023-07-27 17:02:10 +00:00
try {
syncStatus = AttemptingSyncStatus();
await _updateBalance();
await updateTransactions();
2023-08-01 17:48:22 +00:00
_receiveTimer?.cancel();
_receiveTimer = Timer.periodic(const Duration(seconds: 15), (timer) async {
// get our balance:
await _updateBalance();
// if we have anything to receive, process it:
if (balance[currency]!.receivableBalance > BigInt.zero) {
await _receiveAll();
}
});
2023-07-27 17:02:10 +00:00
syncStatus = SyncedSyncStatus();
} catch (e) {
2023-08-01 17:48:22 +00:00
print(e);
2023-07-27 17:02:10 +00:00
syncStatus = FailedSyncStatus();
2023-08-01 17:48:22 +00:00
rethrow;
2023-07-27 17:02:10 +00:00
}
2023-07-24 16:56:20 +00:00
}
2023-07-26 17:15:22 +00:00
Future<String> makePath() async => pathForWallet(name: walletInfo.name, type: walletInfo.type);
String toJSON() => json.encode({
2023-07-27 14:30:07 +00:00
'seedKey': _seedKey,
2023-07-26 17:15:22 +00:00
'mnemonic': _mnemonic,
2023-08-04 14:54:20 +00:00
'currentBalance': balance[currency]?.currentBalance.toString() ?? "0",
'receivableBalance': balance[currency]?.receivableBalance.toString() ?? "0",
2023-07-27 14:30:07 +00:00
'derivationType': _derivationType.toString()
2023-07-26 17:15:22 +00:00
});
2023-07-25 15:21:49 +00:00
static Future<NanoWallet> open({
required String name,
required String password,
required WalletInfo walletInfo,
}) async {
2023-07-27 14:30:07 +00:00
final path = await pathForWallet(name: name, type: walletInfo.type);
final jsonSource = await read(path: path, password: password);
2023-08-04 14:54:20 +00:00
2023-07-27 14:30:07 +00:00
final data = json.decode(jsonSource) as Map;
final mnemonic = data['mnemonic'] as String;
2023-07-27 17:02:10 +00:00
final balance = NanoBalance.fromString(
2023-08-04 14:54:20 +00:00
formattedCurrentBalance: data['currentBalance'] as String? ?? "0",
formattedReceivableBalance: data['receivableBalance'] as String? ?? "0");
2023-07-27 14:30:07 +00:00
DerivationType derivationType = DerivationType.bip39;
2023-07-27 17:02:10 +00:00
if (data['derivationType'] == "DerivationType.nano") {
2023-07-27 14:30:07 +00:00
derivationType = DerivationType.nano;
}
2023-08-14 22:02:12 +00:00
walletInfo.derivationType = derivationType;
2023-07-28 14:36:50 +00:00
return NanoWallet(
2023-08-14 22:02:12 +00:00
walletInfo: walletInfo,
2023-07-27 14:30:07 +00:00
password: password,
mnemonic: mnemonic,
initialBalance: balance,
);
2023-08-04 14:54:20 +00:00
// init() should always be run after this!
2023-07-24 16:56:20 +00:00
}
2023-07-25 15:21:49 +00:00
Future<void> _updateBalance() async {
2023-08-21 14:25:17 +00:00
try {
balance[currency] = await _client.getBalance(_publicAddress!);
} catch (e) {
2023-08-24 22:06:58 +00:00
print("Failed to get balance $e");
2023-08-21 14:25:17 +00:00
}
2023-07-25 15:21:49 +00:00
await save();
2023-07-24 16:56:20 +00:00
}
2023-08-02 15:47:00 +00:00
Future<void> _updateRep() async {
try {
2023-08-04 14:54:20 +00:00
final accountInfo = await _client.getAccountInfo(_publicAddress!);
2023-08-08 12:58:08 +00:00
if (accountInfo["error"] != null) {
// account not found:
_representativeAddress = NanoClient.DEFAULT_REPRESENTATIVE;
} else {
_representativeAddress = accountInfo["representative"] as String;
}
2023-08-02 15:47:00 +00:00
} catch (e) {
throw Exception("Failed to get representative address $e");
}
}
2023-08-10 22:34:20 +00:00
Future<void> regenerateAddress() async {
final String type = (_derivationType == DerivationType.nano) ? "standard" : "hd";
_privateKey =
await NanoUtil.uniSeedToPrivate(_seedKey!, this.walletAddresses.account!.id, type);
_publicAddress =
await NanoUtil.uniSeedToAddress(_seedKey!, this.walletAddresses.account!.id, type);
this.walletInfo.address = _publicAddress!;
this.walletAddresses.address = _publicAddress!;
}
2023-08-04 13:33:48 +00:00
Future<void> changeRep(String address) async {
try {
final String hash = await _client.changeRep(
2023-08-04 14:54:20 +00:00
privateKey: _privateKey!,
2023-08-04 13:33:48 +00:00
repAddress: address,
2023-08-04 14:54:20 +00:00
ourAddress: _publicAddress!,
2023-08-04 13:33:48 +00:00
);
if (hash.isNotEmpty) {
_representativeAddress = address;
}
} catch (e) {
throw Exception("Failed to change representative address $e");
}
}
2023-07-25 15:21:49 +00:00
Future<void>? updateBalance() async => await _updateBalance();
2023-07-24 16:56:20 +00:00
2023-07-25 15:21:49 +00:00
@override
Future<void> renameWalletFiles(String newWalletName) async {
2023-08-08 13:49:13 +00:00
final currentWalletPath = await pathForWallet(name: walletInfo.name, type: type);
final currentWalletFile = File(currentWalletPath);
final currentDirPath = await pathForWalletDir(name: walletInfo.name, type: type);
final currentTransactionsFile = File('$currentDirPath/$transactionsHistoryFileName');
// Copies current wallet files into new wallet name's dir and files
if (currentWalletFile.existsSync()) {
final newWalletPath = await pathForWallet(name: newWalletName, type: type);
await currentWalletFile.copy(newWalletPath);
}
if (currentTransactionsFile.existsSync()) {
final newDirPath = await pathForWalletDir(name: newWalletName, type: type);
await currentTransactionsFile.copy('$newDirPath/$transactionsHistoryFileName');
}
// Delete old name's dir and files
await Directory(currentDirPath).delete(recursive: true);
2023-07-24 16:56:20 +00:00
}
}