cake_wallet/lib/bitcoin/bitcoin_wallet.dart

383 lines
12 KiB
Dart
Raw Normal View History

2020-08-29 10:19:27 +00:00
import 'dart:async';
2020-05-12 12:04:54 +00:00
import 'dart:typed_data';
2020-06-20 07:10:00 +00:00
import 'dart:convert';
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_info.dart';
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-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-07-06 20:09:03 +00:00
import 'package:cake_wallet/src/domain/bitcoin/bitcoin_amount_format.dart';
import 'package:cake_wallet/src/domain/common/crypto_currency.dart';
import 'package:cake_wallet/src/domain/common/sync_status.dart';
2020-08-25 16:32:40 +00:00
import 'package:cake_wallet/src/domain/common/transaction_direction.dart';
import 'package:cake_wallet/src/domain/common/transaction_priority.dart';
import 'package:cw_monero/transaction_history.dart';
2020-07-06 20:09:03 +00:00
import 'package:flutter/cupertino.dart';
2020-06-20 07:10:00 +00:00
import 'package:mobx/mobx.dart';
2020-05-12 12:04:54 +00:00
import 'package:bip39/bip39.dart' as bip39;
2020-06-20 07:10:00 +00:00
import 'package:flutter/foundation.dart';
2020-05-12 12:04:54 +00:00
import 'package:bitcoin_flutter/bitcoin_flutter.dart' as bitcoin;
import 'package:bitcoin_flutter/src/payments/index.dart' show PaymentData;
2020-06-20 07:10:00 +00:00
import 'package:cake_wallet/src/domain/common/wallet_type.dart';
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';
import 'package:cake_wallet/bitcoin/electrum.dart';
2020-06-20 07:10:00 +00:00
import 'package:cake_wallet/bitcoin/bitcoin_balance.dart';
2020-05-12 12:04:54 +00:00
import 'package:cake_wallet/src/domain/common/node.dart';
2020-06-20 07:10:00 +00:00
import 'package:cake_wallet/core/wallet_base.dart';
2020-07-06 20:09:03 +00:00
import 'package:rxdart/rxdart.dart';
2020-08-25 16:32:40 +00:00
import 'package:hex/hex.dart';
2020-08-29 10:19:27 +00:00
import 'package:cake_wallet/di.dart';
import 'package:shared_preferences/shared_preferences.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-08-29 10:19:27 +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,
@required this.name,
List<BitcoinAddressRecord> initialAddresses,
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,
_addressesKeys = {} {
type = WalletType.bitcoin;
currency = CryptoCurrency.btc;
_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,
2020-06-20 07:10:00 +00:00
name: name,
2020-05-12 12:04:54 +00:00
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
String name;
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
Map<String, bitcoin.ECPair> _addressesKeys;
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);
int _accountIndex;
String _password;
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);
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
}