2020-08-29 10:19:27 +00:00
|
|
|
import 'dart:async';
|
2020-06-20 07:10:00 +00:00
|
|
|
import 'dart:convert';
|
2020-09-15 20:35:49 +00:00
|
|
|
import 'package:mobx/mobx.dart';
|
|
|
|
import 'package:bip39/bip39.dart' as bip39;
|
|
|
|
import 'package:flutter/foundation.dart';
|
|
|
|
import 'package:rxdart/rxdart.dart';
|
|
|
|
import 'package:bitcoin_flutter/bitcoin_flutter.dart' as bitcoin;
|
2020-07-06 20:09:03 +00:00
|
|
|
import 'package:cake_wallet/bitcoin/bitcoin_transaction_credentials.dart';
|
2020-08-25 16:32:40 +00:00
|
|
|
import 'package:cake_wallet/bitcoin/bitcoin_transaction_no_inputs_exception.dart';
|
|
|
|
import 'package:cake_wallet/bitcoin/bitcoin_transaction_wrong_balance_exception.dart';
|
|
|
|
import 'package:cake_wallet/bitcoin/bitcoin_unspent.dart';
|
2020-07-06 20:09:03 +00:00
|
|
|
import 'package:cake_wallet/bitcoin/bitcoin_wallet_keys.dart';
|
2020-09-15 20:35:49 +00:00
|
|
|
import 'package:cake_wallet/bitcoin/electrum.dart';
|
2020-08-25 16:32:40 +00:00
|
|
|
import 'package:cake_wallet/bitcoin/pending_bitcoin_transaction.dart';
|
|
|
|
import 'package:cake_wallet/bitcoin/script_hash.dart';
|
|
|
|
import 'package:cake_wallet/bitcoin/utils.dart';
|
2020-09-21 11:50:26 +00:00
|
|
|
import 'package:cake_wallet/bitcoin/bitcoin_amount_format.dart';
|
|
|
|
import 'package:cake_wallet/entities/sync_status.dart';
|
|
|
|
import 'package:cake_wallet/entities/transaction_priority.dart';
|
|
|
|
import 'package:cake_wallet/entities/wallet_info.dart';
|
2020-06-20 07:10:00 +00:00
|
|
|
import 'package:cake_wallet/bitcoin/bitcoin_transaction_history.dart';
|
|
|
|
import 'package:cake_wallet/bitcoin/bitcoin_address_record.dart';
|
2020-05-12 12:04:54 +00:00
|
|
|
import 'package:cake_wallet/bitcoin/file.dart';
|
2020-06-20 07:10:00 +00:00
|
|
|
import 'package:cake_wallet/bitcoin/bitcoin_balance.dart';
|
2020-09-21 11:50:26 +00:00
|
|
|
import 'package:cake_wallet/entities/node.dart';
|
2020-06-20 07:10:00 +00:00
|
|
|
import 'package:cake_wallet/core/wallet_base.dart';
|
2020-05-12 12:04:54 +00:00
|
|
|
|
2020-06-20 07:10:00 +00:00
|
|
|
part 'bitcoin_wallet.g.dart';
|
2020-05-12 12:04:54 +00:00
|
|
|
|
2020-06-20 07:10:00 +00:00
|
|
|
class BitcoinWallet = BitcoinWalletBase with _$BitcoinWallet;
|
2020-05-12 12:04:54 +00:00
|
|
|
|
2020-06-20 07:10:00 +00:00
|
|
|
abstract class BitcoinWalletBase extends WalletBase<BitcoinBalance> with Store {
|
2020-08-25 16:32:40 +00:00
|
|
|
BitcoinWalletBase._internal(
|
|
|
|
{@required this.eclient,
|
|
|
|
@required this.path,
|
|
|
|
@required String password,
|
2020-09-15 20:35:49 +00:00
|
|
|
@required WalletInfo walletInfo,
|
|
|
|
@required List<BitcoinAddressRecord> initialAddresses,
|
2020-08-25 16:32:40 +00:00
|
|
|
int accountIndex = 0,
|
|
|
|
this.transactionHistory,
|
|
|
|
this.mnemonic,
|
|
|
|
BitcoinBalance initialBalance})
|
|
|
|
: balance =
|
|
|
|
initialBalance ?? BitcoinBalance(confirmed: 0, unconfirmed: 0),
|
|
|
|
hd = bitcoin.HDWallet.fromSeed(bip39.mnemonicToSeed(mnemonic),
|
|
|
|
network: bitcoin.bitcoin),
|
|
|
|
addresses = initialAddresses != null
|
|
|
|
? ObservableList<BitcoinAddressRecord>.of(initialAddresses)
|
|
|
|
: ObservableList<BitcoinAddressRecord>(),
|
|
|
|
syncStatus = NotConnectedSyncStatus(),
|
|
|
|
_password = password,
|
|
|
|
_accountIndex = accountIndex,
|
2020-09-15 20:35:49 +00:00
|
|
|
super(walletInfo) {
|
2020-08-25 16:32:40 +00:00
|
|
|
_scripthashesUpdateSubject = {};
|
|
|
|
}
|
|
|
|
|
2020-06-20 07:10:00 +00:00
|
|
|
static BitcoinWallet fromJSON(
|
|
|
|
{@required String password,
|
|
|
|
@required String name,
|
|
|
|
@required String dirPath,
|
|
|
|
String jsonSource}) {
|
|
|
|
final data = json.decode(jsonSource) as Map;
|
|
|
|
final mnemonic = data['mnemonic'] as String;
|
2020-05-12 12:04:54 +00:00
|
|
|
final accountIndex =
|
2020-07-06 20:09:03 +00:00
|
|
|
(data['account_index'] == 'null' || data['account_index'] == null)
|
2020-05-12 12:04:54 +00:00
|
|
|
? 0
|
2020-06-20 07:10:00 +00:00
|
|
|
: int.parse(data['account_index'] as String);
|
2020-08-25 16:32:40 +00:00
|
|
|
final _addresses = data['addresses'] as List ?? <Object>[];
|
2020-06-20 07:10:00 +00:00
|
|
|
final addresses = <BitcoinAddressRecord>[];
|
|
|
|
final balance = BitcoinBalance.fromJSON(data['balance'] as String) ??
|
|
|
|
BitcoinBalance(confirmed: 0, unconfirmed: 0);
|
|
|
|
|
2020-08-25 16:32:40 +00:00
|
|
|
_addresses.forEach((Object el) {
|
2020-06-20 07:10:00 +00:00
|
|
|
if (el is String) {
|
|
|
|
addresses.add(BitcoinAddressRecord.fromJSON(el));
|
|
|
|
}
|
|
|
|
});
|
2020-05-12 12:04:54 +00:00
|
|
|
|
2020-06-20 07:10:00 +00:00
|
|
|
return BitcoinWalletBase.build(
|
|
|
|
dirPath: dirPath,
|
2020-05-12 12:04:54 +00:00
|
|
|
mnemonic: mnemonic,
|
|
|
|
password: password,
|
|
|
|
name: name,
|
2020-06-20 07:10:00 +00:00
|
|
|
accountIndex: accountIndex,
|
|
|
|
initialAddresses: addresses,
|
|
|
|
initialBalance: balance);
|
2020-05-12 12:04:54 +00:00
|
|
|
}
|
|
|
|
|
2020-06-20 07:10:00 +00:00
|
|
|
static BitcoinWallet build(
|
2020-05-12 12:04:54 +00:00
|
|
|
{@required String mnemonic,
|
|
|
|
@required String password,
|
|
|
|
@required String name,
|
2020-06-20 07:10:00 +00:00
|
|
|
@required String dirPath,
|
|
|
|
List<BitcoinAddressRecord> initialAddresses,
|
|
|
|
BitcoinBalance initialBalance,
|
|
|
|
int accountIndex = 0}) {
|
|
|
|
final walletPath = '$dirPath/$name';
|
2020-05-12 12:04:54 +00:00
|
|
|
final eclient = ElectrumClient();
|
2020-06-20 07:10:00 +00:00
|
|
|
final history = BitcoinTransactionHistory(
|
|
|
|
eclient: eclient, dirPath: dirPath, password: password);
|
|
|
|
|
|
|
|
return BitcoinWallet._internal(
|
2020-05-12 12:04:54 +00:00
|
|
|
eclient: eclient,
|
|
|
|
path: walletPath,
|
|
|
|
mnemonic: mnemonic,
|
|
|
|
password: password,
|
2020-06-20 07:10:00 +00:00
|
|
|
accountIndex: accountIndex,
|
|
|
|
initialAddresses: initialAddresses,
|
|
|
|
initialBalance: initialBalance,
|
|
|
|
transactionHistory: history);
|
2020-05-12 12:04:54 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
@override
|
2020-06-20 07:10:00 +00:00
|
|
|
final BitcoinTransactionHistory transactionHistory;
|
|
|
|
final String path;
|
2020-08-25 16:32:40 +00:00
|
|
|
final bitcoin.HDWallet hd;
|
2020-06-20 07:10:00 +00:00
|
|
|
final ElectrumClient eclient;
|
|
|
|
final String mnemonic;
|
2020-05-12 12:04:54 +00:00
|
|
|
|
|
|
|
@override
|
2020-06-20 07:10:00 +00:00
|
|
|
@observable
|
|
|
|
String address;
|
2020-05-12 12:04:54 +00:00
|
|
|
|
|
|
|
@override
|
2020-06-20 07:10:00 +00:00
|
|
|
@observable
|
|
|
|
BitcoinBalance balance;
|
2020-05-12 12:04:54 +00:00
|
|
|
|
|
|
|
@override
|
2020-07-06 20:09:03 +00:00
|
|
|
@observable
|
|
|
|
SyncStatus syncStatus;
|
2020-05-12 12:04:54 +00:00
|
|
|
|
2020-06-20 07:10:00 +00:00
|
|
|
ObservableList<BitcoinAddressRecord> addresses;
|
2020-05-12 12:04:54 +00:00
|
|
|
|
2020-08-25 16:32:40 +00:00
|
|
|
List<String> get scriptHashes =>
|
|
|
|
addresses.map((addr) => scriptHash(addr.address)).toList();
|
|
|
|
|
2020-06-20 07:10:00 +00:00
|
|
|
String get xpub => hd.base58;
|
2020-05-12 12:04:54 +00:00
|
|
|
|
2020-07-06 20:09:03 +00:00
|
|
|
@override
|
|
|
|
String get seed => mnemonic;
|
|
|
|
|
|
|
|
@override
|
|
|
|
BitcoinWalletKeys get keys => BitcoinWalletKeys(
|
|
|
|
wif: hd.wif, privateKey: hd.privKey, publicKey: hd.pubKey);
|
|
|
|
|
2020-09-15 20:35:49 +00:00
|
|
|
final String _password;
|
2020-07-06 20:09:03 +00:00
|
|
|
int _accountIndex;
|
2020-08-25 16:32:40 +00:00
|
|
|
Map<String, BehaviorSubject<Object>> _scripthashesUpdateSubject;
|
2020-07-06 20:09:03 +00:00
|
|
|
|
2020-06-20 07:10:00 +00:00
|
|
|
Future<void> init() async {
|
2020-07-06 20:09:03 +00:00
|
|
|
if (addresses.isEmpty) {
|
2020-08-25 16:32:40 +00:00
|
|
|
final index = 0;
|
|
|
|
addresses
|
|
|
|
.add(BitcoinAddressRecord(_getAddress(index: index), index: index));
|
2020-07-06 20:09:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
address = addresses.first.address;
|
|
|
|
transactionHistory.wallet = this;
|
2020-06-20 07:10:00 +00:00
|
|
|
await transactionHistory.init();
|
|
|
|
}
|
2020-05-12 12:04:54 +00:00
|
|
|
|
2020-06-20 07:10:00 +00:00
|
|
|
Future<BitcoinAddressRecord> generateNewAddress({String label}) async {
|
|
|
|
_accountIndex += 1;
|
2020-08-25 16:32:40 +00:00
|
|
|
final address = BitcoinAddressRecord(_getAddress(index: _accountIndex),
|
|
|
|
index: _accountIndex, label: label);
|
2020-06-20 07:10:00 +00:00
|
|
|
addresses.add(address);
|
2020-05-12 12:04:54 +00:00
|
|
|
|
2020-06-20 07:10:00 +00:00
|
|
|
await save();
|
2020-05-12 12:04:54 +00:00
|
|
|
|
2020-06-20 07:10:00 +00:00
|
|
|
return address;
|
|
|
|
}
|
2020-05-12 12:04:54 +00:00
|
|
|
|
2020-06-20 07:10:00 +00:00
|
|
|
Future<void> updateAddress(String address, {String label}) async {
|
|
|
|
for (final addr in addresses) {
|
|
|
|
if (addr.address == address) {
|
|
|
|
addr.label = label;
|
|
|
|
await save();
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-05-12 12:04:54 +00:00
|
|
|
|
2020-07-06 20:09:03 +00:00
|
|
|
@action
|
2020-05-12 12:04:54 +00:00
|
|
|
@override
|
2020-07-06 20:09:03 +00:00
|
|
|
Future<void> startSync() async {
|
|
|
|
try {
|
|
|
|
syncStatus = StartingSyncStatus();
|
2020-08-27 16:54:34 +00:00
|
|
|
transactionHistory.updateAsync(
|
|
|
|
onFinished: () => print('transactionHistory update finished!'));
|
2020-08-25 16:32:40 +00:00
|
|
|
_subscribeForUpdates();
|
2020-07-06 20:09:03 +00:00
|
|
|
await _updateBalance();
|
|
|
|
syncStatus = SyncedSyncStatus();
|
|
|
|
} catch (e) {
|
|
|
|
print(e.toString());
|
|
|
|
syncStatus = FailedSyncStatus();
|
|
|
|
}
|
|
|
|
}
|
2020-05-12 12:04:54 +00:00
|
|
|
|
2020-07-06 20:09:03 +00:00
|
|
|
@action
|
2020-05-12 12:04:54 +00:00
|
|
|
@override
|
2020-07-06 20:09:03 +00:00
|
|
|
Future<void> connectToNode({@required Node node}) async {
|
|
|
|
try {
|
|
|
|
syncStatus = ConnectingSyncStatus();
|
2020-08-27 16:54:34 +00:00
|
|
|
await eclient.connectToUri(node.uri);
|
2020-08-29 10:19:27 +00:00
|
|
|
eclient.onConnectionStatusChange = (bool isConnected) {
|
|
|
|
if (!isConnected) {
|
|
|
|
syncStatus = LostConnectionSyncStatus();
|
|
|
|
}
|
|
|
|
};
|
2020-07-06 20:09:03 +00:00
|
|
|
syncStatus = ConnectedSyncStatus();
|
|
|
|
} catch (e) {
|
2020-08-25 16:32:40 +00:00
|
|
|
print(e.toString());
|
2020-07-06 20:09:03 +00:00
|
|
|
syncStatus = FailedSyncStatus();
|
|
|
|
}
|
|
|
|
}
|
2020-05-12 12:04:54 +00:00
|
|
|
|
|
|
|
@override
|
2020-08-25 16:32:40 +00:00
|
|
|
Future<PendingBitcoinTransaction> createTransaction(
|
|
|
|
Object credentials) async {
|
2020-07-06 20:09:03 +00:00
|
|
|
final transactionCredentials = credentials as BitcoinTransactionCredentials;
|
2020-08-25 16:32:40 +00:00
|
|
|
final inputs = <BitcoinUnspent>[];
|
|
|
|
final fee = _feeMultiplier(transactionCredentials.priority);
|
|
|
|
final amount = transactionCredentials.amount != null
|
|
|
|
? doubleToBitcoinAmount(transactionCredentials.amount)
|
|
|
|
: balance.total - fee;
|
|
|
|
final totalAmount = amount + fee;
|
2020-07-06 20:09:03 +00:00
|
|
|
final txb = bitcoin.TransactionBuilder(network: bitcoin.bitcoin);
|
2020-08-25 16:32:40 +00:00
|
|
|
var leftAmount = totalAmount;
|
|
|
|
final changeAddress = address;
|
|
|
|
var totalInputAmount = 0;
|
|
|
|
|
|
|
|
final unspent = addresses.map((address) => eclient
|
|
|
|
.getListUnspentWithAddress(address.address)
|
|
|
|
.then((unspent) => unspent
|
|
|
|
.map((unspent) => BitcoinUnspent.fromJSON(address, unspent))));
|
|
|
|
|
|
|
|
for (final unptsFutures in unspent) {
|
|
|
|
final utxs = await unptsFutures;
|
|
|
|
|
|
|
|
for (final utx in utxs) {
|
|
|
|
final inAmount = utx.value > totalAmount ? totalAmount : utx.value;
|
|
|
|
leftAmount = leftAmount - inAmount;
|
|
|
|
totalInputAmount += inAmount;
|
|
|
|
inputs.add(utx);
|
|
|
|
|
|
|
|
if (leftAmount <= 0) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (leftAmount <= 0) {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (inputs.isEmpty) {
|
|
|
|
throw BitcoinTransactionNoInputsException();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (amount <= 0 || totalInputAmount < amount) {
|
|
|
|
throw BitcoinTransactionWrongBalanceException();
|
|
|
|
}
|
|
|
|
|
|
|
|
final changeValue = totalInputAmount - amount - fee;
|
2020-07-06 20:09:03 +00:00
|
|
|
|
|
|
|
txb.setVersion(1);
|
2020-05-12 12:04:54 +00:00
|
|
|
|
2020-08-25 16:32:40 +00:00
|
|
|
inputs.forEach((input) {
|
|
|
|
if (input.isP2wpkh) {
|
|
|
|
final p2wpkh = bitcoin
|
|
|
|
.P2WPKH(
|
|
|
|
data: generatePaymentData(hd: hd, index: input.address.index),
|
|
|
|
network: bitcoin.bitcoin)
|
|
|
|
.data;
|
|
|
|
|
|
|
|
txb.addInput(input.hash, input.vout, null, p2wpkh.output);
|
|
|
|
} else {
|
|
|
|
txb.addInput(input.hash, input.vout);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
txb.addOutput(transactionCredentials.address, amount);
|
|
|
|
|
|
|
|
if (changeValue > 0) {
|
|
|
|
txb.addOutput(changeAddress, changeValue);
|
|
|
|
}
|
|
|
|
|
|
|
|
for (var i = 0; i < inputs.length; i++) {
|
|
|
|
final input = inputs[i];
|
|
|
|
final keyPair = generateKeyPair(hd: hd, index: input.address.index);
|
|
|
|
final witnessValue = input.isP2wpkh ? input.value : null;
|
|
|
|
|
|
|
|
txb.sign(vin: i, keyPair: keyPair, witnessValue: witnessValue);
|
|
|
|
}
|
|
|
|
|
|
|
|
return PendingBitcoinTransaction(txb.build(),
|
|
|
|
eclient: eclient, amount: amount, fee: fee)
|
|
|
|
..addListener((transaction) => transactionHistory.addOne(transaction));
|
|
|
|
}
|
2020-05-12 12:04:54 +00:00
|
|
|
|
2020-06-20 07:10:00 +00:00
|
|
|
String toJSON() => json.encode({
|
|
|
|
'mnemonic': mnemonic,
|
|
|
|
'account_index': _accountIndex.toString(),
|
|
|
|
'addresses': addresses.map((addr) => addr.toJSON()).toList(),
|
|
|
|
'balance': balance?.toJSON()
|
|
|
|
});
|
2020-05-12 12:04:54 +00:00
|
|
|
|
2020-08-25 16:32:40 +00:00
|
|
|
@override
|
|
|
|
double calculateEstimatedFee(TransactionPriority priority) =>
|
|
|
|
bitcoinAmountToDouble(amount: _feeMultiplier(priority));
|
|
|
|
|
|
|
|
@override
|
|
|
|
Future<void> save() async =>
|
|
|
|
await write(path: path, password: _password, data: toJSON());
|
|
|
|
|
|
|
|
bitcoin.ECPair keyPairFor({@required int index}) =>
|
|
|
|
generateKeyPair(hd: hd, index: index);
|
|
|
|
|
2020-09-21 11:50:26 +00:00
|
|
|
@override
|
|
|
|
Future<void> rescan({int height}) async {
|
|
|
|
// FIXME: Unimplemented
|
|
|
|
}
|
|
|
|
|
2020-08-25 16:32:40 +00:00
|
|
|
void _subscribeForUpdates() {
|
|
|
|
scriptHashes.forEach((sh) async {
|
|
|
|
await _scripthashesUpdateSubject[sh]?.close();
|
|
|
|
_scripthashesUpdateSubject[sh] = eclient.scripthashUpdate(sh);
|
|
|
|
_scripthashesUpdateSubject[sh].listen((event) async {
|
|
|
|
transactionHistory.updateAsync();
|
|
|
|
await _updateBalance();
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
2020-05-12 12:04:54 +00:00
|
|
|
|
2020-07-06 20:09:03 +00:00
|
|
|
Future<BitcoinBalance> _fetchBalances() async {
|
2020-05-12 12:04:54 +00:00
|
|
|
final balances = await Future.wait(
|
2020-08-25 16:32:40 +00:00
|
|
|
scriptHashes.map((sHash) => eclient.getBalance(sHash)));
|
2020-07-06 20:09:03 +00:00
|
|
|
final balance = balances.fold(
|
|
|
|
BitcoinBalance(confirmed: 0, unconfirmed: 0),
|
|
|
|
(BitcoinBalance acc, val) => BitcoinBalance(
|
|
|
|
confirmed: (val['confirmed'] as int ?? 0) + (acc.confirmed ?? 0),
|
|
|
|
unconfirmed:
|
|
|
|
(val['unconfirmed'] as int ?? 0) + (acc.unconfirmed ?? 0)));
|
2020-05-12 12:04:54 +00:00
|
|
|
|
|
|
|
return balance;
|
|
|
|
}
|
2020-07-06 20:09:03 +00:00
|
|
|
|
|
|
|
Future<void> _updateBalance() async {
|
|
|
|
balance = await _fetchBalances();
|
|
|
|
await save();
|
|
|
|
}
|
2020-08-25 16:32:40 +00:00
|
|
|
|
|
|
|
String _getAddress({@required int index}) =>
|
|
|
|
generateAddress(hd: hd, index: index);
|
|
|
|
|
|
|
|
int _feeMultiplier(TransactionPriority priority) {
|
|
|
|
switch (priority) {
|
|
|
|
case TransactionPriority.slow:
|
|
|
|
return 6000;
|
|
|
|
case TransactionPriority.regular:
|
|
|
|
return 9000;
|
|
|
|
case TransactionPriority.fast:
|
|
|
|
return 15000;
|
|
|
|
default:
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
}
|
2020-05-12 12:04:54 +00:00
|
|
|
}
|