BlueWallet/screen/send/psbtWithHardwareWallet.js

341 lines
11 KiB
JavaScript
Raw Normal View History

import React, { useContext, useEffect, useRef, useState } from 'react';
import { ActivityIndicator, TouchableOpacity, ScrollView, View, TextInput, Linking, Platform, Text, StyleSheet } from 'react-native';
2021-02-28 06:13:37 +01:00
import Clipboard from '@react-native-clipboard/clipboard';
2020-12-25 17:09:53 +01:00
import DocumentPicker from 'react-native-document-picker';
2023-10-24 03:28:44 +02:00
import { useNavigation, useRoute, useIsFocused } from '@react-navigation/native';
2020-12-25 17:09:53 +01:00
import RNFS from 'react-native-fs';
2021-01-20 03:13:01 +01:00
import Biometric from '../../class/biometrics';
2020-12-25 17:09:53 +01:00
import { SecondButton, BlueText, BlueCard, BlueSpacing20, BlueCopyToClipboardButton } from '../../BlueComponents';
2020-12-25 17:09:53 +01:00
import navigationStyle from '../../components/navigationStyle';
2020-07-20 15:38:46 +02:00
import loc from '../../loc';
import { BlueStorageContext } from '../../blue_modules/storage-context';
import Notifications from '../../blue_modules/notifications';
2021-09-11 18:33:27 +02:00
import { DynamicQRCode } from '../../components/DynamicQRCode';
import presentAlert from '../../components/Alert';
2023-10-17 15:35:10 +02:00
import { requestCameraAuthorization } from '../../helpers/scan-qr';
2023-10-24 03:28:44 +02:00
import { useTheme } from '../../components/themes';
import triggerHapticFeedback, { HapticFeedbackTypes } from '../../blue_modules/hapticFeedback';
import SafeArea from '../../components/SafeArea';
const BlueElectrum = require('../../blue_modules/BlueElectrum');
2019-09-27 16:49:56 +02:00
const bitcoin = require('bitcoinjs-lib');
const fs = require('../../blue_modules/fs');
const PsbtWithHardwareWallet = () => {
2021-08-24 07:00:57 +02:00
const { txMetadata, fetchAndSaveWalletTransactions, isElectrumDisabled } = useContext(BlueStorageContext);
const navigation = useNavigation();
const route = useRoute();
2021-09-09 13:00:11 +02:00
const { fromWallet, memo, psbt, deepLinkPSBT, launchedBy } = route.params;
const routeParamsPSBT = useRef(route.params.psbt);
const routeParamsTXHex = route.params.txhex;
const { colors } = useTheme();
const [isLoading, setIsLoading] = useState(false);
const [txHex, setTxHex] = useState(route.params.txhex);
const openScannerButton = useRef();
2021-09-11 19:46:01 +02:00
const dynamicQRCode = useRef();
2021-09-11 19:57:43 +02:00
const isFocused = useIsFocused();
2019-09-27 16:49:56 +02:00
const stylesHook = StyleSheet.create({
root: {
backgroundColor: colors.elevated,
},
rootPadding: {
backgroundColor: colors.elevated,
},
hexWrap: {
backgroundColor: colors.elevated,
},
hexLabel: {
color: colors.foregroundColor,
},
hexInput: {
borderColor: colors.formBorder,
backgroundColor: colors.inputBackgroundColor,
color: colors.foregroundColor,
},
hexText: {
color: colors.foregroundColor,
},
});
2019-09-27 16:49:56 +02:00
const _combinePSBT = receivedPSBT => {
return fromWallet.combinePsbt(psbt, receivedPSBT);
};
const onBarScanned = ret => {
if (ret && !ret.data) ret = { data: ret };
if (ret.data.toUpperCase().startsWith('UR')) {
presentAlert({ message: 'BC-UR not decoded. This should never happen' });
}
2020-02-24 22:45:14 +01:00
if (ret.data.indexOf('+') === -1 && ret.data.indexOf('=') === -1 && ret.data.indexOf('=') === -1) {
// this looks like NOT base64, so maybe its transaction's hex
setTxHex(ret.data);
2020-02-24 22:45:14 +01:00
return;
}
try {
const Tx = _combinePSBT(ret.data);
setTxHex(Tx.toHex());
2021-09-09 13:00:11 +02:00
if (launchedBy) {
// we must navigate back to the screen who requested psbt (instead of broadcasting it ourselves)
// most likely for LN channel opening
navigation.navigate({ name: launchedBy, params: { psbt }, merge: true });
2021-09-09 13:00:11 +02:00
// ^^^ we just use `psbt` variable sinse it was finalized in the above _combinePSBT()
// (passed by reference)
}
} catch (Err) {
presentAlert({ message: Err.message });
}
2019-09-27 16:49:56 +02:00
};
2021-09-11 19:57:43 +02:00
useEffect(() => {
if (isFocused) {
dynamicQRCode.current?.startAutoMove();
} else {
dynamicQRCode.current?.stopAutoMove();
}
}, [isFocused]);
useEffect(() => {
if (!psbt && !route.params.txhex) {
presentAlert({ message: loc.send.no_tx_signing_in_progress });
}
2020-01-03 05:02:41 +01:00
if (deepLinkPSBT) {
const newPsbt = bitcoin.Psbt.fromBase64(deepLinkPSBT);
2020-01-03 05:02:41 +01:00
try {
const Tx = fromWallet.combinePsbt(routeParamsPSBT.current, newPsbt);
setTxHex(Tx.toHex());
2020-01-03 05:02:41 +01:00
} catch (Err) {
presentAlert({ message: Err });
2020-01-03 05:02:41 +01:00
}
} else if (routeParamsTXHex) {
setTxHex(routeParamsTXHex);
2020-01-03 05:02:41 +01:00
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [deepLinkPSBT, routeParamsTXHex]);
2020-01-03 05:02:41 +01:00
const broadcast = async () => {
setIsLoading(true);
2021-01-20 03:13:01 +01:00
const isBiometricsEnabled = await Biometric.isBiometricUseCapableAndEnabled();
if (isBiometricsEnabled) {
if (!(await Biometric.unlockWithBiometrics())) {
setIsLoading(false);
return;
}
}
try {
await BlueElectrum.ping();
await BlueElectrum.waitTillConnected();
const result = await fromWallet.broadcastTx(txHex);
if (result) {
setIsLoading(false);
const txDecoded = bitcoin.Transaction.fromHex(txHex);
const txid = txDecoded.getId();
Notifications.majorTomToGroundControl([], [], [txid]);
if (memo) {
txMetadata[txid] = { memo };
2019-09-27 16:49:56 +02:00
}
navigation.navigate('Success', { amount: undefined });
await new Promise(resolve => setTimeout(resolve, 3000)); // sleep to make sure network propagates
fetchAndSaveWalletTransactions(fromWallet.getID());
} else {
triggerHapticFeedback(HapticFeedbackTypes.NotificationError);
setIsLoading(false);
presentAlert({ message: loc.errors.broadcast });
2019-09-27 16:49:56 +02:00
}
} catch (error) {
triggerHapticFeedback(HapticFeedbackTypes.NotificationError);
setIsLoading(false);
presentAlert({ message: error.message });
}
};
2019-09-27 16:49:56 +02:00
2020-11-20 02:19:04 +01:00
const handleOnVerifyPressed = () => {
Linking.openURL('https://coinb.in/?verify=' + txHex);
};
2019-09-27 16:49:56 +02:00
2020-11-20 14:01:49 +01:00
const copyHexToClipboard = () => {
Clipboard.setString(txHex);
};
const _renderBroadcastHex = () => {
2019-09-27 16:49:56 +02:00
return (
<View style={[styles.rootPadding, stylesHook.rootPadding]}>
<BlueCard style={[styles.hexWrap, stylesHook.hexWrap]}>
<BlueText style={[styles.hexLabel, stylesHook.hexLabel]}>{loc.send.create_this_is_hex}</BlueText>
<TextInput style={[styles.hexInput, stylesHook.hexInput]} height={112} multiline editable value={txHex} />
2019-09-27 16:49:56 +02:00
<TouchableOpacity accessibilityRole="button" style={styles.hexTouch} onPress={copyHexToClipboard}>
<Text style={[styles.hexText, stylesHook.hexText]}>{loc.send.create_copy}</Text>
2019-09-27 16:49:56 +02:00
</TouchableOpacity>
<TouchableOpacity accessibilityRole="button" style={styles.hexTouch} onPress={handleOnVerifyPressed}>
<Text style={[styles.hexText, stylesHook.hexText]}>{loc.send.create_verify}</Text>
2019-09-27 16:49:56 +02:00
</TouchableOpacity>
<BlueSpacing20 />
2021-08-24 06:33:32 +02:00
<SecondButton
disabled={isElectrumDisabled}
onPress={broadcast}
title={loc.send.confirm_sendNow}
testID="PsbtWithHardwareWalletBroadcastTransactionButton"
/>
2019-09-27 16:49:56 +02:00
</BlueCard>
</View>
);
};
2019-09-27 16:49:56 +02:00
const exportPSBT = () => {
const fileName = `${Date.now()}.psbt`;
2021-09-11 19:46:01 +02:00
dynamicQRCode.current?.stopAutoMove();
fs.writeFileAndExport(fileName, typeof psbt === 'string' ? psbt : psbt.toBase64()).finally(() => {
dynamicQRCode.current?.startAutoMove();
});
2020-01-01 04:31:04 +01:00
};
const openSignedTransaction = async () => {
2020-01-01 04:31:04 +01:00
try {
2021-12-27 22:17:02 +01:00
const res = await DocumentPicker.pickSingle({
type: Platform.OS === 'ios' ? ['io.bluewallet.psbt', 'io.bluewallet.psbt.txn'] : [DocumentPicker.types.allFiles],
2020-02-24 22:45:14 +01:00
});
2020-01-03 05:02:41 +01:00
const file = await RNFS.readFile(res.uri);
if (file) {
onBarScanned({ data: file });
2020-01-01 04:31:04 +01:00
} else {
throw new Error();
}
} catch (err) {
if (!DocumentPicker.isCancel(err)) {
presentAlert({ message: loc.send.details_no_signed_tx });
2020-01-01 04:31:04 +01:00
}
}
};
const openScanner = () => {
2023-10-17 15:35:10 +02:00
requestCameraAuthorization().then(() => {
navigation.navigate('ScanQRCodeRoot', {
screen: 'ScanQRCode',
params: {
launchedBy: route.name,
showFileImportButton: false,
onBarScanned,
},
});
});
};
if (txHex) return _renderBroadcastHex();
2019-09-27 16:49:56 +02:00
return isLoading ? (
<View style={[styles.rootPadding, stylesHook.rootPadding]}>
<ActivityIndicator />
</View>
) : (
<SafeArea style={stylesHook.root}>
<ScrollView centerContent contentContainerStyle={styles.scrollViewContent} testID="PsbtWithHardwareScrollView">
<View style={styles.container}>
<BlueCard>
<BlueText testID="TextHelperForPSBT">{loc.send.psbt_this_is_psbt}</BlueText>
<BlueSpacing20 />
2020-11-22 08:07:27 +01:00
<Text testID="PSBTHex" style={styles.hidden}>
{psbt.toHex()}
</Text>
2021-09-11 19:46:01 +02:00
<DynamicQRCode value={psbt.toHex()} ref={dynamicQRCode} />
<BlueSpacing20 />
<SecondButton
testID="PsbtTxScanButton"
icon={{
name: 'qrcode',
type: 'font-awesome',
color: colors.buttonTextColor,
}}
onPress={openScanner}
ref={openScannerButton}
title={loc.send.psbt_tx_scan}
/>
<BlueSpacing20 />
<SecondButton
icon={{
2023-04-30 13:36:40 +02:00
name: 'login',
type: 'entypo',
color: colors.buttonTextColor,
}}
onPress={openSignedTransaction}
title={loc.send.psbt_tx_open}
/>
<BlueSpacing20 />
<SecondButton
icon={{
name: 'share-alternative',
type: 'entypo',
color: colors.buttonTextColor,
}}
onPress={exportPSBT}
title={loc.send.psbt_tx_export}
/>
<BlueSpacing20 />
<View style={styles.copyToClipboard}>
<BlueCopyToClipboardButton
stringToCopy={typeof psbt === 'string' ? psbt : psbt.toBase64()}
displayText={loc.send.psbt_clipboard}
2020-01-01 04:31:04 +01:00
/>
</View>
</BlueCard>
</View>
</ScrollView>
</SafeArea>
);
2019-09-27 16:49:56 +02:00
};
2020-07-15 19:32:59 +02:00
export default PsbtWithHardwareWallet;
2021-02-15 09:03:54 +01:00
PsbtWithHardwareWallet.navigationOptions = navigationStyle({}, opts => ({ ...opts, title: loc.send.header }));
const styles = StyleSheet.create({
scrollViewContent: {
flexGrow: 1,
justifyContent: 'space-between',
},
container: {
flexDirection: 'row',
justifyContent: 'center',
paddingTop: 16,
paddingBottom: 16,
},
rootPadding: {
flex: 1,
paddingTop: 20,
},
hexWrap: {
alignItems: 'center',
flex: 1,
},
hexLabel: {
fontWeight: '500',
},
hexInput: {
borderRadius: 4,
marginTop: 20,
fontWeight: '500',
fontSize: 14,
paddingHorizontal: 16,
paddingBottom: 16,
paddingTop: 16,
},
hexTouch: {
marginVertical: 24,
},
hexText: {
fontSize: 15,
fontWeight: '500',
alignSelf: 'center',
},
copyToClipboard: {
justifyContent: 'center',
alignItems: 'center',
},
2020-11-22 08:07:27 +01:00
hidden: {
width: 0,
height: 0,
},
});