cake_wallet/lib/bitcoin/bitcoin_wallet.dart

265 lines
8.1 KiB
Dart
Raw Normal View History

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';
import 'package:cake_wallet/bitcoin/bitcoin_wallet_keys.dart';
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';
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-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 {
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);
final _addresses = data['addresses'] as List;
final addresses = <BitcoinAddressRecord>[];
final balance = BitcoinBalance.fromJSON(data['balance'] as String) ??
BitcoinBalance(confirmed: 0, unconfirmed: 0);
_addresses?.forEach((Object el) {
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
}
2020-06-20 07:10:00 +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}) {
2020-07-06 20:09:03 +00:00
type = WalletType.bitcoin;
currency = CryptoCurrency.btc;
2020-06-20 07:10:00 +00:00
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>();
2020-07-06 20:09:03 +00:00
syncStatus = NotConnectedSyncStatus();
2020-05-12 12:04:54 +00:00
2020-06-20 07:10:00 +00:00
_password = password;
_accountIndex = accountIndex;
}
2020-05-12 12:04:54 +00:00
@override
2020-06-20 07:10:00 +00:00
final BitcoinTransactionHistory transactionHistory;
final String path;
bitcoin.HDWallet hd;
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-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;
BehaviorSubject<Object> _addressUpdateSubject;
2020-06-20 07:10:00 +00:00
Future<void> init() async {
2020-07-06 20:09:03 +00:00
if (addresses.isEmpty) {
addresses.add(BitcoinAddressRecord(_getAddress(hd: hd, index: 0)));
}
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;
final address = BitcoinAddressRecord(
_getAddress(hd: hd, index: _accountIndex),
label: label);
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();
await _addressUpdateSubject?.close();
_addressUpdateSubject = eclient.addressUpdate(address: address);
await transactionHistory.update();
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();
await eclient.connect(host: 'electrum2.hodlister.co', port: 50002);
syncStatus = ConnectedSyncStatus();
} catch (e) {
print(e.toString);
syncStatus = FailedSyncStatus();
}
}
2020-05-12 12:04:54 +00:00
@override
2020-07-06 20:09:03 +00:00
Future<void> createTransaction(Object credentials) async {
final transactionCredentials = credentials as BitcoinTransactionCredentials;
final txb = bitcoin.TransactionBuilder(network: bitcoin.bitcoin);
final keyPair = bitcoin.ECPair.fromWIF(hd.wif);
final transactions = transactionHistory.transactions;
transactions.sort((q, w) => q.height.compareTo(w.height));
final prevTx = transactions.first;
txb.setVersion(1);
txb.addInput(prevTx, 0);
txb.addOutput(transactionCredentials.address,
doubleToBitcoinAmount(transactionCredentials.amount));
txb.sign(vin: 0, keyPair: keyPair);
final encoded = txb.build().toHex();
print('Enoded transaction $encoded');
await eclient.broadcastTransaction(transactionRaw: encoded);
}
2020-05-12 12:04:54 +00:00
@override
2020-06-20 07:10:00 +00:00
Future<void> save() async =>
await write(path: path, password: _password, data: toJSON());
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
String _getAddress({bitcoin.HDWallet hd, int index}) => bitcoin
2020-07-06 20:09:03 +00:00
.P2WPKH(
2020-05-12 12:04:54 +00:00
data: PaymentData(
pubkey: Uint8List.fromList(hd.derive(index).pubKey.codeUnits)))
.data
.address;
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-06-20 07:10:00 +00:00
addresses.map((record) => eclient.getBalance(address: record.address)));
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-05-12 12:04:54 +00:00
}