Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pay Card area #91

Merged
merged 7 commits into from
Jun 25, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions BlueApp.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ class AppStorage {
static ADVANCED_MODE_ENABLED = 'advancedmodeenabled';
static DO_NOT_TRACK = 'donottrack';
static HANDOFF_STORAGE_KEY = 'HandOff';
static FEATURE_FLAGS = 'feature_flags';
static PAY_CARD = 'PAY_CARD';
static FF_LDS_DEV_API = 'ff_lds_dev_api';

static keys2migrate = [AppStorage.HANDOFF_STORAGE_KEY, AppStorage.DO_NOT_TRACK, AppStorage.ADVANCED_MODE_ENABLED];
Expand Down Expand Up @@ -398,8 +398,8 @@ class AppStorage {
break;
case LightningCustodianWallet.type:
case LightningLdsWallet.type: {
/** @type {LightningCustodianWallet} */
unserializedWallet = LightningCustodianWallet.fromJson(key);
unserializedWallet =
tempObj.type === LightningCustodianWallet.type ? LightningCustodianWallet.fromJson(key) : LightningLdsWallet.fromJson(key);
let lndhub = false;
try {
lndhub = await AsyncStorage.getItem(AppStorage.LNDHUB);
Expand Down Expand Up @@ -839,15 +839,15 @@ class AppStorage {
await AsyncStorage.setItem(AppStorage.ADVANCED_MODE_ENABLED, value ? '1' : '');
};

isFeatureFlagsEnabled = async () => {
isPayCardEnabled = async () => {
try {
return !!(await AsyncStorage.getItem(AppStorage.FEATURE_FLAGS));
return !!(await AsyncStorage.getItem(AppStorage.PAY_CARD));
} catch (_) {}
return false;
};

setIsFeatureFlagsEnabled = async value => {
await AsyncStorage.setItem(AppStorage.FEATURE_FLAGS, value ? '1' : '');
setIsPayCardEnabled = async value => {
await AsyncStorage.setItem(AppStorage.PAY_CARD, value ? '1' : '');
};

isLdsDevEnabled = async () => {
Expand Down
10 changes: 10 additions & 0 deletions Navigation.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,11 @@ import Asset from './screen/wallets/asset';
import AddLightning from './screen/wallets/dfx/add-lightning';
import LNDReceive from './screen/lnd/lndReceive';
import FeatureFlags from './screen/settings/FeatureFlags';
import AddBoltcard from './screen/boltcard/add';
import BoltcardDetails from './screen/boltcard/details';
import BackupBolcard from './screen/boltcard/backup';
import DeleteBolcard from './screen/boltcard/delete';
import WrittenCardError from './screen/boltcard/writtenCardError';

const WalletsStack = createNativeStackNavigator();

Expand All @@ -110,6 +115,11 @@ const WalletsRoot = () => {
component={WalletsAddMultisigStep2}
options={WalletsAddMultisigStep2.navigationOptions(theme)}
/>
<WalletsStack.Screen name="AddBoltcard" component={AddBoltcard} options={AddBoltcard.navigationOptions(theme)} />
<WalletsStack.Screen name="BoltCardDetails" component={BoltcardDetails} options={BoltcardDetails.navigationOptions(theme)} />
<WalletsStack.Screen name="BackupBoltcard" component={BackupBolcard} options={BackupBolcard.navigationOptions(theme)} />
<WalletsStack.Screen name="DeleteBoltcard" component={DeleteBolcard} options={DeleteBolcard.navigationOptions(theme)} />
<WalletsStack.Screen name="WrittenCardError" component={WrittenCardError} options={WrittenCardError.navigationOptions(theme)} />
<WalletsStack.Screen name="LdkOpenChannel" component={LdkOpenChannel} options={LdkOpenChannel.navigationOptions(theme)} />
<WalletsStack.Screen name="LdkInfo" component={LdkInfo} options={LdkInfo.navigationOptions(theme)} />
<WalletsStack.Screen name="WalletDetails" component={WalletDetails} options={WalletDetails.navigationOptions(theme)} />
Expand Down
42 changes: 42 additions & 0 deletions api/boltcards/definitions/apiDtos.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
export interface BoltcardUpdateDTO {
card_name: string;
counter: number;
daily_limit: number;
enable: boolean;
id: string;
k0: string;
k1: string;
k2: string;
prev_k0: string;
prev_k1: string;
prev_k2: string;
time: number;
tx_limit: number;
uid: string;
wallet: string;
}

export interface BoltcardCreateDTO {
card_name: string;
counter: number;
daily_limit: number;
tx_limit: number;
uid: string;
k0: string;
k1: string;
k2: string;
k3: string;
k4: string;
}

export interface Hit {
id: string;
amount: number;
card_id: string;
ip: string;
new_ctr: number;
old_ctr: number;
spent: boolean;
time: number;
useragent: string;
}
7 changes: 7 additions & 0 deletions api/boltcards/definitions/urls.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export const BoltcardUrl = Object.freeze({
cards: '/boltcards/cards',
auth: '/boltcards/auth',
scan: '/boltcards/scan',
enable: '/boltcards/cards/enable',
hits: '/boltcards/hits',
});
44 changes: 44 additions & 0 deletions api/boltcards/hooks/api.hook.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { useContext, useMemo } from 'react';
import Config from 'react-native-config';
import { BlueStorageContext } from '../../../blue_modules/storage-context';

export interface ApiInterface {
call: <T>(config: CallConfig) => Promise<T>;
}

export interface CallConfig {
url: string;
method: 'GET' | 'PUT' | 'POST' | 'DELETE';
data?: any;
apiKey?: string;
}

export function useApi(): ApiInterface {
const { ldsDEV } = useContext(BlueStorageContext);

function buildInit(method: 'GET' | 'PUT' | 'POST' | 'DELETE', apiKey?: string | null, data?: any): RequestInit {
return {
method,
headers: {
'Content-Type': 'application/json',
'X-Api-Key': apiKey || '',
},
body: JSON.stringify(data),
};
}

async function call<T>(config: CallConfig): Promise<T> {
const baseUrl = ldsDEV ? Config.REACT_APP_LDS_DEV_URL : Config.REACT_APP_LDS_URL;
return fetch(`${baseUrl}/${config.url}`, buildInit(config.method, config.apiKey, config.data)).then(response => {
if (response.ok) {
return response.json().catch(() => undefined);
}
return response.json().then(body => {
throw body;
});
});
}

// eslint-disable-next-line react-hooks/exhaustive-deps
return useMemo(() => ({ call }), []);
}
85 changes: 85 additions & 0 deletions api/boltcards/hooks/bolcards.hook.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { useApi } from './api.hook';
import { BoltcardUrl } from '../definitions/urls';
import { BoltcardCreateDTO, BoltcardUpdateDTO, Hit } from '../definitions/apiDtos';
import { BolcardSecrets, BoltCardModel } from '../../../models/boltcard';
import { useWalletContext } from '../../../contexts/wallet.context';
const createHash = require('create-hash');

type UseLdsBoltcards = {
getBoltcards: (invoiceId: string) => Promise<BoltCardModel[]>;
createBoltcard: (adminKey: string) => Promise<BoltCardModel>;
getBoltcardSecret: (boltcard: BoltCardModel) => Promise<BolcardSecrets>;
updateBoltcard: (adminKey: string, boltcard: BoltcardUpdateDTO) => Promise<BoltCardModel>;
enableBoltcard: (adminKey: string, boltcard: BoltcardUpdateDTO, state: boolean) => Promise<BoltCardModel>;
getHits: (invoiceId: string) => Promise<Hit[]>;
deleteBoltcard: (adminKey: string, boltcard: BoltCardModel) => Promise<void>;
};

const generateRandomHex = (size: number): string => [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16)).join('');

const hashIt = (s: string) => createHash('sha256').update(s).digest().toString('hex');

export function useLdsBoltcards(): UseLdsBoltcards {
const { getOwnershipProof } = useWalletContext();
const { call } = useApi();

const genFreshCardDetails = async (): Promise<BoltcardCreateDTO> => {
const ownerProof = await getOwnershipProof();
const k0 = hashIt(`k0-seed-${ownerProof}`).slice(0, 32);
const k1 = hashIt(`k1-k3-seed-${ownerProof}`).slice(0, 32);
const k2 = hashIt(`k2-k4-seed-${ownerProof}`).slice(0, 32);

return {
card_name: 'BITCOIN PAY CARD',
k0,
k1,
k2,
k3: k1,
k4: k2,
counter: 0,
tx_limit: 100000,
daily_limit: 100000,
uid: generateRandomHex(14), // dummy value, the phisical card holds the real value
};
};

const getBoltcards = async (invoiceId: string): Promise<BoltCardModel[]> => {
return call<BoltCardModel[]>({ method: 'GET', url: BoltcardUrl.cards, apiKey: invoiceId });
};

const createBoltcard = async (adminKey: string): Promise<BoltCardModel> => {
const freshCardDetails = await genFreshCardDetails();
return call<BoltCardModel>({ method: 'POST', url: BoltcardUrl.cards, apiKey: adminKey, data: freshCardDetails });
};

const getBoltcardSecret = async ({ otp }: BoltCardModel): Promise<BolcardSecrets> => {
const url = new URL(BoltcardUrl.auth);
url.searchParams.append('a', otp);
return call<BolcardSecrets>({ method: 'GET', url: url.toString() });
};

const updateBoltcard = async (adminKey: string, boltcard: BoltcardUpdateDTO): Promise<BoltCardModel> => {
return call<BoltCardModel>({ method: 'PUT', url: `${BoltcardUrl.cards}/${boltcard.id}`, apiKey: adminKey, data: boltcard });
};

const enableBoltcard = async (adminKey: string, boltcard: BoltcardUpdateDTO, state: boolean): Promise<BoltCardModel> => {
return call<BoltCardModel>({
method: 'GET',
url: `${BoltcardUrl.enable}/${boltcard.id}/${state ? 'true' : 'false'}`,
apiKey: adminKey,
});
};

const getHits = async (invoiceId: string): Promise<Hit[]> => {
const hits = await call<Hit[]>({ method: 'GET', url: BoltcardUrl.hits, apiKey: invoiceId });
return hits.reverse().filter(({ amount }) => amount > 0);
};

const deleteBoltcard = async (adminKey: string, boltcard: BoltCardModel): Promise<void> => {
await call<void>({ method: 'DELETE', url: `${BoltcardUrl.cards}/${boltcard.id}`, apiKey: adminKey });
};

return { getBoltcards, createBoltcard, getBoltcardSecret, updateBoltcard, enableBoltcard, getHits, deleteBoltcard };
}

export default useLdsBoltcards;
126 changes: 126 additions & 0 deletions api/boltcards/hooks/ntag424.hook.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import { useEffect } from 'react';
import NfcManager, { NfcTech, Ndef } from 'react-native-nfc-manager';
import { BolcardSecrets } from '../../../models/boltcard';
import Ntag424 from '../../../class/Ntag424';
import loc from '../../../loc';
import { Platform } from 'react-native';

interface CardKeys {
k0: string;
k1: string;
k2: string;
k3: string;
k4: string;
lnurlw_base: string;
}

type CardKeysWithUid = CardKeys & {
uid: string;
version: number;
};

interface UseNtag424Interface {
writeCard: (cardDetails: CardKeys) => Promise<CardKeysWithUid>;
wipeCard: (cardDetails: BolcardSecrets) => Promise<void>;
stopNfcSession: () => void;
}

export function useNtag424(): UseNtag424Interface {
useEffect(() => {
Ntag424.setSendAPDUCommand(async (commandBytes: number[]) => {
const response = Platform.OS == 'ios' ? await NfcManager.sendCommandAPDUIOS(commandBytes) : await NfcManager.transceive(commandBytes);
let newResponse: any = response;
if (Platform.OS == 'android') {
newResponse = {};
newResponse.response = response.slice(0, -2);
newResponse.sw1 = response.slice(-2, -1);
newResponse.sw2 = response.slice(-1);
}
return newResponse;
});

return () => {
NfcManager.cancelTechnologyRequest();
};
}, []);

const writeCard = async (cardDetails: CardKeys): Promise<CardKeysWithUid> => {
try {
await NfcManager.requestTechnology(NfcTech.IsoDep, {
alertMessage: loc.boltcard.alert_message_write_card,
});

const ndefMessage = `${cardDetails.lnurlw_base}?p=00000000000000000000000000000000&c=0000000000000000`;
const message = [Ndef.uriRecord(ndefMessage)];
const bytes = Ndef.encodeMessage(message);
await Ntag424.setNdefMessage(bytes);

const key0 = '00000000000000000000000000000000';
await Ntag424.AuthEv2First('00', key0);

const piccOffset = ndefMessage.indexOf('p=') + 9;
const macOffset = ndefMessage.indexOf('c=') + 9;
await Ntag424.setBoltCardFileSettings(piccOffset, macOffset);
await Ntag424.changeKey('01', key0, cardDetails.k1, '01');
await Ntag424.changeKey('02', key0, cardDetails.k2, '01');
await Ntag424.changeKey('03', key0, cardDetails.k3, '01');
await Ntag424.changeKey('04', key0, cardDetails.k4, '01');
await Ntag424.changeKey('00', key0, cardDetails.k0, '01');

const ndef = await Ntag424.readData('060000');
const setNdefMessage = Ndef.uri.decodePayload(ndef);
const httpsLNURL = setNdefMessage.replace('lnurlw://', 'https://');
fetch(httpsLNURL)
.then(r => r.json())
.then(() => console.log('Boltcard server request success'));

await Ntag424.AuthEv2First('00', cardDetails.k0);

const params: any = {};
setNdefMessage.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
params[key] = value;
});
if (!params['p'] || !params['c']) throw new Error('Invalid lnurlw data');

const uid = await Ntag424.getCardUid();
const pVal = params['p'];
const cVal = params['c'].slice(0, 16);
const { pTest, cTest } = await Ntag424.testPAndC(pVal, cVal, uid, cardDetails.k1, cardDetails.k2);
if (!pTest || !cTest) throw new Error(`Test failed for p: ${pTest} and c: ${cTest}`);
NfcManager.cancelTechnologyRequest();

return { ...cardDetails, uid, version: 1 };
} catch (error: any) {
NfcManager.cancelTechnologyRequest();
throw error;
}
};

const wipeCard = async (cardDetails: BolcardSecrets) => {
try {
await NfcManager.requestTechnology(NfcTech.IsoDep, {
alertMessage: loc.boltcard.alert_message_write_card,
});
const defaultKey = '00000000000000000000000000000000';
await Ntag424.AuthEv2First('00', cardDetails.k0);
await Ntag424.resetFileSettings();
await Ntag424.changeKey('01', cardDetails.k1, defaultKey, '00');
await Ntag424.changeKey('02', cardDetails.k2, defaultKey, '00');
await Ntag424.changeKey('03', cardDetails.k3, defaultKey, '00');
await Ntag424.changeKey('04', cardDetails.k4, defaultKey, '00');
await Ntag424.changeKey('00', cardDetails.k0, defaultKey, '00');
const message = [Ndef.uriRecord('')];
const bytes = Ndef.encodeMessage(message);
await Ntag424.setNdefMessage(bytes);
} catch (error: any) {
NfcManager.cancelTechnologyRequest();
throw error;
} finally {
NfcManager.cancelTechnologyRequest();
}
};

const stopNfcSession = () => NfcManager.cancelTechnologyRequest();

return { writeCard, wipeCard, stopNfcSession };
}
Loading