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 all 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
30 changes: 20 additions & 10 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 @@ -100,6 +105,21 @@ const WalletsRoot = () => {
<WalletsStack.Screen name="WalletTransactions" component={WalletHome} options={WalletHome.navigationOptions(theme)} />
<WalletsStack.Screen name="WalletAsset" component={Asset} options={Asset.navigationOptions(theme)} />
<WalletsStack.Screen name="AddLightning" component={AddLightning} options={AddLightning.navigationOptions(theme)} />
<AddWalletStack.Screen
name="WalletsAddMultisig"
component={WalletsAddMultisig}
options={WalletsAddMultisig.navigationOptions(theme)}
/>
<AddWalletStack.Screen
name="WalletsAddMultisigStep2"
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 Expand Up @@ -204,16 +224,6 @@ const AddWalletRoot = () => {
/>
<AddWalletStack.Screen name="PleaseBackupLdk" component={PleaseBackupLdk} options={PleaseBackupLdk.navigationOptions(theme)} />
<AddWalletStack.Screen name="ProvideEntropy" component={ProvideEntropy} options={ProvideEntropy.navigationOptions(theme)} />
<AddWalletStack.Screen
name="WalletsAddMultisig"
component={WalletsAddMultisig}
options={WalletsAddMultisig.navigationOptions(theme)}
/>
<AddWalletStack.Screen
name="WalletsAddMultisigStep2"
component={WalletsAddMultisigStep2}
options={WalletsAddMultisigStep2.navigationOptions(theme)}
/>
<AddWalletStack.Screen
name="WalletsAddMultisigHelp"
component={WalletsAddMultisigHelp}
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, freshCardDetails: BoltcardCreateDTO) => Promise<BoltCardModel>;
genFreshCardDetails: () => Promise<BoltcardCreateDTO>;
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, freshCardDetails: BoltcardCreateDTO): Promise<BoltCardModel> => {
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, genFreshCardDetails, createBoltcard, getBoltcardSecret, updateBoltcard, enableBoltcard, getHits, deleteBoltcard };
}

export default useLdsBoltcards;
Loading