mirror of
https://github.com/Such-Software/hash-wallet.git
synced 2026-12-04 12:34:14 +01:00
TMP
This commit is contained in:
@@ -1,17 +1,19 @@
|
||||
import 'dart:convert';
|
||||
|
||||
class BitcoinAddressRecord {
|
||||
BitcoinAddressRecord(this.address, {this.label});
|
||||
BitcoinAddressRecord(this.address, {this.label, this.index});
|
||||
|
||||
factory BitcoinAddressRecord.fromJSON(String jsonSource) {
|
||||
final decoded = json.decode(jsonSource) as Map;
|
||||
|
||||
return BitcoinAddressRecord(decoded['address'] as String,
|
||||
label: decoded['label'] as String);
|
||||
label: decoded['label'] as String, index: decoded['index'] as int);
|
||||
}
|
||||
|
||||
final String address;
|
||||
int index;
|
||||
String label;
|
||||
|
||||
String toJSON() => json.encode({'label': label, 'address': address});
|
||||
String toJSON() =>
|
||||
json.encode({'label': label, 'address': address, 'index': index});
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import 'package:cake_wallet/src/domain/common/transaction_priority.dart';
|
||||
|
||||
class BitcoinTransactionCredentials {
|
||||
const BitcoinTransactionCredentials(this.address, this.amount);
|
||||
BitcoinTransactionCredentials(this.address, this.amount, this.priority);
|
||||
|
||||
final String address;
|
||||
final double amount;
|
||||
TransactionPriority priority;
|
||||
}
|
||||
|
||||
@@ -6,8 +6,6 @@ import 'package:cake_wallet/bitcoin/file.dart';
|
||||
import 'package:cake_wallet/bitcoin/bitcoin_wallet.dart';
|
||||
import 'package:cake_wallet/bitcoin/bitcoin_transaction_info.dart';
|
||||
import 'package:cake_wallet/bitcoin/electrum.dart';
|
||||
import 'package:cake_wallet/src/domain/common/transaction_info.dart';
|
||||
import 'package:cake_wallet/src/domain/common/transaction_direction.dart';
|
||||
|
||||
part 'bitcoin_transaction_history.g.dart';
|
||||
|
||||
@@ -24,100 +22,176 @@ abstract class BitcoinTransactionHistoryBase
|
||||
{this.eclient, String dirPath, @required String password})
|
||||
: path = '$dirPath/$_transactionsHistoryFileName',
|
||||
_password = password,
|
||||
_height = 0;
|
||||
_height = 0,
|
||||
_isUpdating = false {
|
||||
transactions = ObservableMap<String, BitcoinTransactionInfo>();
|
||||
}
|
||||
|
||||
BitcoinWalletBase wallet;
|
||||
final ElectrumClient eclient;
|
||||
final String path;
|
||||
final String _password;
|
||||
int _height;
|
||||
bool _isUpdating;
|
||||
|
||||
Future<void> init() async {
|
||||
final info = await _read();
|
||||
_height = info['height'] as int ?? _height;
|
||||
transactions = ObservableList.of(
|
||||
info['transactions'] as List<BitcoinTransactionInfo> ??
|
||||
<BitcoinTransactionInfo>[]);
|
||||
await _load();
|
||||
}
|
||||
|
||||
@override
|
||||
Future update() async {
|
||||
await super.update();
|
||||
_updateHeight();
|
||||
if (_isUpdating) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
_isUpdating = true;
|
||||
final txs = await fetchTransactions();
|
||||
await add(txs);
|
||||
_isUpdating = false;
|
||||
} catch (_) {
|
||||
_isUpdating = false;
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<BitcoinTransactionInfo>> fetchTransactions() async {
|
||||
final addresses = wallet.addresses;
|
||||
Future<Map<String, BitcoinTransactionInfo>> fetchTransactions() async {
|
||||
final histories =
|
||||
addresses.map((record) => eclient.getHistory(address: record.address));
|
||||
wallet.scriptHashes.map((scriptHash) => eclient.getHistory(scriptHash));
|
||||
final _historiesWithDetails = await Future.wait(histories)
|
||||
.then((histories) => histories
|
||||
.map((h) => h.where((tx) => (tx['height'] as int) > _height))
|
||||
// .map((h) => h.where((tx) {
|
||||
// final height = tx['height'] as int ?? 0;
|
||||
// // FIXME: Filter only needed transactions
|
||||
// final _tx = get(tx['tx_hash'] as String);
|
||||
//
|
||||
// return height == 0 || height > _height;
|
||||
// }))
|
||||
.expand((i) => i)
|
||||
.toList())
|
||||
.then((histories) => histories.map((tx) => fetchTransactionInfo(
|
||||
hash: tx['tx_hash'] as String, height: tx['height'] as int)));
|
||||
final historiesWithDetails = await Future.wait(_historiesWithDetails);
|
||||
|
||||
return historiesWithDetails
|
||||
.map((info) => BitcoinTransactionInfo.fromHexAndHeader(
|
||||
info['raw'] as String, info['header'] as Map<String, Object>,
|
||||
addresses: addresses.map((record) => record.address).toList()))
|
||||
.toList();
|
||||
return historiesWithDetails.fold<Map<String, BitcoinTransactionInfo>>(
|
||||
<String, BitcoinTransactionInfo>{}, (acc, tx) {
|
||||
acc[tx.id] = tx;
|
||||
return acc;
|
||||
});
|
||||
}
|
||||
|
||||
Future<Map<String, Object>> fetchTransactionInfo(
|
||||
Future<BitcoinTransactionInfo> fetchTransactionInfo(
|
||||
{@required String hash, @required int height}) async {
|
||||
final rawFetching = eclient.getTransactionRaw(hash: hash);
|
||||
final headerFetching = eclient.getHeader(height: height);
|
||||
final result = await Future.wait([rawFetching, headerFetching]);
|
||||
final raw = result.first as String;
|
||||
final header = result[1] as Map<String, Object>;
|
||||
|
||||
return {'raw': raw, 'header': header};
|
||||
final tx = await eclient.getTransactionExpanded(hash: hash);
|
||||
return BitcoinTransactionInfo.fromElectrumVerbose(tx,
|
||||
height: height, addresses: wallet.addresses);
|
||||
}
|
||||
|
||||
Future<void> add(List<BitcoinTransactionInfo> transactions) async {
|
||||
this.transactions.addAll(transactions);
|
||||
Future<void> add(Map<String, BitcoinTransactionInfo> transactionsList) async {
|
||||
transactionsList.entries.forEach((entry) {
|
||||
_updateOrInsert(entry.value);
|
||||
|
||||
if (entry.value.height > _height) {
|
||||
_height = entry.value.height;
|
||||
}
|
||||
});
|
||||
|
||||
await save();
|
||||
}
|
||||
|
||||
Future<void> addOne(BitcoinTransactionInfo tx) async {
|
||||
transactions.add(tx);
|
||||
_updateOrInsert(tx);
|
||||
|
||||
if (tx.height > _height) {
|
||||
_height = tx.height;
|
||||
}
|
||||
|
||||
await save();
|
||||
}
|
||||
|
||||
Future<void> save() async => writeData(
|
||||
path: path,
|
||||
password: _password,
|
||||
data: json.encode({'height': _height, 'transactions': transactions}));
|
||||
BitcoinTransactionInfo get(String id) => transactions[id];
|
||||
|
||||
Future<void> save() async {
|
||||
final data = json.encode({'height': _height, 'transactions': transactions});
|
||||
|
||||
print('data');
|
||||
print(data);
|
||||
|
||||
await writeData(path: path, password: _password, data: data);
|
||||
}
|
||||
|
||||
@override
|
||||
void updateAsync({void Function() onFinished}) {
|
||||
fetchTransactionsAsync((transaction) => _updateOrInsert(transaction),
|
||||
onFinished: onFinished);
|
||||
}
|
||||
|
||||
@override
|
||||
void fetchTransactionsAsync(
|
||||
void Function(BitcoinTransactionInfo transaction) onTransactionLoaded,
|
||||
{void Function() onFinished}) async {
|
||||
final histories = await Future.wait(wallet.scriptHashes
|
||||
.map((scriptHash) async => await eclient.getHistory(scriptHash)));
|
||||
final transactionsCount =
|
||||
histories.fold<int>(0, (acc, m) => acc + m.length);
|
||||
var counter = 0;
|
||||
|
||||
final batches = histories.map((metaList) =>
|
||||
_fetchBatchOfTransactions(metaList, onTransactionLoaded: (transaction) {
|
||||
onTransactionLoaded(transaction);
|
||||
counter += 1;
|
||||
|
||||
if (counter == transactionsCount) {
|
||||
onFinished?.call();
|
||||
}
|
||||
}));
|
||||
|
||||
await Future.wait(batches);
|
||||
}
|
||||
|
||||
Future<void> _fetchBatchOfTransactions(
|
||||
Iterable<Map<String, dynamic>> metaList,
|
||||
{void Function(BitcoinTransactionInfo tranasaction)
|
||||
onTransactionLoaded}) async =>
|
||||
metaList.forEach((txMeta) => fetchTransactionInfo(
|
||||
hash: txMeta['tx_hash'] as String,
|
||||
height: txMeta['height'] as int)
|
||||
.then((transaction) => onTransactionLoaded(transaction)));
|
||||
|
||||
Future<Map<String, Object>> _read() async {
|
||||
final content = await read(path: path, password: _password);
|
||||
return json.decode(content) as Map<String, Object>;
|
||||
}
|
||||
|
||||
Future<void> _load() async {
|
||||
try {
|
||||
final content = await read(path: path, password: _password);
|
||||
final jsoned = json.decode(content) as Map<String, Object>;
|
||||
final height = jsoned['height'] as int;
|
||||
final transactions = (jsoned['transactions'] as List<dynamic>)
|
||||
.map((dynamic row) {
|
||||
if (row is Map<String, Object>) {
|
||||
return BitcoinTransactionInfo.fromJson(row);
|
||||
}
|
||||
final content = await _read();
|
||||
final txs = content['transactions'] as Map<String, Object> ?? {};
|
||||
|
||||
return null;
|
||||
})
|
||||
.where((el) => el != null)
|
||||
.toList();
|
||||
txs.entries.forEach((entry) {
|
||||
final val = entry.value;
|
||||
|
||||
return {'transactions': transactions, 'height': height};
|
||||
} catch (_) {
|
||||
return {'transactions': <BitcoinTransactionInfo>[], 'height': 0};
|
||||
if (val is Map<String, Object>) {
|
||||
final tx = BitcoinTransactionInfo.fromJson(val);
|
||||
_updateOrInsert(tx);
|
||||
}
|
||||
});
|
||||
|
||||
_height = content['height'] as int;
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
void _updateOrInsert(BitcoinTransactionInfo transaction) {
|
||||
if (transactions[transaction.id] == null) {
|
||||
transactions[transaction.id] = transaction;
|
||||
} else {
|
||||
final originalTx = transactions[transaction.id];
|
||||
originalTx.confirmations = transaction.confirmations;
|
||||
originalTx.amount = transaction.amount;
|
||||
originalTx.height = transaction.height;
|
||||
originalTx.date ??= transaction.date;
|
||||
originalTx.isPending = transaction.isPending;
|
||||
}
|
||||
}
|
||||
|
||||
void _updateHeight() {
|
||||
final newHeight = transactions.fold(
|
||||
0, (int acc, val) => val.height > acc ? val.height : acc);
|
||||
_height = newHeight > _height ? newHeight : _height;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import 'package:cake_wallet/bitcoin/bitcoin_amount_format.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:bitcoin_flutter/bitcoin_flutter.dart' as bitcoin;
|
||||
import 'package:cake_wallet/bitcoin/bitcoin_address_record.dart';
|
||||
import 'package:bitcoin_flutter/src/payments/index.dart' show PaymentData;
|
||||
import 'package:cake_wallet/bitcoin/bitcoin_amount_format.dart';
|
||||
import 'package:cake_wallet/src/domain/bitcoin/bitcoin_amount_format.dart';
|
||||
import 'package:cake_wallet/src/domain/common/transaction_direction.dart';
|
||||
import 'package:cake_wallet/src/domain/common/transaction_info.dart';
|
||||
import 'package:cake_wallet/src/domain/common/format_amount.dart';
|
||||
@@ -13,7 +15,8 @@ class BitcoinTransactionInfo extends TransactionInfo {
|
||||
@required int amount,
|
||||
@required TransactionDirection direction,
|
||||
@required bool isPending,
|
||||
@required DateTime date}) {
|
||||
@required DateTime date,
|
||||
@required this.confirmations}) {
|
||||
this.height = height;
|
||||
this.amount = amount;
|
||||
this.direction = direction;
|
||||
@@ -21,34 +24,87 @@ class BitcoinTransactionInfo extends TransactionInfo {
|
||||
this.isPending = isPending;
|
||||
}
|
||||
|
||||
factory BitcoinTransactionInfo.fromHexAndHeader(
|
||||
String hex, Map<String, Object> header,
|
||||
{List<String> addresses}) {
|
||||
factory BitcoinTransactionInfo.fromElectrumVerbose(Map<String, Object> obj,
|
||||
{@required List<BitcoinAddressRecord> addresses, @required int height}) {
|
||||
final addressesSet = addresses.map((addr) => addr.address).toSet();
|
||||
final id = obj['txid'] as String;
|
||||
final vins = obj['vin'] as List<Object> ?? [];
|
||||
final vout = (obj['vout'] as List<Object> ?? []);
|
||||
final date = obj['time'] is int
|
||||
? DateTime.fromMillisecondsSinceEpoch((obj['time'] as int) * 1000)
|
||||
: DateTime.now();
|
||||
final confirmations = obj['confirmations'] as int ?? 0;
|
||||
var direction = TransactionDirection.incoming;
|
||||
|
||||
for (dynamic vin in vins) {
|
||||
final vout = vin['vout'] as int;
|
||||
final out = vin['tx']['vout'][vout] as Map;
|
||||
final outAddresses =
|
||||
(out['scriptPubKey']['addresses'] as List<Object>)?.toSet();
|
||||
|
||||
if (outAddresses?.intersection(addressesSet)?.isNotEmpty ?? false) {
|
||||
direction = TransactionDirection.outgoing;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
final amount = vout.fold(0, (int acc, dynamic out) {
|
||||
final outAddresses =
|
||||
out['scriptPubKey']['addresses'] as List<Object> ?? [];
|
||||
final ntrs = outAddresses.toSet().intersection(addressesSet);
|
||||
var amount = acc;
|
||||
|
||||
if ((direction == TransactionDirection.incoming && ntrs.isNotEmpty) ||
|
||||
(direction == TransactionDirection.outgoing && ntrs.isEmpty)) {
|
||||
amount += doubleToBitcoinAmount(out['value'] as double ?? 0.0);
|
||||
}
|
||||
|
||||
return amount;
|
||||
});
|
||||
|
||||
return BitcoinTransactionInfo(
|
||||
id: id,
|
||||
height: height,
|
||||
isPending: false,
|
||||
direction: direction,
|
||||
amount: amount,
|
||||
date: date,
|
||||
confirmations: confirmations);
|
||||
}
|
||||
|
||||
factory BitcoinTransactionInfo.fromHexAndHeader(String hex,
|
||||
{List<String> addresses, int height, int timestamp, int confirmations}) {
|
||||
final tx = bitcoin.Transaction.fromHex(hex);
|
||||
var exist = false;
|
||||
var amount = 0;
|
||||
|
||||
tx.outs.forEach((out) {
|
||||
try {
|
||||
final p2pkh = bitcoin.P2PKH(
|
||||
data: PaymentData(output: out.script), network: bitcoin.bitcoin);
|
||||
exist = addresses.contains(p2pkh.data.address);
|
||||
if (addresses != null) {
|
||||
tx.outs.forEach((out) {
|
||||
try {
|
||||
final p2pkh = bitcoin.P2PKH(
|
||||
data: PaymentData(output: out.script), network: bitcoin.bitcoin);
|
||||
exist = addresses.contains(p2pkh.data.address);
|
||||
|
||||
if (exist) {
|
||||
amount += out.value;
|
||||
}
|
||||
} catch (_) {}
|
||||
});
|
||||
if (exist) {
|
||||
amount += out.value;
|
||||
}
|
||||
} catch (_) {}
|
||||
});
|
||||
}
|
||||
|
||||
final date = timestamp != null
|
||||
? DateTime.fromMillisecondsSinceEpoch(timestamp * 1000)
|
||||
: DateTime.now();
|
||||
|
||||
// FIXME: Get transaction is pending
|
||||
return BitcoinTransactionInfo(
|
||||
id: tx.getId(),
|
||||
height: header['block_height'] as int,
|
||||
height: height,
|
||||
isPending: false,
|
||||
direction: TransactionDirection.incoming,
|
||||
amount: amount,
|
||||
date: DateTime.fromMillisecondsSinceEpoch(
|
||||
(header['timestamp'] as int) * 1000));
|
||||
date: date,
|
||||
confirmations: confirmations);
|
||||
}
|
||||
|
||||
factory BitcoinTransactionInfo.fromJson(Map<String, dynamic> data) {
|
||||
@@ -58,15 +114,18 @@ class BitcoinTransactionInfo extends TransactionInfo {
|
||||
amount: data['amount'] as int,
|
||||
direction: parseTransactionDirectionFromInt(data['direction'] as int),
|
||||
date: DateTime.fromMillisecondsSinceEpoch(data['date'] as int),
|
||||
isPending: data['isPending'] as bool);
|
||||
isPending: data['isPending'] as bool,
|
||||
confirmations: data['confirmations'] as int);
|
||||
}
|
||||
|
||||
final String id;
|
||||
int confirmations;
|
||||
|
||||
String _fiatAmount;
|
||||
|
||||
@override
|
||||
String amountFormatted() => '${formatAmount(bitcoinAmountToString(amount: amount))} BTC';
|
||||
String amountFormatted() =>
|
||||
'${formatAmount(bitcoinAmountToString(amount: amount))} BTC';
|
||||
|
||||
@override
|
||||
String fiatAmount() => _fiatAmount ?? '';
|
||||
@@ -75,13 +134,14 @@ class BitcoinTransactionInfo extends TransactionInfo {
|
||||
void changeFiatAmount(String amount) => _fiatAmount = formatAmount(amount);
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
final m = Map<String, dynamic>();
|
||||
final m = <String, dynamic>{};
|
||||
m['id'] = id;
|
||||
m['height'] = height;
|
||||
m['amount'] = amount;
|
||||
m['direction'] = direction.index;
|
||||
m['date'] = date.millisecondsSinceEpoch;
|
||||
m['isPending'] = isPending;
|
||||
m['confirmations'] = confirmations;
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
class BitcoinTransactionNoInputsException implements Exception {
|
||||
@override
|
||||
String toString() => 'No inputs for the transaction.';
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
class BitcoinTransactionWrongBalanceException implements Exception {
|
||||
@override
|
||||
String toString() => 'Wrong balance. Not enough BTC on your balance.';
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import 'package:cake_wallet/bitcoin/bitcoin_address_record.dart';
|
||||
|
||||
class BitcoinUnspent {
|
||||
BitcoinUnspent(this.address, this.hash, this.value, this.vout);
|
||||
|
||||
factory BitcoinUnspent.fromJSON(
|
||||
BitcoinAddressRecord address, Map<String, dynamic> json) =>
|
||||
BitcoinUnspent(address, json['tx_hash'] as String, json['value'] as int,
|
||||
json['tx_pos'] as int);
|
||||
|
||||
final BitcoinAddressRecord address;
|
||||
final String hash;
|
||||
final int value;
|
||||
final int vout;
|
||||
|
||||
bool get isP2wpkh => address.address.startsWith('bc1');
|
||||
}
|
||||
+174
-61
@@ -1,10 +1,20 @@
|
||||
import 'dart:typed_data';
|
||||
import 'dart:convert';
|
||||
import 'package:cake_wallet/bitcoin/bitcoin_transaction_credentials.dart';
|
||||
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';
|
||||
import 'package:cake_wallet/bitcoin/bitcoin_wallet_keys.dart';
|
||||
import 'package:cake_wallet/bitcoin/pending_bitcoin_transaction.dart';
|
||||
import 'package:cake_wallet/bitcoin/script_hash.dart';
|
||||
import 'package:cake_wallet/bitcoin/utils.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: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';
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:mobx/mobx.dart';
|
||||
import 'package:bip39/bip39.dart' as bip39;
|
||||
@@ -20,12 +30,39 @@ import 'package:cake_wallet/bitcoin/bitcoin_balance.dart';
|
||||
import 'package:cake_wallet/src/domain/common/node.dart';
|
||||
import 'package:cake_wallet/core/wallet_base.dart';
|
||||
import 'package:rxdart/rxdart.dart';
|
||||
import 'package:hex/hex.dart';
|
||||
|
||||
part 'bitcoin_wallet.g.dart';
|
||||
|
||||
class BitcoinWallet = BitcoinWalletBase with _$BitcoinWallet;
|
||||
|
||||
abstract class BitcoinWalletBase extends WalletBase<BitcoinBalance> with Store {
|
||||
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 = {};
|
||||
}
|
||||
|
||||
static BitcoinWallet fromJSON(
|
||||
{@required String password,
|
||||
@required String name,
|
||||
@@ -37,12 +74,12 @@ abstract class BitcoinWalletBase extends WalletBase<BitcoinBalance> with Store {
|
||||
(data['account_index'] == 'null' || data['account_index'] == null)
|
||||
? 0
|
||||
: int.parse(data['account_index'] as String);
|
||||
final _addresses = data['addresses'] as List;
|
||||
final _addresses = data['addresses'] as List ?? <Object>[];
|
||||
final addresses = <BitcoinAddressRecord>[];
|
||||
final balance = BitcoinBalance.fromJSON(data['balance'] as String) ??
|
||||
BitcoinBalance(confirmed: 0, unconfirmed: 0);
|
||||
|
||||
_addresses?.forEach((Object el) {
|
||||
_addresses.forEach((Object el) {
|
||||
if (el is String) {
|
||||
addresses.add(BitcoinAddressRecord.fromJSON(el));
|
||||
}
|
||||
@@ -83,34 +120,10 @@ abstract class BitcoinWalletBase extends WalletBase<BitcoinBalance> with Store {
|
||||
transactionHistory: history);
|
||||
}
|
||||
|
||||
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}) {
|
||||
type = WalletType.bitcoin;
|
||||
currency = CryptoCurrency.btc;
|
||||
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;
|
||||
}
|
||||
|
||||
@override
|
||||
final BitcoinTransactionHistory transactionHistory;
|
||||
final String path;
|
||||
bitcoin.HDWallet hd;
|
||||
final bitcoin.HDWallet hd;
|
||||
final ElectrumClient eclient;
|
||||
final String mnemonic;
|
||||
|
||||
@@ -131,6 +144,11 @@ abstract class BitcoinWalletBase extends WalletBase<BitcoinBalance> with Store {
|
||||
|
||||
ObservableList<BitcoinAddressRecord> addresses;
|
||||
|
||||
Map<String, bitcoin.ECPair> _addressesKeys;
|
||||
|
||||
List<String> get scriptHashes =>
|
||||
addresses.map((addr) => scriptHash(addr.address)).toList();
|
||||
|
||||
String get xpub => hd.base58;
|
||||
|
||||
@override
|
||||
@@ -142,11 +160,13 @@ abstract class BitcoinWalletBase extends WalletBase<BitcoinBalance> with Store {
|
||||
|
||||
int _accountIndex;
|
||||
String _password;
|
||||
BehaviorSubject<Object> _addressUpdateSubject;
|
||||
Map<String, BehaviorSubject<Object>> _scripthashesUpdateSubject;
|
||||
|
||||
Future<void> init() async {
|
||||
if (addresses.isEmpty) {
|
||||
addresses.add(BitcoinAddressRecord(_getAddress(hd: hd, index: 0)));
|
||||
final index = 0;
|
||||
addresses
|
||||
.add(BitcoinAddressRecord(_getAddress(index: index), index: index));
|
||||
}
|
||||
|
||||
address = addresses.first.address;
|
||||
@@ -156,9 +176,8 @@ abstract class BitcoinWalletBase extends WalletBase<BitcoinBalance> with Store {
|
||||
|
||||
Future<BitcoinAddressRecord> generateNewAddress({String label}) async {
|
||||
_accountIndex += 1;
|
||||
final address = BitcoinAddressRecord(
|
||||
_getAddress(hd: hd, index: _accountIndex),
|
||||
label: label);
|
||||
final address = BitcoinAddressRecord(_getAddress(index: _accountIndex),
|
||||
index: _accountIndex, label: label);
|
||||
addresses.add(address);
|
||||
|
||||
await save();
|
||||
@@ -181,9 +200,8 @@ abstract class BitcoinWalletBase extends WalletBase<BitcoinBalance> with Store {
|
||||
Future<void> startSync() async {
|
||||
try {
|
||||
syncStatus = StartingSyncStatus();
|
||||
await _addressUpdateSubject?.close();
|
||||
_addressUpdateSubject = eclient.addressUpdate(address: address);
|
||||
await transactionHistory.update();
|
||||
transactionHistory.updateAsync(onFinished: () => print('finished!'));
|
||||
_subscribeForUpdates();
|
||||
await _updateBalance();
|
||||
syncStatus = SyncedSyncStatus();
|
||||
} catch (e) {
|
||||
@@ -197,39 +215,102 @@ abstract class BitcoinWalletBase extends WalletBase<BitcoinBalance> with Store {
|
||||
Future<void> connectToNode({@required Node node}) async {
|
||||
try {
|
||||
syncStatus = ConnectingSyncStatus();
|
||||
await eclient.connect(host: 'electrum2.hodlister.co', port: 50002);
|
||||
// electrum2.hodlister.co
|
||||
// bitcoin.electrumx.multicoin.co:50002
|
||||
// electrum2.taborsky.cz:5002
|
||||
await eclient.connect(
|
||||
host: 'bitcoin.electrumx.multicoin.co', port: 50002);
|
||||
syncStatus = ConnectedSyncStatus();
|
||||
} catch (e) {
|
||||
print(e.toString);
|
||||
print(e.toString());
|
||||
syncStatus = FailedSyncStatus();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> createTransaction(Object credentials) async {
|
||||
Future<PendingBitcoinTransaction> createTransaction(
|
||||
Object credentials) async {
|
||||
final transactionCredentials = credentials as BitcoinTransactionCredentials;
|
||||
|
||||
final inputs = <BitcoinUnspent>[];
|
||||
final fee = _feeMultiplier(transactionCredentials.priority);
|
||||
final amount = transactionCredentials.amount != null
|
||||
? doubleToBitcoinAmount(transactionCredentials.amount)
|
||||
: balance.total - fee;
|
||||
final totalAmount = amount + fee;
|
||||
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;
|
||||
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;
|
||||
|
||||
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);
|
||||
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));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> save() async =>
|
||||
await write(path: path, password: _password, data: toJSON());
|
||||
|
||||
String toJSON() => json.encode({
|
||||
'mnemonic': mnemonic,
|
||||
'account_index': _accountIndex.toString(),
|
||||
@@ -237,16 +318,32 @@ abstract class BitcoinWalletBase extends WalletBase<BitcoinBalance> with Store {
|
||||
'balance': balance?.toJSON()
|
||||
});
|
||||
|
||||
String _getAddress({bitcoin.HDWallet hd, int index}) => bitcoin
|
||||
.P2WPKH(
|
||||
data: PaymentData(
|
||||
pubkey: Uint8List.fromList(hd.derive(index).pubKey.codeUnits)))
|
||||
.data
|
||||
.address;
|
||||
@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 {
|
||||
print('event $event');
|
||||
transactionHistory.updateAsync();
|
||||
await _updateBalance();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
Future<BitcoinBalance> _fetchBalances() async {
|
||||
final balances = await Future.wait(
|
||||
addresses.map((record) => eclient.getBalance(address: record.address)));
|
||||
scriptHashes.map((sHash) => eclient.getBalance(sHash)));
|
||||
final balance = balances.fold(
|
||||
BitcoinBalance(confirmed: 0, unconfirmed: 0),
|
||||
(BitcoinBalance acc, val) => BitcoinBalance(
|
||||
@@ -261,4 +358,20 @@ abstract class BitcoinWalletBase extends WalletBase<BitcoinBalance> with Store {
|
||||
balance = await _fetchBalances();
|
||||
await save();
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+91
-24
@@ -1,17 +1,18 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:cake_wallet/bitcoin/script_hash.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:rxdart/rxdart.dart';
|
||||
|
||||
String jsonrpcparams(List<Object> params) {
|
||||
final _params = params?.map((val) => '"${val.toString()}"')?.join(',');
|
||||
return "[$_params]";
|
||||
return '[$_params]';
|
||||
}
|
||||
|
||||
String jsonrpc(
|
||||
{String method, List<Object> params, int id, double version = 2.0}) =>
|
||||
'{"jsonrpc": "$version", "method": "$method", "id": "$id", "params": ${jsonrpcparams(params)}}\n';
|
||||
'{"jsonrpc": "$version", "method": "$method", "id": "$id", "params": ${json.encode(params)}}\n';
|
||||
|
||||
class SocketTask {
|
||||
SocketTask({this.completer, this.isSubscription, this.subject});
|
||||
@@ -50,6 +51,7 @@ class ElectrumClient {
|
||||
socket.listen((List<int> event) {
|
||||
try {
|
||||
final jsoned = json.decode(utf8.decode(event)) as Map<String, Object>;
|
||||
// print(jsoned);
|
||||
final method = jsoned['method'];
|
||||
|
||||
if (method is String) {
|
||||
@@ -93,18 +95,18 @@ class ElectrumClient {
|
||||
return [];
|
||||
});
|
||||
|
||||
Future<Map<String, Object>> getBalance({String address}) =>
|
||||
call(method: 'blockchain.address.get_balance', params: [address])
|
||||
Future<Map<String, Object>> getBalance(String scriptHash) =>
|
||||
call(method: 'blockchain.scripthash.get_balance', params: [scriptHash])
|
||||
.then((dynamic result) {
|
||||
if (result is Map<String, Object>) {
|
||||
return result;
|
||||
}
|
||||
|
||||
return Map<String, Object>();
|
||||
return <String, Object>{};
|
||||
});
|
||||
|
||||
Future<List<Map<String, dynamic>>> getHistory({String address}) =>
|
||||
call(method: 'blockchain.address.get_history', params: [address])
|
||||
Future<List<Map<String, dynamic>>> getHistory(String scriptHash) =>
|
||||
call(method: 'blockchain.scripthash.get_history', params: [scriptHash])
|
||||
.then((dynamic result) {
|
||||
if (result is List) {
|
||||
return result.map((dynamic val) {
|
||||
@@ -112,26 +114,94 @@ class ElectrumClient {
|
||||
return val;
|
||||
}
|
||||
|
||||
return Map<String, Object>();
|
||||
return <String, Object>{};
|
||||
}).toList();
|
||||
}
|
||||
|
||||
return [];
|
||||
});
|
||||
|
||||
Future<String> getTransactionRaw({@required String hash}) async =>
|
||||
call(method: 'blockchain.transaction.get', params: [hash])
|
||||
Future<List<Map<String, dynamic>>> getListUnspentWithAddress(
|
||||
String address) =>
|
||||
call(
|
||||
method: 'blockchain.scripthash.listunspent',
|
||||
params: [scriptHash(address)]).then((dynamic result) {
|
||||
if (result is List) {
|
||||
return result.map((dynamic val) {
|
||||
if (val is Map<String, Object>) {
|
||||
val['address'] = address;
|
||||
return val;
|
||||
}
|
||||
|
||||
return <String, Object>{};
|
||||
}).toList();
|
||||
}
|
||||
|
||||
return [];
|
||||
});
|
||||
|
||||
Future<List<Map<String, dynamic>>> getListUnspent(String scriptHash) =>
|
||||
call(method: 'blockchain.scripthash.listunspent', params: [scriptHash])
|
||||
.then((dynamic result) {
|
||||
if (result is String) {
|
||||
if (result is List) {
|
||||
return result.map((dynamic val) {
|
||||
if (val is Map<String, Object>) {
|
||||
return val;
|
||||
}
|
||||
|
||||
return <String, Object>{};
|
||||
}).toList();
|
||||
}
|
||||
|
||||
return [];
|
||||
});
|
||||
|
||||
Future<List<Map<String, dynamic>>> getMempool(String scriptHash) =>
|
||||
call(method: 'blockchain.scripthash.get_mempool', params: [scriptHash])
|
||||
.then((dynamic result) {
|
||||
if (result is List) {
|
||||
return result.map((dynamic val) {
|
||||
if (val is Map<String, Object>) {
|
||||
return val;
|
||||
}
|
||||
|
||||
return <String, Object>{};
|
||||
}).toList();
|
||||
}
|
||||
|
||||
return [];
|
||||
});
|
||||
|
||||
Future<Map<String, Object>> getTransactionRaw(
|
||||
{@required String hash}) async =>
|
||||
call(method: 'blockchain.transaction.get', params: [hash, true])
|
||||
.then((dynamic result) {
|
||||
if (result is Map<String, Object>) {
|
||||
return result;
|
||||
}
|
||||
|
||||
return '';
|
||||
return <String, Object>{};
|
||||
});
|
||||
|
||||
Future<String> broadcastTransaction({@required String transactionRaw}) async =>
|
||||
Future<Map<String, Object>> getTransactionExpanded(
|
||||
{@required String hash}) async {
|
||||
final originalTx = await getTransactionRaw(hash: hash);
|
||||
final vins = originalTx['vin'] as List<Object>;
|
||||
|
||||
for (dynamic vin in vins) {
|
||||
if (vin is Map<String, Object>) {
|
||||
vin['tx'] = await getTransactionRaw(hash: vin['txid'] as String);
|
||||
}
|
||||
}
|
||||
|
||||
return originalTx;
|
||||
}
|
||||
|
||||
Future<String> broadcastTransaction(
|
||||
{@required String transactionRaw}) async =>
|
||||
call(method: 'blockchain.transaction.broadcast', params: [transactionRaw])
|
||||
.then((dynamic result) {
|
||||
print('result $result');
|
||||
if (result is String) {
|
||||
return result;
|
||||
}
|
||||
@@ -163,11 +233,11 @@ class ElectrumClient {
|
||||
return 0;
|
||||
});
|
||||
|
||||
BehaviorSubject<Object> addressUpdate({@required String address}) =>
|
||||
BehaviorSubject<Object> scripthashUpdate(String scripthash) =>
|
||||
subscribe<Object>(
|
||||
id: 'blockchain.address.subscribe:$address',
|
||||
method: 'blockchain.address.subscribe',
|
||||
params: [address]);
|
||||
id: 'blockchain.scripthash.subscribe:$scripthash',
|
||||
method: 'blockchain.scripthash.subscribe',
|
||||
params: [scripthash]);
|
||||
|
||||
BehaviorSubject<T> subscribe<T>(
|
||||
{@required String id,
|
||||
@@ -218,15 +288,12 @@ class ElectrumClient {
|
||||
void _methodHandler(
|
||||
{@required String method, @required Map<String, Object> request}) {
|
||||
switch (method) {
|
||||
case 'blockchain.address.subscribe':
|
||||
case 'blockchain.scripthash.subscribe':
|
||||
final params = request['params'] as List<dynamic>;
|
||||
final address = params.first as String;
|
||||
final id = 'blockchain.address.subscribe:$address';
|
||||
|
||||
if (_tasks[id] != null) {
|
||||
_tasks[id].subject.add(params.last);
|
||||
}
|
||||
final scripthash = params.first as String;
|
||||
final id = 'blockchain.scripthash.subscribe:$scripthash';
|
||||
|
||||
_tasks[id]?.subject?.add(params.last);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import 'package:cake_wallet/bitcoin/bitcoin_amount_format.dart';
|
||||
import 'package:cake_wallet/bitcoin/bitcoin_transaction_info.dart';
|
||||
import 'package:cake_wallet/src/domain/common/transaction_direction.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:bitcoin_flutter/bitcoin_flutter.dart' as bitcoin;
|
||||
import 'package:cake_wallet/core/pending_transaction.dart';
|
||||
import 'package:cake_wallet/bitcoin/electrum.dart';
|
||||
|
||||
class PendingBitcoinTransaction with PendingTransaction {
|
||||
PendingBitcoinTransaction(this._tx,
|
||||
{@required this.eclient, @required this.amount, @required this.fee})
|
||||
: _listeners = <void Function(BitcoinTransactionInfo transaction)>[];
|
||||
|
||||
final bitcoin.Transaction _tx;
|
||||
final ElectrumClient eclient;
|
||||
final int amount;
|
||||
final int fee;
|
||||
|
||||
String get id => _tx.getId();
|
||||
|
||||
@override
|
||||
String get amountFormatted => bitcoinAmountToString(amount: amount);
|
||||
|
||||
@override
|
||||
String get feeFormatted => bitcoinAmountToString(amount: fee);
|
||||
|
||||
final List<void Function(BitcoinTransactionInfo transaction)> _listeners;
|
||||
|
||||
@override
|
||||
Future<void> commit() async {
|
||||
await eclient.broadcastTransaction(transactionRaw: _tx.toHex());
|
||||
_listeners?.forEach((listener) => listener(transactionInfo()));
|
||||
}
|
||||
|
||||
void addListener(
|
||||
void Function(BitcoinTransactionInfo transaction) listener) =>
|
||||
_listeners.add(listener);
|
||||
|
||||
BitcoinTransactionInfo transactionInfo() => BitcoinTransactionInfo(
|
||||
id: id,
|
||||
height: 0,
|
||||
amount: amount,
|
||||
direction: TransactionDirection.outgoing,
|
||||
date: DateTime.now(),
|
||||
isPending: true,
|
||||
confirmations: 0);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import 'package:bitcoin_flutter/bitcoin_flutter.dart' as bitcoin;
|
||||
import 'package:crypto/crypto.dart';
|
||||
|
||||
String scriptHash(String address) {
|
||||
final outputScript = bitcoin.Address.addressToOutputScript(address);
|
||||
final splitted = sha256.convert(outputScript).toString().split('');
|
||||
var res = '';
|
||||
|
||||
for (var i = splitted.length - 1; i >= 0; i--) {
|
||||
final char = splitted[i];
|
||||
i--;
|
||||
final nextChar = splitted[i];
|
||||
res += nextChar;
|
||||
res += char;
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import 'dart:typed_data';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:bitcoin_flutter/bitcoin_flutter.dart' as bitcoin;
|
||||
import 'package:bitcoin_flutter/src/payments/index.dart' show PaymentData;
|
||||
import 'package:hex/hex.dart';
|
||||
|
||||
bitcoin.PaymentData generatePaymentData(
|
||||
{@required bitcoin.HDWallet hd, @required int index}) =>
|
||||
PaymentData(
|
||||
pubkey: Uint8List.fromList(HEX.decode(hd.derive(index).pubKey)));
|
||||
|
||||
bitcoin.ECPair generateKeyPair(
|
||||
{@required bitcoin.HDWallet hd,
|
||||
@required int index,
|
||||
bitcoin.NetworkType network}) =>
|
||||
bitcoin.ECPair.fromWIF(hd.derive(index).wif,
|
||||
network: network ?? bitcoin.bitcoin);
|
||||
|
||||
String generateAddress({@required bitcoin.HDWallet hd, @required int index}) =>
|
||||
bitcoin
|
||||
.P2WPKH(
|
||||
data: PaymentData(
|
||||
pubkey:
|
||||
Uint8List.fromList(HEX.decode(hd.derive(index).pubKey))))
|
||||
.data
|
||||
.address;
|
||||
Reference in New Issue
Block a user