Skip to content

Commit 31f8d2f

Browse files
committed
Replace react-native-securerandom as a dependency
1 parent cdbd1eb commit 31f8d2f

File tree

15 files changed

+345
-147
lines changed

15 files changed

+345
-147
lines changed

android/app/src/main/java/com/blixtwallet/LndMobileTools.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
import java.io.FileNotFoundException;
3434
import java.io.IOException;
3535
import java.io.InputStreamReader;
36+
import java.security.SecureRandom;
3637
import java.util.Arrays;
3738
import java.io.UnsupportedEncodingException;
3839

@@ -756,6 +757,14 @@ public void getInternalFiles(Promise promise) {
756757
}
757758
}
758759

760+
@ReactMethod
761+
public void generateSecureRandomAsBase64(int length, Promise promise) {
762+
SecureRandom secureRandom = new SecureRandom();
763+
byte[] buffer = new byte[length];
764+
secureRandom.nextBytes(buffer);
765+
promise.resolve(Base64.encodeToString(buffer, Base64.NO_WRAP));
766+
}
767+
759768
private void checkWriteExternalStoragePermission(@NonNull RequestWriteExternalStoragePermissionCallback successCallback,
760769
@NonNull Runnable failCallback,
761770
@NonNull Runnable failPermissionCheckcallback) {

ios/LndMobile/LndMobileTools.m

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,4 +139,9 @@ @interface RCT_EXTERN_MODULE(LndMobileTools, RCTEventEmitter)
139139
rejecter: (RCTPromiseRejectBlock)reject
140140
)
141141

142+
RCT_EXTERN_METHOD(
143+
generateSecureRandomAsBase64: (NSInteger)length
144+
resolver: (RCTPromiseResolveBlock)resolve
145+
rejecter: (RCTPromiseRejectBlock)reject
146+
)
142147
@end

ios/LndMobile/LndMobileTools.swift

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -702,4 +702,23 @@ autopilot.heuristic=preferential:0.05
702702
}
703703
resolve(filesMap)
704704
}
705+
706+
@objc(generateSecureRandomAsBase64:resolver:rejecter:)
707+
func generateSecureRandomAsBase64(length: Int, resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: RCTPromiseRejectBlock) {
708+
var bytes = Data(count: length)
709+
let result = bytes.withUnsafeMutableBytes { mutableBytes -> Int32 in
710+
if let baseAddress = mutableBytes.baseAddress {
711+
return SecRandomCopyBytes(kSecRandomDefault, length, baseAddress)
712+
} else {
713+
return errSecParam
714+
}
715+
}
716+
717+
if result == errSecSuccess {
718+
resolve(bytes.base64EncodedString())
719+
} else {
720+
let error = NSError(domain: "LndMobileTools", code: Int(result), userInfo: nil)
721+
reject("randombytes_error", "Error generating random bytes", error)
722+
}
723+
}
705724
}

mocks/lndmobile/index.ts

Lines changed: 87 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -33,16 +33,25 @@ export const writeConfigFile = jest.fn(async () => {
3333
return "File written:";
3434
});
3535

36-
export const subscribeStateEmitter = (data: Uint8Array) => DeviceEventEmitter.emit("SubscribeState", { data: base64.fromByteArray(data) });
36+
export const subscribeStateEmitter = (data: Uint8Array) =>
37+
DeviceEventEmitter.emit("SubscribeState", { data: base64.fromByteArray(data) });
3738
export const subscribeState = async () => {
3839
setTimeout(async () => {
3940
subscribeStateEmitter(
4041
lnrpc.SubscribeStateResponse.encode({
4142
state: lnrpc.WalletState.LOCKED,
42-
}).finish()
43+
}).finish(),
4344
);
44-
}, 10)
45-
}
45+
}, 10);
46+
};
47+
48+
export const generateSecureRandomAsBase64 = jest.fn(async (length: number) => {
49+
return "c2F0b3NoaQ==";
50+
});
51+
52+
export const generateSecureRandom = jest.fn(async (length: number) => {
53+
return new Uint8Array([0, 1, 2, 3]);
54+
});
4655

4756
export const decodeState = (data: string): lnrpc.SubscribeStateResponse => {
4857
return decodeStreamResult<lnrpc.SubscribeStateResponse>({
@@ -84,10 +93,12 @@ export const startLnd = jest.fn(async (): Promise<string> => {
8493

8594
export const getInfoResponse = lnrpc.GetInfoResponse.create({
8695
uris: [],
87-
chains: [{
88-
chain: "bitcoin",
89-
network: "testnet",
90-
}],
96+
chains: [
97+
{
98+
chain: "bitcoin",
99+
network: "testnet",
100+
},
101+
],
91102
identityPubkey: "02b5380da0919e32b13c1a21c1c85000eed0ba9a9309fc6849d72230d43088ae1d",
92103
alias: "02b5380da0919e32b13c",
93104
numPeers: 3,
@@ -100,13 +111,18 @@ export const getInfoResponse = lnrpc.GetInfoResponse.create({
100111
version: "0.7.1-beta commit=v0.7.1-beta-rc1-10-g3760f29f5e758b2865b756604333ca22cf23e90b",
101112
features: {},
102113
});
103-
export const getInfo = jest.fn()
114+
export const getInfo = jest
115+
.fn()
104116
.mockImplementationOnce(async () => getInfoResponse)
105-
.mockImplementation(async () => ({ ...getInfoResponse, syncedToChain: true, syncedToGraph: true }));
117+
.mockImplementation(async () => ({
118+
...getInfoResponse,
119+
syncedToChain: true,
120+
syncedToGraph: true,
121+
}));
106122

107123
export const sendPaymentSync = async (paymentRequest: string): Promise<lnrpc.SendResponse> => {
108124
const response = lnrpc.SendResponse.create({
109-
paymentHash: new Uint8Array([1,2,3,4]),
125+
paymentHash: new Uint8Array([1, 2, 3, 4]),
110126
paymentRoute: {
111127
totalAmt: Long.fromNumber(1000),
112128
totalAmtMsat: Long.fromNumber(1000000),
@@ -121,8 +137,8 @@ export const sendPaymentSync = async (paymentRequest: string): Promise<lnrpc.Sen
121137
export const sendPaymentV2Sync = async (paymentRequest: string): Promise<lnrpc.Payment> => {
122138
await timeout(600);
123139

124-
const paymentHash = new Uint8Array([0,1,2,3]);
125-
const paymentPreimage = new Uint8Array([0,1,2,3]);
140+
const paymentHash = new Uint8Array([0, 1, 2, 3]);
141+
const paymentPreimage = new Uint8Array([0, 1, 2, 3]);
126142

127143
const response = lnrpc.Payment.create({
128144
paymentHash: bytesToHexString(paymentHash),
@@ -131,39 +147,50 @@ export const sendPaymentV2Sync = async (paymentRequest: string): Promise<lnrpc.P
131147
status: lnrpc.Payment.PaymentStatus.SUCCEEDED,
132148
fee: Long.fromValue(1),
133149
feeMsat: Long.fromValue(1000),
134-
htlcs: [{
135-
route: {
136-
hops: [{
137-
chanId: Long.fromValue(1),
138-
chanCapacity: Long.fromValue(10000),
139-
amtToForward: Long.fromValue(100),
140-
amtToForwardMsat: Long.fromValue(100000),
141-
fee: Long.fromValue(1),
142-
feeMsat: Long.fromValue(1000),
143-
expiry: 3600,
144-
pubKey: "abc",
145-
}],
150+
htlcs: [
151+
{
152+
route: {
153+
hops: [
154+
{
155+
chanId: Long.fromValue(1),
156+
chanCapacity: Long.fromValue(10000),
157+
amtToForward: Long.fromValue(100),
158+
amtToForwardMsat: Long.fromValue(100000),
159+
fee: Long.fromValue(1),
160+
feeMsat: Long.fromValue(1000),
161+
expiry: 3600,
162+
pubKey: "abc",
163+
},
164+
],
165+
},
146166
},
147-
}],
167+
],
148168
});
149169
return response;
150170
};
151171

152-
export const addInvoice = async (amount: number, memo: string, expiry: number = 3600): Promise<lnrpc.AddInvoiceResponse> => {
172+
export const addInvoice = async (
173+
amount: number,
174+
memo: string,
175+
expiry: number = 3600,
176+
): Promise<lnrpc.AddInvoiceResponse> => {
153177
try {
154178
const unixTimestamp = Math.floor(Date.now() / 1000);
155179
const encoded = payReq.encode({
156180
coinType: "testnet",
157181
satoshis: amount,
158182
timestamp: unixTimestamp,
159183
timeExpireDate: expiry,
160-
tags: [{
161-
tagName: "payment_hash",
162-
data: "0001020304050607080900010203040506070809000102030405060708090102",
163-
}, {
164-
tagName: "description",
165-
data: memo,
166-
}],
184+
tags: [
185+
{
186+
tagName: "payment_hash",
187+
data: "0001020304050607080900010203040506070809000102030405060708090102",
188+
},
189+
{
190+
tagName: "description",
191+
data: memo,
192+
},
193+
],
167194
});
168195

169196
const privateKeyHex = "e126f68f7eafcc8b74f54d269fe206be715000f94dac067d1c04a8ca3b2db734";
@@ -188,7 +215,7 @@ export const addInvoice = async (amount: number, memo: string, expiry: number =
188215
value: Long.fromNumber(signed!.satoshis!),
189216
amtPaidMsat: Long.fromNumber(signed!.satoshis!).mul(1000),
190217
amtPaidSat: Long.fromNumber(signed!.satoshis!),
191-
cltvExpiry: cltvExpiry && (Long.fromNumber(cltvExpiry.data as number)),
218+
cltvExpiry: cltvExpiry && Long.fromNumber(cltvExpiry.data as number),
192219
creationDate: Long.fromNumber(signed!.timestamp!),
193220
expiry: Long.fromNumber(expiry),
194221
rPreimage: new Uint8Array([1, 2, 3, 4]), // TODO
@@ -207,9 +234,19 @@ export const addInvoice = async (amount: number, memo: string, expiry: number =
207234
}
208235
};
209236

210-
export const addInvoiceBlixtLsp = ({amount, memo, expiry = 600, servicePubkey, chanId, cltvExpiryDelta, feeBaseMsat, feeProportionalMillionths, preimage}: IAddInvoiceBlixtLspArgs) => {
237+
export const addInvoiceBlixtLsp = ({
238+
amount,
239+
memo,
240+
expiry = 600,
241+
servicePubkey,
242+
chanId,
243+
cltvExpiryDelta,
244+
feeBaseMsat,
245+
feeProportionalMillionths,
246+
preimage,
247+
}: IAddInvoiceBlixtLspArgs) => {
211248
return addInvoice(amount, memo, expiry);
212-
}
249+
};
213250

214251
//
215252
// export const lookupInvoice = async (rHash: string): Promise<lnrpc.Invoice> => {
@@ -224,12 +261,16 @@ export const addInvoiceBlixtLsp = ({amount, memo, expiry = 600, servicePubkey, c
224261
// return response;
225262
// };
226263

227-
export const queryRoutes = async (pubKey: string, amount?: Long, routeHints?: lnrpc.IRouteHint[]): Promise<lnrpc.QueryRoutesResponse> => {
264+
export const queryRoutes = async (
265+
pubKey: string,
266+
amount?: Long,
267+
routeHints?: lnrpc.IRouteHint[],
268+
): Promise<lnrpc.QueryRoutesResponse> => {
228269
return lnrpc.QueryRoutesResponse.create({
229270
routes: [],
230271
successProb: 0.5,
231272
});
232-
}
273+
};
233274

234275
// TODO test
235276
export const decodePayReq = async (bolt11: string): Promise<lnrpc.PayReq> => {
@@ -250,30 +291,30 @@ export const decodePayReq = async (bolt11: string): Promise<lnrpc.PayReq> => {
250291
/**
251292
* @throws
252293
*/
253-
export const getRecoveryInfo = async (): Promise<lnrpc.GetRecoveryInfoResponse> => {
294+
export const getRecoveryInfo = async (): Promise<lnrpc.GetRecoveryInfoResponse> => {
254295
const response = lnrpc.GetRecoveryInfoResponse.create({
255296
progress: 1,
256297
recoveryFinished: false,
257298
recoveryMode: false,
258-
})
299+
});
259300
return response;
260301
};
261302

262303
/**
263304
* @throws
264305
*/
265-
export const listUnspent = async (): Promise<lnrpc.ListUnspentResponse> => {
306+
export const listUnspent = async (): Promise<lnrpc.ListUnspentResponse> => {
266307
const response = lnrpc.ListUnspentResponse.create({
267-
utxos: []
268-
})
308+
utxos: [],
309+
});
269310
return response;
270311
};
271312

272313
/**
273314
* @throws
274315
*/
275-
export const resetMissionControl = async (): Promise<routerrpc.ResetMissionControlResponse> => {
276-
const response = routerrpc.ResetMissionControlResponse.create({})
316+
export const resetMissionControl = async (): Promise<routerrpc.ResetMissionControlResponse> => {
317+
const response = routerrpc.ResetMissionControlResponse.create({});
277318
return response;
278319
};
279320

src/lndmobile/LndMobile.d.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ export interface ILndMobile {
3939
export interface ILndMobileTools {
4040
writeConfig(data: string): Promise<string>;
4141
writeConfigFile(): Promise<string>;
42+
generateSecureRandomAsBase64(length: number): Promise<string>;
4243
killLnd(): Promise<boolean>;
4344
log(level: "v" | "d" | "i" | "w" | "e", tag: string, msg: string): void;
4445
saveLogs(): Promise<string>;

0 commit comments

Comments
 (0)