cake_wallet/lib/bitcoin/bitcoin_wallet.dart

473 lines
14 KiB
Dart
Raw Normal View History

2020-08-29 10:19:27 +00:00
import 'dart:async';
2020-06-20 07:10:00 +00:00
import 'dart:convert';
2020-12-08 21:47:08 +00:00
import 'package:cake_wallet/bitcoin/address_to_output_script.dart';
2020-11-27 09:52:05 +00:00
import 'package:cake_wallet/bitcoin/bitcoin_mnemonic.dart';
2021-01-27 13:51:51 +00:00
import 'package:cake_wallet/bitcoin/bitcoin_transaction_priority.dart';
import 'package:cake_wallet/entities/transaction_priority.dart';
2020-09-15 20:35:49 +00:00
import 'package:mobx/mobx.dart';
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/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),
2020-11-27 09:52:05 +00:00
hd = bitcoin.HDWallet.fromSeed(mnemonicToSeedBytes(mnemonic),
network: bitcoin.bitcoin)
.derivePath("m/0'/0"),
2020-08-25 16:32:40 +00:00
addresses = initialAddresses != null
2021-01-11 17:15:27 +00:00
? ObservableList<BitcoinAddressRecord>.of(initialAddresses.toSet())
2020-08-25 16:32:40 +00:00
: ObservableList<BitcoinAddressRecord>(),
syncStatus = NotConnectedSyncStatus(),
_password = password,
_accountIndex = accountIndex,
2021-02-12 22:38:34 +00:00
_feeRates = <int>[],
2020-09-15 20:35:49 +00:00
super(walletInfo) {
2021-01-27 13:51:51 +00:00
_unspent = [];
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,
2020-11-27 09:52:05 +00:00
@required WalletInfo walletInfo,
2020-06-20 07:10:00 +00:00
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,
walletInfo: walletInfo);
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,
@required WalletInfo walletInfo,
2020-06-20 07:10:00 +00:00
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,
walletInfo: walletInfo);
2020-05-12 12:04:54 +00:00
}
2021-01-27 13:51:51 +00:00
static int estimatedTransactionSize(int inputsCount, int outputsCounts) =>
inputsCount * 146 + outputsCounts * 33 + 8;
2021-01-05 18:31:03 +00:00
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
2021-01-27 13:51:51 +00:00
List<BitcoinUnspent> _unspent;
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;
2021-02-12 22:38:34 +00:00
List<int> _feeRates;
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 {
if (addresses.isEmpty || addresses.length < 33) {
final addressesCount = 33 - addresses.length;
2021-01-12 11:14:28 +00:00
await generateNewAddresses(addressesCount, startIndex: addresses.length);
2020-07-06 20:09:03 +00:00
}
address = addresses[_accountIndex].address;
2020-07-06 20:09:03 +00:00
transactionHistory.wallet = this;
2020-06-20 07:10:00 +00:00
await transactionHistory.init();
}
2020-05-12 12:04:54 +00:00
@action
2021-04-06 15:54:22 +00:00
Future<void> nextAddress() async {
_accountIndex += 1;
if (_accountIndex >= addresses.length) {
_accountIndex = 0;
}
address = addresses[_accountIndex].address;
await save();
}
Future<BitcoinAddressRecord> generateNewAddress() async {
2020-06-20 07:10:00 +00:00
_accountIndex += 1;
2020-08-25 16:32:40 +00:00
final address = BitcoinAddressRecord(_getAddress(index: _accountIndex),
index: _accountIndex);
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
Future<List<BitcoinAddressRecord>> generateNewAddresses(int count,
{int startIndex = 0}) async {
2020-11-30 17:17:44 +00:00
final list = <BitcoinAddressRecord>[];
for (var i = startIndex; i < count + startIndex; i++) {
final address = BitcoinAddressRecord(_getAddress(index: i), index: i);
2020-11-30 17:17:44 +00:00
list.add(address);
}
addresses.addAll(list);
await save();
return list;
}
Future<void> updateAddress(String address) async {
2020-06-20 07:10:00 +00:00
for (final addr in addresses) {
if (addr.address == address) {
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-11-30 17:17:44 +00:00
transactionHistory.updateAsync(onFinished: () {
print('transactionHistory update finished!');
transactionHistory.save();
});
2020-08-25 16:32:40 +00:00
_subscribeForUpdates();
2020-07-06 20:09:03 +00:00
await _updateBalance();
2021-01-27 13:51:51 +00:00
await _updateUnspent();
2021-02-12 22:38:34 +00:00
_feeRates = await eclient.feeRates();
Timer.periodic(const Duration(minutes: 1),
(timer) async => _feeRates = await eclient.feeRates());
2020-07-06 20:09:03 +00:00
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 {
const minAmount = 546;
2020-07-06 20:09:03 +00:00
final transactionCredentials = credentials as BitcoinTransactionCredentials;
2020-08-25 16:32:40 +00:00
final inputs = <BitcoinUnspent>[];
2021-01-27 13:51:51 +00:00
final allAmountFee =
calculateEstimatedFee(transactionCredentials.priority, null);
final allAmount = balance.confirmed - allAmountFee;
2021-01-27 13:51:51 +00:00
var fee = 0;
final credentialsAmount = transactionCredentials.amount != null
2021-01-05 18:31:03 +00:00
? stringDoubleToBitcoinAmount(transactionCredentials.amount)
: 0;
final amount = transactionCredentials.amount == null ||
allAmount - credentialsAmount < minAmount
? allAmount
: credentialsAmount;
2020-07-06 20:09:03 +00:00
final txb = bitcoin.TransactionBuilder(network: bitcoin.bitcoin);
2020-08-25 16:32:40 +00:00
final changeAddress = address;
2021-01-27 13:51:51 +00:00
var leftAmount = amount;
2020-08-25 16:32:40 +00:00
var totalInputAmount = 0;
2021-01-27 13:51:51 +00:00
if (_unspent.isEmpty) {
await _updateUnspent();
2021-01-05 18:31:03 +00:00
}
2021-01-27 13:51:51 +00:00
for (final utx in _unspent) {
leftAmount = leftAmount - utx.value;
totalInputAmount += utx.value;
inputs.add(utx);
2020-08-25 16:32:40 +00:00
if (leftAmount <= 0) {
break;
}
}
if (inputs.isEmpty) {
throw BitcoinTransactionNoInputsException();
}
2021-01-27 13:51:51 +00:00
final totalAmount = amount + fee;
fee = transactionCredentials.amount != null
? feeAmountForPriority(transactionCredentials.priority, inputs.length,
amount == allAmount ? 1 : 2)
2021-01-27 13:51:51 +00:00
: allAmountFee;
if (totalAmount > balance.confirmed) {
2020-08-25 16:32:40 +00:00
throw BitcoinTransactionWrongBalanceException();
}
2021-01-27 13:51:51 +00:00
if (amount <= 0 || totalInputAmount < amount) {
throw BitcoinTransactionWrongBalanceException();
}
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);
}
});
2020-12-08 21:47:08 +00:00
txb.addOutput(
addressToOutputScript(transactionCredentials.address), amount);
2020-08-25 16:32:40 +00:00
2021-01-27 13:51:51 +00:00
final estimatedSize = estimatedTransactionSize(inputs.length, 2);
2021-02-12 22:38:34 +00:00
final feeAmount = feeRate(transactionCredentials.priority) * estimatedSize;
2021-01-27 13:51:51 +00:00
final changeValue = totalInputAmount - amount - feeAmount;
if (changeValue > minAmount) {
2020-08-25 16:32:40 +00:00
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) async {
transactionHistory.addOne(transaction);
await _updateBalance();
});
2020-08-25 16:32:40 +00:00
}
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
2021-02-12 22:38:34 +00:00
int feeRate(TransactionPriority priority) {
if (priority is BitcoinTransactionPriority) {
return _feeRates[priority.raw];
}
return 0;
}
int feeAmountForPriority(BitcoinTransactionPriority priority, int inputsCount,
int outputsCount) =>
feeRate(priority) * estimatedTransactionSize(inputsCount, outputsCount);
2020-08-25 16:32:40 +00:00
@override
2021-01-27 13:51:51 +00:00
int calculateEstimatedFee(TransactionPriority priority, int amount) {
if (priority is BitcoinTransactionPriority) {
int inputsCount = 0;
if (amount != null) {
int totalValue = 0;
for (final input in _unspent) {
if (totalValue >= amount) {
break;
}
totalValue += input.value;
inputsCount += 1;
}
} else {
inputsCount = _unspent.length;
}
// If send all, then we have no change value
return feeAmountForPriority(
priority, inputsCount, amount != null ? 2 : 1);
2021-01-27 13:51:51 +00:00
}
return 0;
}
2020-08-25 16:32:40 +00:00
@override
2020-11-30 17:17:44 +00:00
Future<void> save() async {
await write(path: path, password: _password, data: toJSON());
await transactionHistory.save();
}
2020-08-25 16:32:40 +00:00
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
}
@override
void close() async {
await eclient.close();
}
2021-01-27 13:51:51 +00:00
Future<void> _updateUnspent() async {
final unspent = await Future.wait(addresses.map((address) => eclient
.getListUnspentWithAddress(address.address)
.then((unspent) => unspent
.map((unspent) => BitcoinUnspent.fromJSON(address, unspent)))));
_unspent = unspent.expand((e) => e).toList();
}
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 {
2021-01-27 13:51:51 +00:00
try {
await _updateBalance();
await _updateUnspent();
transactionHistory.updateAsync();
} catch (e) {
print(e.toString());
}
2020-08-25 16:32:40 +00:00
});
});
}
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);
2020-05-12 12:04:54 +00:00
}