REF: removed single address RBF; refactored breadwallet format a bit

This commit is contained in:
Overtorment 2020-03-11 19:16:51 +00:00
parent 8ab1f299e7
commit b9e038d909
8 changed files with 15 additions and 508 deletions

View File

@ -28,8 +28,6 @@ import SelectWallet from './screen/wallets/selectWallet';
import details from './screen/transactions/details';
import TransactionStatus from './screen/transactions/transactionStatus';
import rbf from './screen/transactions/RBF';
import createrbf from './screen/transactions/RBF-create';
import cpfp from './screen/transactions/CPFP';
import rbfBumpFee from './screen/transactions/RBFBumpFee';
import rbfCancel from './screen/transactions/RBFCancel';
@ -78,12 +76,6 @@ const WalletsStackNavigator = createStackNavigator(
WalletDetails: {
screen: WalletDetails,
},
RBF: {
screen: rbf,
},
CreateRBF: {
screen: createrbf,
},
CPFP: {
screen: cpfp,
},

View File

@ -34,15 +34,10 @@ export class HDLegacyBreadwalletWallet extends AbstractHDElectrumWallet {
_getExternalAddressByIndex(index) {
index = index * 1; // cast to int
if (this.external_addresses_cache[index]) return this.external_addresses_cache[index]; // cache hit
const mnemonic = this.secret;
const seed = bip39.mnemonicToSeed(mnemonic);
const root = bip32.fromSeed(seed);
const path = "m/0'/0/" + index;
const child = root.derivePath(path);
const node = bitcoinjs.bip32.fromBase58(this.getXpub());
const address = bitcoinjs.payments.p2pkh({
pubkey: child.publicKey,
pubkey: node.derive(0).derive(index).publicKey,
}).address;
return (this.external_addresses_cache[index] = address);
@ -51,15 +46,10 @@ export class HDLegacyBreadwalletWallet extends AbstractHDElectrumWallet {
_getInternalAddressByIndex(index) {
index = index * 1; // cast to int
if (this.internal_addresses_cache[index]) return this.internal_addresses_cache[index]; // cache hit
const mnemonic = this.secret;
const seed = bip39.mnemonicToSeed(mnemonic);
const root = bip32.fromSeed(seed);
const path = "m/0'/1/" + index;
const child = root.derivePath(path);
const node = bitcoinjs.bip32.fromBase58(this.getXpub());
const address = bitcoinjs.payments.p2pkh({
pubkey: child.publicKey,
pubkey: node.derive(1).derive(index).publicKey,
}).address;
return (this.internal_addresses_cache[index] = address);

View File

@ -20,4 +20,8 @@ export class HDSegwitBech32Wallet extends AbstractHDElectrumWallet {
allowSendMax() {
return true;
}
allowRBF() {
return true;
}
}

View File

@ -22,10 +22,6 @@ export class SegwitP2SHWallet extends LegacyWallet {
static type = 'segwitP2SH';
static typeReadable = 'SegWit (P2SH)';
allowRBF() {
return true;
}
static witnessToAddress(witness) {
const pubKey = Buffer.from(witness, 'hex');
return pubkeyToP2shSegwitAddress(pubKey);

View File

@ -1,255 +0,0 @@
/** @type {AppStorage} */
/* global alert */
import React, { Component } from 'react';
import { TextInput, View, ActivtyIndicator } from 'react-native';
import { FormValidationMessage } from 'react-native-elements';
import {
BlueLoading,
BlueSpacing20,
BlueButton,
SafeBlueArea,
BlueCard,
BlueText,
BlueSpacing,
BlueNavigationStyle,
} from '../../BlueComponents';
import PropTypes from 'prop-types';
const bitcoinjs = require('bitcoinjs-lib');
let BigNumber = require('bignumber.js');
let BlueApp = require('../../BlueApp');
export default class SendCreate extends Component {
static navigationOptions = () => ({
...BlueNavigationStyle(null, false),
title: 'Create RBF',
});
constructor(props) {
super(props);
console.log('send/create constructor');
if (!props.navigation.state.params.feeDelta) {
props.navigation.state.params.feeDelta = '0';
}
this.state = {
isLoading: true,
feeDelta: props.navigation.state.params.feeDelta,
newDestinationAddress: props.navigation.state.params.newDestinationAddress,
txid: props.navigation.state.params.txid,
sourceTx: props.navigation.state.params.sourceTx,
fromWallet: props.navigation.state.params.sourceWallet,
};
}
async componentDidMount() {
console.log('RBF-create - componentDidMount');
let utxo = [];
let lastSequence = 0;
let totalInputAmountSatoshi = 0;
for (let input of this.state.sourceTx.inputs) {
if (input.sequence > lastSequence) {
lastSequence = input.sequence;
}
totalInputAmountSatoshi += input.output_value;
// let amount = new BigNumber(input.output_value)
// amount = amount.div(10000000).toString(10)
utxo.push({
tx_hash: input.prev_hash,
tx_output_n: input.output_index,
value: input.output_value,
});
}
// check seq=MAX and fail if it is
if (lastSequence === bitcoinjs.Transaction.DEFAULT_SEQUENCE) {
return this.setState({
isLoading: false,
nonReplaceable: true,
});
// lastSequence = 1
}
let txMetadata = BlueApp.tx_metadata[this.state.txid];
if (txMetadata) {
if (txMetadata.last_sequence) {
lastSequence = Math.max(lastSequence, txMetadata.last_sequence);
}
}
lastSequence += 1;
let changeAddress;
let transferAmount;
let totalOutputAmountSatoshi = 0;
for (let o of this.state.sourceTx.outputs) {
totalOutputAmountSatoshi += o.value;
if (o.addresses[0] === this.state.fromWallet.getAddress()) {
// change
changeAddress = o.addresses[0];
} else {
transferAmount = new BigNumber(o.value);
transferAmount = transferAmount.dividedBy(100000000).toString(10);
}
}
let oldFee = new BigNumber(totalInputAmountSatoshi - totalOutputAmountSatoshi);
oldFee = parseFloat(oldFee.dividedBy(100000000).toString(10));
console.log('changeAddress = ', changeAddress);
console.log('utxo', utxo);
console.log('lastSequence', lastSequence);
console.log('totalInputAmountSatoshi', totalInputAmountSatoshi);
console.log('totalOutputAmountSatoshi', totalOutputAmountSatoshi);
console.log('transferAmount', transferAmount);
console.log('oldFee', oldFee);
let newFee = new BigNumber(oldFee);
newFee = newFee.plus(this.state.feeDelta).toString(10);
console.log('new Fee', newFee);
// creating TX
setTimeout(() => {
// more responsive
let tx;
try {
tx = this.state.fromWallet.createTx(utxo, transferAmount, newFee, this.state.newDestinationAddress, false, lastSequence);
BlueApp.tx_metadata[this.state.txid] = txMetadata || {};
BlueApp.tx_metadata[this.state.txid]['last_sequence'] = lastSequence;
// in case new TX get confirmed, we must save metadata under new txid
let bitcoin = bitcoinjs;
let txDecoded = bitcoin.Transaction.fromHex(tx);
let txid = txDecoded.getId();
BlueApp.tx_metadata[txid] = BlueApp.tx_metadata[this.state.txid];
BlueApp.tx_metadata[txid]['txhex'] = tx;
//
BlueApp.saveToDisk();
console.log('BlueApp.txMetadata[this.state.txid]', BlueApp.tx_metadata[this.state.txid]);
} catch (err) {
console.log(err);
return this.setState({
isError: true,
errorMessage: JSON.stringify(err.message),
});
}
let newFeeSatoshi = new BigNumber(newFee);
newFeeSatoshi = parseInt(newFeeSatoshi.multipliedBy(100000000));
let satoshiPerByte = Math.round(newFeeSatoshi / (tx.length / 2));
this.setState({
isLoading: false,
size: Math.round(tx.length / 2),
tx,
satoshiPerByte: satoshiPerByte,
amount: transferAmount,
fee: newFee,
});
}, 10);
}
async broadcast() {
this.setState({ isLoading: true }, async () => {
console.log('broadcasting', this.state.tx);
let result = await this.state.fromWallet.broadcastTx(this.state.tx);
console.log('broadcast result = ', result);
if (typeof result === 'string') {
try {
result = JSON.parse(result);
} catch (_) {
result = { result };
}
}
if (result && result.error) {
alert(JSON.stringify(result.error));
this.setState({ isLoading: false });
} else {
alert(JSON.stringify(result.result || result.txid));
this.props.navigation.navigate('TransactionStatus');
}
});
}
render() {
if (this.state.isError) {
return (
<SafeBlueArea style={{ flex: 1, paddingTop: 20 }}>
<BlueSpacing />
<BlueCard title={'Replace Transaction'} style={{ alignItems: 'center', flex: 1 }}>
<BlueText>Error creating transaction. Invalid address or send amount?</BlueText>
<FormValidationMessage>{this.state.errorMessage}</FormValidationMessage>
</BlueCard>
<BlueButton onPress={() => this.props.navigation.goBack()} title="Go back" />
</SafeBlueArea>
);
}
if (this.state.isLoading) {
return <BlueLoading />;
}
if (this.state.nonReplaceable) {
return (
<SafeBlueArea style={{ flex: 1, paddingTop: 20 }}>
<View style={{ flex: 1, justifyContent: 'center', alignContent: 'center' }}>
<BlueText h4 style={{ textAlign: 'center' }}>
This transaction is not replaceable
</BlueText>
</View>
</SafeBlueArea>
);
}
return (
<SafeBlueArea style={{ flex: 1, paddingTop: 20 }}>
<BlueSpacing />
<BlueCard title={'Replace Transaction'} style={{ alignItems: 'center', flex: 1 }}>
<BlueText>This is your transaction's hex, signed and ready to be broadcasted to the network. Continue?</BlueText>
<TextInput
style={{
borderColor: '#ebebeb',
borderWidth: 1,
marginTop: 20,
color: '#ebebeb',
}}
maxHeight={70}
multiline
editable={false}
value={this.state.tx}
/>
<BlueSpacing20 />
<BlueText style={{ paddingTop: 20 }}>To: {this.state.newDestinationAddress}</BlueText>
<BlueText>Amount: {this.state.amount} BTC</BlueText>
<BlueText>Fee: {this.state.fee} BTC</BlueText>
<BlueText>TX size: {this.state.size} Bytes</BlueText>
<BlueText>satoshiPerByte: {this.state.satoshiPerByte} Sat/B</BlueText>
</BlueCard>
{this.state.isLoading ? (
<ActivtyIndicator />
) : (
<BlueButton icon={{ name: 'bullhorn', type: 'font-awesome' }} onPress={() => this.broadcast()} title="Broadcast" />
)}
</SafeBlueArea>
);
}
}
SendCreate.propTypes = {
navigation: PropTypes.shape({
goBack: PropTypes.func,
navigate: PropTypes.func,
state: PropTypes.shape({
params: PropTypes.shape({
address: PropTypes.string,
feeDelta: PropTypes.string,
fromAddress: PropTypes.string,
newDestinationAddress: PropTypes.string,
txid: PropTypes.string,
sourceTx: PropTypes.object,
sourceWallet: PropTypes.object,
}),
}),
}),
};

View File

@ -1,202 +0,0 @@
import React, { Component } from 'react';
import { ActivityIndicator, View, TextInput } from 'react-native';
import { BlueSpacing20, BlueButton, SafeBlueArea, BlueCard, BlueText, BlueSpacing, BlueNavigationStyle } from '../../BlueComponents';
import PropTypes from 'prop-types';
import { SegwitBech32Wallet } from '../../class';
/** @type {AppStorage} */
let BlueApp = require('../../BlueApp');
export default class RBF extends Component {
static navigationOptions = () => ({
...BlueNavigationStyle(null, false),
title: 'RBF',
});
constructor(props) {
super(props);
let txid;
if (props.navigation.state.params) txid = props.navigation.state.params.txid;
let sourceWallet;
let sourceTx;
for (let w of BlueApp.getWallets()) {
for (let t of w.getTransactions()) {
if (t.hash === txid) {
// found our source wallet
sourceWallet = w;
sourceTx = t;
console.log(t);
}
}
}
let destinationAddress;
for (let o of sourceTx.outputs) {
if (!o.addresses && o.script) {
// probably bech32 output, so we need to decode address
o.addresses = [SegwitBech32Wallet.scriptPubKeyToAddress(o.script)];
}
if (o.addresses && o.addresses[0] === sourceWallet.getAddress()) {
// change
// nop
} else {
// DESTINATION address
destinationAddress = (o.addresses && o.addresses[0]) || '';
console.log('dest = ', destinationAddress);
}
}
if (!destinationAddress || sourceWallet.type === 'legacy') {
// for now I'm too lazy to add RBF support for legacy addresses
this.state = {
isLoading: false,
nonReplaceable: true,
};
return;
}
this.state = {
isLoading: true,
txid,
sourceTx,
sourceWallet,
newDestinationAddress: destinationAddress,
feeDelta: '',
};
}
async componentDidMount() {
let startTime = Date.now();
console.log('transactions/RBF - componentDidMount');
this.setState({
isLoading: false,
});
let endTime = Date.now();
console.log('componentDidMount took', (endTime - startTime) / 1000, 'sec');
}
createTransaction() {
this.props.navigation.navigate('CreateRBF', {
feeDelta: this.state.feeDelta,
newDestinationAddress: this.state.newDestinationAddress,
txid: this.state.txid,
sourceTx: this.state.sourceTx,
sourceWallet: this.state.sourceWallet,
});
}
render() {
if (this.state.isLoading) {
return (
<View style={{ flex: 1, paddingTop: 20 }}>
<ActivityIndicator />
</View>
);
}
if (this.state.nonReplaceable) {
return (
<SafeBlueArea style={{ flex: 1, paddingTop: 20 }}>
<BlueSpacing20 />
<BlueSpacing20 />
<BlueSpacing20 />
<BlueSpacing20 />
<BlueSpacing20 />
<BlueText h4>This transaction is not replaceable</BlueText>
<BlueButton onPress={() => this.props.navigation.goBack()} title="Back" />
</SafeBlueArea>
);
}
if (!this.state.sourceWallet.getAddress) {
return (
<SafeBlueArea style={{ flex: 1, paddingTop: 20 }}>
<BlueText>System error: Source wallet not found (this should never happen)</BlueText>
<BlueButton onPress={() => this.props.navigation.goBack()} title="Back" />
</SafeBlueArea>
);
}
return (
<SafeBlueArea style={{ flex: 1, paddingTop: 20 }}>
<BlueSpacing />
<BlueCard title={'Replace By Fee'} style={{ alignItems: 'center', flex: 1 }}>
<BlueText>RBF allows you to increase fee on already sent but not confirmed transaction, thus speeding up mining</BlueText>
<BlueSpacing20 />
<BlueText>
From wallet '{this.state.sourceWallet.getLabel()}' ({this.state.sourceWallet.getAddress()})
</BlueText>
<BlueSpacing20 />
<View
style={{
flexDirection: 'row',
borderColor: '#d2d2d2',
borderBottomColor: '#d2d2d2',
borderWidth: 1.0,
borderBottomWidth: 0.5,
backgroundColor: '#f5f5f5',
minHeight: 44,
height: 44,
alignItems: 'center',
marginVertical: 8,
borderRadius: 4,
}}
>
<TextInput
onChangeText={text => this.setState({ newDestinationAddress: text })}
placeholder={'receiver address here'}
value={this.state.newDestinationAddress}
style={{ flex: 1, minHeight: 33, marginHorizontal: 8 }}
/>
</View>
<View
style={{
flexDirection: 'row',
borderColor: '#d2d2d2',
borderBottomColor: '#d2d2d2',
borderWidth: 1.0,
borderBottomWidth: 0.5,
backgroundColor: '#f5f5f5',
minHeight: 44,
height: 44,
alignItems: 'center',
marginVertical: 8,
borderRadius: 4,
}}
>
<TextInput
onChangeText={text => this.setState({ feeDelta: text })}
keyboardType={'numeric'}
placeholder={'fee to add (in BTC)'}
value={this.state.feeDelta + ''}
style={{ flex: 1, minHeight: 33, marginHorizontal: 8 }}
/>
</View>
</BlueCard>
<BlueSpacing />
<BlueButton onPress={() => this.createTransaction()} title="Create" />
</SafeBlueArea>
);
}
}
RBF.propTypes = {
navigation: PropTypes.shape({
goBack: PropTypes.func,
navigate: PropTypes.func,
state: PropTypes.shape({
params: PropTypes.shape({
txid: PropTypes.string,
}),
}),
}),
};

View File

@ -13,7 +13,7 @@ import {
BlueNavigationStyle,
} from '../../BlueComponents';
import PropTypes from 'prop-types';
import { HDSegwitBech32Transaction, HDSegwitBech32Wallet } from '../../class';
import { HDSegwitBech32Transaction } from '../../class';
import { BitcoinUnit } from '../../models/bitcoinUnits';
import { Icon } from 'react-native-elements';
import Handoff from 'react-native-handoff';
@ -93,7 +93,7 @@ export default class TransactionsStatus extends Component {
}
async checkPossibilityOfCPFP() {
if (this.state.wallet.type !== HDSegwitBech32Wallet.type) {
if (!this.state.wallet.allowRBF()) {
return this.setState({ isCPFPpossible: buttonStatus.notPossible });
}
@ -106,7 +106,7 @@ export default class TransactionsStatus extends Component {
}
async checkPossibilityOfRBFBumpFee() {
if (this.state.wallet.type !== HDSegwitBech32Wallet.type) {
if (!this.state.wallet.allowRBF()) {
return this.setState({ isRBFBumpFeePossible: buttonStatus.notPossible });
}
@ -119,7 +119,7 @@ export default class TransactionsStatus extends Component {
}
async checkPossibilityOfRBFCancel() {
if (this.state.wallet.type !== HDSegwitBech32Wallet.type) {
if (!this.state.wallet.allowRBF()) {
return this.setState({ isRBFCancelPossible: buttonStatus.notPossible });
}
@ -250,24 +250,6 @@ export default class TransactionsStatus extends Component {
</BlueCard>
<View style={{ alignSelf: 'center', justifyContent: 'center' }}>
{(() => {
if (this.state.tx.confirmations === 0 && this.state.wallet && this.state.wallet.allowRBF()) {
return (
<React.Fragment>
<BlueButton
onPress={() =>
this.props.navigation.navigate('RBF', {
txid: this.state.tx.hash,
})
}
title="Replace-By-Fee (RBF)"
/>
<BlueSpacing20 />
</React.Fragment>
);
}
})()}
{(() => {
if (this.state.isCPFPpossible === buttonStatus.unknown) {
return (

View File

@ -363,17 +363,17 @@ it('HD breadwallet works', async function() {
'xpub68nLLEi3KERQY7jyznC9PQSpSjmekrEmN8324YRCXayMXaavbdEJsK4gEcX2bNf9vGzT4xRks9utZ7ot1CTHLtdyCn9udvv1NWvtY7HXroh',
);
await hdBread.fetchBalance();
assert.strictEqual(hdBread.getBalance(), 0);
assert.strictEqual(hdBread.getBalance(), 123456);
assert.ok(hdBread._lastTxFetch === 0);
await hdBread.fetchTransactions();
assert.ok(hdBread._lastTxFetch > 0);
assert.strictEqual(hdBread.getTransactions().length, 177);
assert.strictEqual(hdBread.getTransactions().length, 178);
for (let tx of hdBread.getTransactions()) {
assert.ok(tx.confirmations);
}
assert.strictEqual(hdBread.next_free_address_index, 10);
assert.strictEqual(hdBread.next_free_address_index, 11);
assert.strictEqual(hdBread.next_free_change_address_index, 118);
// checking that internal pointer and async address getter return the same address