BlueWallet/screen/settings/electrumSettings.js

574 lines
19 KiB
JavaScript
Raw Normal View History

2019-07-18 12:22:01 +02:00
/* global alert */
import React, { Component } from 'react';
2020-12-25 17:09:53 +01:00
import PropTypes from 'prop-types';
2021-04-28 16:57:14 +02:00
import {
Alert,
View,
TextInput,
TouchableOpacity,
StyleSheet,
ScrollView,
Text,
Keyboard,
KeyboardAvoidingView,
Platform,
2021-07-05 05:05:04 +02:00
Switch,
Pressable,
2021-04-28 16:57:14 +02:00
} from 'react-native';
2020-12-25 17:09:53 +01:00
import DefaultPreference from 'react-native-default-preference';
2020-12-16 04:15:57 +01:00
import AsyncStorage from '@react-native-async-storage/async-storage';
2020-12-25 17:09:53 +01:00
2020-07-20 15:38:46 +02:00
import loc from '../../loc';
import DeeplinkSchemaMatch from '../../class/deeplink-schema-match';
2020-12-25 17:09:53 +01:00
import navigationStyle from '../../components/navigationStyle';
import {
BlueButton,
BlueButtonLink,
BlueCard,
BlueLoading,
BlueSpacing20,
BlueText,
SafeBlueArea,
BlueDoneAndDismissKeyboardInputAccessory,
BlueDismissKeyboardInputAccessory,
BlueListItem,
} from '../../BlueComponents';
2020-12-25 17:09:53 +01:00
import { BlueCurrentTheme } from '../../components/themes';
import { isTorCapable } from '../../blue_modules/environment';
2021-04-27 03:33:56 +02:00
import ReactNativeHapticFeedback from 'react-native-haptic-feedback';
2021-08-03 18:28:47 +02:00
import WidgetCommunication from '../../blue_modules/WidgetCommunication';
2021-08-24 07:00:57 +02:00
import { BlueStorageContext } from '../../blue_modules/storage-context';
const BlueElectrum = require('../../blue_modules/BlueElectrum');
2019-07-18 12:22:01 +02:00
export default class ElectrumSettings extends Component {
2021-08-24 07:00:57 +02:00
static contextType = BlueStorageContext;
2019-07-18 12:22:01 +02:00
constructor(props) {
super(props);
const server = props?.route?.params?.server;
2019-07-18 12:22:01 +02:00
this.state = {
isLoading: true,
isOfflineMode: false,
2020-12-25 17:20:15 +01:00
serverHistory: [],
2019-07-18 12:22:01 +02:00
config: {},
server,
2021-07-05 05:05:04 +02:00
sslPort: '',
port: '',
2019-07-18 12:22:01 +02:00
};
}
componentWillUnmount() {
clearInterval(this.state.inverval);
}
2019-07-18 12:22:01 +02:00
async componentDidMount() {
2021-05-18 22:38:18 +02:00
const host = await AsyncStorage.getItem(BlueElectrum.ELECTRUM_HOST);
const port = await AsyncStorage.getItem(BlueElectrum.ELECTRUM_TCP_PORT);
const sslPort = await AsyncStorage.getItem(BlueElectrum.ELECTRUM_SSL_PORT);
const serverHistoryStr = await AsyncStorage.getItem(BlueElectrum.ELECTRUM_SERVER_HISTORY);
const isOfflineMode = await BlueElectrum.isDisabled();
2020-12-25 17:20:15 +01:00
const serverHistory = JSON.parse(serverHistoryStr) || [];
2019-07-18 12:22:01 +02:00
this.setState({
isLoading: false,
host,
port,
sslPort,
2020-12-25 17:20:15 +01:00
serverHistory,
isOfflineMode,
2021-04-28 16:57:14 +02:00
isAndroidNumericKeyboardFocused: false,
isAndroidAddressKeyboardVisible: false,
2019-07-18 12:22:01 +02:00
});
const inverval = setInterval(async () => {
this.setState({
config: await BlueElectrum.getConfig(),
});
2020-06-11 19:34:28 +02:00
}, 500);
2020-04-01 17:41:50 +02:00
this.setState({
2019-07-18 12:22:01 +02:00
config: await BlueElectrum.getConfig(),
inverval,
2019-07-18 12:22:01 +02:00
});
if (this.state.server) {
2021-04-27 03:33:56 +02:00
ReactNativeHapticFeedback.trigger('impactHeavy', { ignoreAndroidSystemSettings: false });
Alert.alert(
loc.formatString(loc.settings.set_electrum_server_as_default, { server: this.state.server }),
'',
[
{
text: loc._.ok,
onPress: () => {
this.onBarScanned(this.state.server);
},
style: 'default',
},
{ text: loc._.cancel, onPress: () => {}, style: 'cancel' },
],
{ cancelable: false },
);
}
2019-07-18 12:22:01 +02:00
}
checkServer = async () => {
this.setState({ isLoading: true }, async () => {
const features = await BlueElectrum.serverFeatures();
2021-04-27 03:33:56 +02:00
ReactNativeHapticFeedback.trigger('notificationWarning', { ignoreAndroidSystemSettings: false });
alert(JSON.stringify(features, null, 2));
this.setState({ isLoading: false });
});
};
2020-12-25 17:20:15 +01:00
selectServer = async server => {
this.setState({ host: server.host, port: server.port, sslPort: server.sslPort }, () => {
this.save();
});
};
clearHistoryAlert() {
2021-04-27 03:33:56 +02:00
ReactNativeHapticFeedback.trigger('impactHeavy', { ignoreAndroidSystemSettings: false });
2020-12-25 17:20:15 +01:00
Alert.alert(loc.settings.electrum_clear_alert_title, loc.settings.electrum_clear_alert_message, [
{ text: loc.settings.electrum_clear_alert_cancel, onPress: () => console.log('Cancel Pressed'), style: 'cancel' },
{ text: loc.settings.electrum_clear_alert_ok, onPress: () => this.clearHistory() },
]);
}
clearHistory = async () => {
this.setState({ isLoading: true }, async () => {
2021-05-18 22:38:18 +02:00
await AsyncStorage.setItem(BlueElectrum.ELECTRUM_SERVER_HISTORY, JSON.stringify([]));
2020-12-25 17:20:15 +01:00
this.setState({
serverHistory: [],
isLoading: false,
});
});
};
resetToDefault = async () => {
this.setState({ port: '', host: '', sslPort: '' }, () => {
this.save();
});
};
serverExists = server => {
const { serverHistory } = this.state;
return serverHistory.some(s => {
return `${s.host}${s.port}${s.sslPort}` === `${server.host}${server.port}${server.sslPort}`;
});
};
2019-07-18 12:22:01 +02:00
save = () => {
const host = this.state.host ? this.state.host : '';
const port = this.state.port ? this.state.port : '';
const sslPort = this.state.sslPort ? this.state.sslPort : '';
2020-12-25 17:20:15 +01:00
const serverHistory = this.state.serverHistory || [];
2021-08-25 23:06:07 +02:00
if (host.endsWith('.onion') && !isTorCapable) {
return alert(loc.settings.tor_unsupported);
}
2019-07-18 12:22:01 +02:00
this.setState({ isLoading: true }, async () => {
try {
if (!host && !port && !sslPort) {
2021-05-18 22:38:18 +02:00
await AsyncStorage.setItem(BlueElectrum.ELECTRUM_HOST, '');
await AsyncStorage.setItem(BlueElectrum.ELECTRUM_TCP_PORT, '');
await AsyncStorage.setItem(BlueElectrum.ELECTRUM_SSL_PORT, '');
2020-11-02 14:11:28 +01:00
try {
await DefaultPreference.setName('group.io.bluewallet.bluewallet');
2021-05-18 22:38:18 +02:00
await DefaultPreference.clear(BlueElectrum.ELECTRUM_HOST);
await DefaultPreference.clear(BlueElectrum.ELECTRUM_SSL_PORT);
await DefaultPreference.clear(BlueElectrum.ELECTRUM_TCP_PORT);
2021-08-03 18:28:47 +02:00
WidgetCommunication.reloadAllTimelines();
2020-11-02 14:11:28 +01:00
} catch (e) {
// Must be running on Android
console.log(e);
}
2021-04-27 03:33:56 +02:00
ReactNativeHapticFeedback.trigger('notificationSuccess', { ignoreAndroidSystemSettings: false });
2020-07-20 15:38:46 +02:00
alert(loc.settings.electrum_saved);
} else if (!(await BlueElectrum.testConnection(host, port, sslPort))) {
2021-04-27 03:33:56 +02:00
ReactNativeHapticFeedback.trigger('notificationError', { ignoreAndroidSystemSettings: false });
2020-07-20 15:38:46 +02:00
alert(loc.settings.electrum_error_connect);
2019-07-18 12:22:01 +02:00
} else {
2021-05-18 22:38:18 +02:00
await AsyncStorage.setItem(BlueElectrum.ELECTRUM_HOST, host);
await AsyncStorage.setItem(BlueElectrum.ELECTRUM_TCP_PORT, port);
await AsyncStorage.setItem(BlueElectrum.ELECTRUM_SSL_PORT, sslPort);
2020-12-25 17:20:15 +01:00
if (!this.serverExists({ host, port, sslPort })) {
serverHistory.push({
host,
port,
sslPort,
});
2021-05-18 22:38:18 +02:00
await AsyncStorage.setItem(BlueElectrum.ELECTRUM_SERVER_HISTORY, JSON.stringify(serverHistory));
2020-12-25 17:20:15 +01:00
}
2020-11-02 14:11:28 +01:00
try {
await DefaultPreference.setName('group.io.bluewallet.bluewallet');
2021-05-18 22:38:18 +02:00
await DefaultPreference.set(BlueElectrum.ELECTRUM_HOST, host);
await DefaultPreference.set(BlueElectrum.ELECTRUM_TCP_PORT, port);
await DefaultPreference.set(BlueElectrum.ELECTRUM_SSL_PORT, sslPort);
2021-08-03 18:28:47 +02:00
WidgetCommunication.reloadAllTimelines();
2020-11-02 14:11:28 +01:00
} catch (e) {
// Must be running on Android
console.log(e);
}
2021-04-27 03:33:56 +02:00
ReactNativeHapticFeedback.trigger('notificationSuccess', { ignoreAndroidSystemSettings: false });
2020-07-20 15:38:46 +02:00
alert(loc.settings.electrum_saved);
2019-07-18 12:22:01 +02:00
}
2020-06-11 19:34:28 +02:00
} catch (error) {
2021-04-27 03:33:56 +02:00
ReactNativeHapticFeedback.trigger('notificationError', { ignoreAndroidSystemSettings: false });
2020-06-11 19:34:28 +02:00
alert(error);
}
2019-07-18 12:22:01 +02:00
this.setState({ isLoading: false });
});
};
2020-10-26 16:31:23 +01:00
onBarScanned = value => {
if (DeeplinkSchemaMatch.getServerFromSetElectrumServerAction(value)) {
// in case user scans a QR with a deeplink like `bluewallet:setelectrumserver?server=electrum1.bluewallet.io%3A443%3As`
value = DeeplinkSchemaMatch.getServerFromSetElectrumServerAction(value);
}
const [host, port, type] = value.split(':');
this.setState({ host: host, sslPort: '', port: '' }, () => {
type === 's' ? this.setState({ sslPort: port }) : this.setState({ port: port });
});
};
importScan = () => {
this.props.navigation.navigate('ScanQRCodeRoot', {
screen: 'ScanQRCode',
params: {
launchedBy: this.props.route.name,
onBarScanned: this.onBarScanned,
showFileImportButton: true,
},
});
};
2021-07-05 05:05:04 +02:00
useSSLPortToggled = value => {
switch (value) {
case true:
this.setState(prevState => {
return { port: '', sslPort: prevState.port };
});
break;
case false:
this.setState(prevState => {
return { port: prevState.sslPort, sslPort: '' };
});
break;
}
};
onElectrumConnectionEnabledSwitchValueChangd = async value => {
if (value === true) {
await BlueElectrum.setDisabled(true);
2021-08-24 07:00:57 +02:00
this.context.setIsElectrumDisabled(true);
BlueElectrum.forceDisconnect();
} else {
await BlueElectrum.setDisabled(false);
2021-08-24 07:00:57 +02:00
this.context.setIsElectrumDisabled(false);
BlueElectrum.connectMain();
}
this.setState({ isOfflineMode: value });
};
renderElectrumSettings = () => {
2020-12-25 17:20:15 +01:00
const serverHistoryItems = this.state.serverHistory.map((server, i) => {
return (
<View key={i} style={styles.serverHistoryItem}>
2021-04-28 16:57:14 +02:00
<Text style={styles.serverRow} numberOfLines={1} ellipsizeMode="middle">{`${server.host}:${server.port || server.sslPort}`}</Text>
<TouchableOpacity accessibilityRole="button" style={styles.selectButton} onPress={() => this.selectServer(server)}>
2020-12-25 17:20:15 +01:00
<BlueText>{loc.settings.electrum_select}</BlueText>
</TouchableOpacity>
</View>
);
});
2019-07-18 12:22:01 +02:00
return (
<>
<BlueCard>
<BlueText style={styles.status}>{loc.settings.electrum_status}</BlueText>
<View style={styles.connectWrap}>
<View style={[styles.container, this.state.config.connected === 1 ? styles.containerConnected : styles.containerDisconnected]}>
<BlueText style={this.state.config.connected === 1 ? styles.textConnected : styles.textDisconnected}>
{this.state.config.connected === 1 ? loc.settings.electrum_connected : loc.settings.electrum_connected_not}
</BlueText>
</View>
</View>
<BlueSpacing20 />
<BlueText style={styles.hostname} onPress={this.checkServer}>
{this.state.config.host}:{this.state.config.port}
</BlueText>
</BlueCard>
<KeyboardAvoidingView>
2020-03-29 13:16:49 +02:00
<BlueCard>
<View style={styles.inputWrap}>
<TextInput
placeholder={
loc.formatString(loc.settings.electrum_host, { example: '111.222.333.111' }) +
(isTorCapable ? ' (' + loc.settings.tor_supported + ')' : '')
}
value={this.state.host}
2021-08-27 03:45:50 +02:00
onChangeText={text => {
const host = text.trim();
this.setState({ host }, () => {
if (host.endsWith('.onion')) {
this.useSSLPortToggled(false);
}
2021-08-27 03:45:50 +02:00
});
}}
numberOfLines={1}
style={styles.inputText}
editable={!this.state.isLoading}
placeholderTextColor="#81868e"
autoCorrect={false}
autoCapitalize="none"
underlineColorAndroid="transparent"
inputAccessoryViewID={BlueDoneAndDismissKeyboardInputAccessory.InputAccessoryViewID}
testID="HostInput"
onFocus={() => this.setState({ isAndroidAddressKeyboardVisible: true })}
onBlur={() => this.setState({ isAndroidAddressKeyboardVisible: false })}
/>
2020-03-29 13:16:49 +02:00
</View>
<BlueSpacing20 />
<View style={styles.portWrap}>
2021-04-28 16:57:14 +02:00
<View style={styles.inputWrap}>
<TextInput
placeholder={loc.formatString(loc.settings.electrum_port, { example: '50001' })}
value={this.state.sslPort?.trim() === '' || this.state.sslPort === null ? this.state.port : this.state.sslPort}
onChangeText={text =>
this.setState(prevState => {
if (prevState.sslPort?.trim() === '') {
return { port: text.trim(), sslPort: '' };
} else {
return { port: '', sslPort: text.trim() };
}
})
2021-04-28 16:57:14 +02:00
}
numberOfLines={1}
style={styles.inputText}
editable={!this.state.isLoading}
placeholderTextColor="#81868e"
underlineColorAndroid="transparent"
2021-04-28 16:57:14 +02:00
autoCorrect={false}
autoCapitalize="none"
keyboardType="number-pad"
inputAccessoryViewID={BlueDismissKeyboardInputAccessory.InputAccessoryViewID}
testID="PortInput"
onFocus={() => this.setState({ isAndroidNumericKeyboardFocused: true })}
onBlur={() => this.setState({ isAndroidNumericKeyboardFocused: false })}
2021-04-28 16:57:14 +02:00
/>
</View>
<BlueText style={styles.usePort}>{loc.settings.use_ssl}</BlueText>
<Switch
testID="SSLPortInput"
value={this.state.sslPort?.trim() > 0}
onValueChange={this.useSSLPortToggled}
disabled={this.state.host?.endsWith('.onion') ?? false}
/>
</View>
<BlueSpacing20 />
2021-04-28 16:57:14 +02:00
<View style={styles.serverAddTitle}>
<BlueText style={styles.explain}>{loc.settings.electrum_settings_explain}</BlueText>
<TouchableOpacity accessibilityRole="button" testID="ResetToDefault" onPress={() => this.resetToDefault()}>
<BlueText>{loc.settings.electrum_reset}</BlueText>
</TouchableOpacity>
</View>
<BlueSpacing20 />
{this.state.isLoading ? <BlueLoading /> : <BlueButton testID="Save" onPress={this.save} title={loc.settings.save} />}
<BlueSpacing20 />
<BlueButtonLink title={loc.wallets.import_scan_qr} onPress={this.importScan} />
<BlueSpacing20 />
</BlueCard>
{Platform.select({
ios: <BlueDismissKeyboardInputAccessory />,
android: this.state.isAndroidNumericKeyboardFocused && <BlueDismissKeyboardInputAccessory />,
})}
2021-04-28 16:57:14 +02:00
{Platform.select({
ios: (
<BlueDoneAndDismissKeyboardInputAccessory
onClearTapped={() => this.setState({ host: '' })}
onPasteTapped={text => {
this.setState({ host: text });
Keyboard.dismiss();
}}
/>
),
android: this.state.isAndroidAddressKeyboardVisible && (
<BlueDoneAndDismissKeyboardInputAccessory
onClearTapped={() => {
this.setState({ host: '' });
Keyboard.dismiss();
}}
onPasteTapped={text => {
this.setState({ host: text });
Keyboard.dismiss();
}}
/>
),
})}
</KeyboardAvoidingView>
{serverHistoryItems.length > 0 && !this.state.isLoading && (
<BlueCard>
<View style={styles.serverHistoryTitle}>
<BlueText style={styles.explain}>{loc.settings.electrum_history}</BlueText>
<TouchableOpacity accessibilityRole="button" onPress={() => this.clearHistoryAlert()}>
<BlueText>{loc.settings.electrum_clear}</BlueText>
</TouchableOpacity>
</View>
{serverHistoryItems}
</BlueCard>
)}
</>
);
};
render() {
return (
<SafeBlueArea>
<ScrollView keyboardShouldPersistTaps="always">
<BlueListItem
Component={Pressable}
title={loc.settings.electrum_offline_mode}
switch={{
onValueChange: this.onElectrumConnectionEnabledSwitchValueChangd,
value: this.state.isOfflineMode,
testID: 'ElectrumConnectionEnabledSwitch',
}}
/>
<BlueCard>
<BlueText>{loc.settings.electrum_offline_description}</BlueText>
</BlueCard>
{!this.state.isOfflineMode && this.renderElectrumSettings()}
</ScrollView>
2019-07-18 12:22:01 +02:00
</SafeBlueArea>
);
}
}
2020-10-26 16:31:23 +01:00
ElectrumSettings.propTypes = {
navigation: PropTypes.shape({
navigate: PropTypes.func,
goBack: PropTypes.func,
}),
route: PropTypes.shape({
name: PropTypes.string,
params: PropTypes.shape({
server: PropTypes.string,
}),
2020-10-26 16:31:23 +01:00
}),
};
2021-02-22 08:27:23 +01:00
ElectrumSettings.navigationOptions = navigationStyle({}, opts => ({ ...opts, title: loc.settings.electrum_settings_server }));
2020-10-26 16:31:23 +01:00
const styles = StyleSheet.create({
status: {
textAlign: 'center',
color: BlueCurrentTheme.colors.feeText,
marginBottom: 4,
},
connectWrap: {
width: 'auto',
height: 34,
flexWrap: 'wrap',
justifyContent: 'center',
flexDirection: 'row',
},
container: {
paddingTop: 6,
paddingBottom: 6,
paddingLeft: 16,
paddingRight: 16,
borderRadius: 20,
},
containerConnected: {
backgroundColor: BlueCurrentTheme.colors.feeLabel,
},
containerDisconnected: {
backgroundColor: BlueCurrentTheme.colors.redBG,
2020-10-26 16:31:23 +01:00
},
textConnected: {
color: BlueCurrentTheme.colors.feeValue,
fontWeight: 'bold',
},
textDisconnected: {
color: BlueCurrentTheme.colors.redText,
2020-10-26 16:31:23 +01:00
fontWeight: 'bold',
},
hostname: {
textAlign: 'center',
color: BlueCurrentTheme.colors.foregroundColor,
},
2021-07-05 05:05:04 +02:00
usePort: {
textAlign: 'center',
color: BlueCurrentTheme.colors.foregroundColor,
marginHorizontal: 8,
},
2020-10-26 16:31:23 +01:00
explain: {
color: BlueCurrentTheme.colors.feeText,
marginBottom: -24,
2021-02-22 08:27:23 +01:00
flexShrink: 1,
2020-10-26 16:31:23 +01:00
},
2021-04-27 03:33:56 +02:00
flexShrink: {
flexShrink: 1,
marginRight: 8,
alignItems: 'flex-start',
},
2020-10-26 16:31:23 +01:00
inputWrap: {
2021-07-05 05:05:04 +02:00
flex: 1,
2020-10-26 16:31:23 +01:00
flexDirection: 'row',
borderColor: BlueCurrentTheme.colors.formBorder,
borderBottomColor: BlueCurrentTheme.colors.formBorder,
borderWidth: 1,
borderBottomWidth: 0.5,
backgroundColor: BlueCurrentTheme.colors.inputBackgroundColor,
minHeight: 44,
height: 44,
alignItems: 'center',
borderRadius: 4,
},
2021-07-05 05:05:04 +02:00
portWrap: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
},
2020-10-26 16:31:23 +01:00
inputText: {
flex: 1,
marginHorizontal: 8,
minHeight: 36,
color: '#81868e',
height: 36,
},
2020-12-25 17:20:15 +01:00
serverAddTitle: {
flexDirection: 'row',
justifyContent: 'space-between',
2021-04-27 18:19:36 +02:00
marginVertical: 16,
2020-12-25 17:20:15 +01:00
},
serverHistoryTitle: {
flexDirection: 'row',
justifyContent: 'space-between',
paddingVertical: 10,
},
serverHistoryItem: {
flexDirection: 'row',
paddingVertical: 20,
borderBottomColor: BlueCurrentTheme.colors.formBorder,
2021-04-28 16:57:14 +02:00
borderBottomWidth: 0.5,
2021-04-27 18:19:36 +02:00
flexWrap: 'nowrap',
2020-12-25 17:20:15 +01:00
},
2021-04-27 18:19:36 +02:00
serverRow: {
flexGrow: 2,
maxWidth: '80%',
color: BlueCurrentTheme.colors.foregroundColor,
},
selectButton: {
flexGrow: 1,
marginLeft: 16,
alignItems: 'flex-end',
2021-04-23 13:29:45 +02:00
},
2020-10-26 16:31:23 +01:00
});