Skip to content
This repository was archived by the owner on Feb 9, 2026. It is now read-only.

Commit c231592

Browse files
Merge pull request #127 from synonymdev/ldk-115
LDK 0.0.115
2 parents 2caec98 + d43d4ed commit c231592

143 files changed

Lines changed: 46849 additions & 398043 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
.idea/
22
**/.DS_Store
3+
example/.watchman*

lib/android/libs/LDK-release.aar

438 KB
Binary file not shown.

lib/android/src/main/java/com/reactnativeldk/Helpers.kt

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -39,17 +39,16 @@ fun String.hexa(): ByteArray {
3939
fun getProbabilisticScorer(path: String, networkGraph: NetworkGraph, logger: Logger): ProbabilisticScorer? {
4040
val params = ProbabilisticScoringParameters.with_default()
4141

42-
//TODO loading cached scorer currently broken
43-
// val scorerFile = File(path + "/" + LdkFileNames.scorer.fileName)
44-
// if (scorerFile.exists()) {
45-
// val read = ProbabilisticScorer.read(scorerFile.readBytes(), params, networkGraph, logger)
46-
// if (read.is_ok) {
47-
// LdkEventEmitter.send(EventTypes.native_log, "Loaded scorer from disk")
48-
// return (read as Result_ProbabilisticScorerDecodeErrorZ.Result_ProbabilisticScorerDecodeErrorZ_OK).res
49-
// } else {
50-
// LdkEventEmitter.send(EventTypes.native_log, "Failed to load cached scorer")
51-
// }
52-
// }
42+
val scorerFile = File(path + "/" + LdkFileNames.scorer.fileName)
43+
if (scorerFile.exists()) {
44+
val read = ProbabilisticScorer.read(scorerFile.readBytes(), params, networkGraph, logger)
45+
if (read.is_ok) {
46+
LdkEventEmitter.send(EventTypes.native_log, "Loaded scorer from disk")
47+
return (read as Result_ProbabilisticScorerDecodeErrorZ.Result_ProbabilisticScorerDecodeErrorZ_OK).res
48+
} else {
49+
LdkEventEmitter.send(EventTypes.native_log, "Failed to load cached scorer")
50+
}
51+
}
5352

5453
val default_scorer = ProbabilisticScorer.of(params, networkGraph, logger)
5554
val score_res = ProbabilisticScorer.read(
@@ -219,7 +218,7 @@ fun RapidGossipSync.downloadAndUpdateGraph(downloadUrl: String, tempStoragePath:
219218
return@downloadFile completion(it)
220219
}
221220

222-
val res = update_network_graph(File(destinationFile).readBytes())
221+
val res = update_network_graph_no_std(File(destinationFile).readBytes(), Option_u64Z.some((System.currentTimeMillis() / 1000)))
223222
if (!res.is_ok()) {
224223
val error = res as? Result_u32GraphSyncErrorZ.Result_u32GraphSyncErrorZ_Err
225224

@@ -279,6 +278,10 @@ fun ChannelHandshakeConfig.mergeWithMap(map: ReadableMap?): ChannelHandshakeConf
279278
try {
280279
_their_channel_reserve_proportional_millionths = map.getInt("their_channel_reserve_proportional_millionths")
281280
} catch (_: Exception) {}
281+
//TODO add _our_max_accepted_htlcs_arg when added to the bindings as it is in swift and JS
282+
// try {
283+
// _our_max_accepted_htlcs_arg = map.getInt("our_max_accepted_htlcs_arg")
284+
// } catch (_: Exception) {}
282285

283286
return this
284287
}

lib/android/src/main/java/com/reactnativeldk/LdkModule.kt

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -405,10 +405,12 @@ class LdkModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaMod
405405
channelManagerConstructor = ChannelManagerConstructor(
406406
channelManagerSerialized,
407407
channelMonitors.toTypedArray(),
408-
userConfig,
409-
keysManager!!,
408+
userConfig!!,
409+
keysManager!!.as_EntropySource(),
410+
keysManager!!.as_NodeSigner(),
411+
keysManager!!.as_SignerProvider(),
410412
feeEstimator.feeEstimator,
411-
chainMonitor,
413+
chainMonitor!!,
412414
filter.filter,
413415
networkGraph!!.write(),
414416
scoringParams,
@@ -426,7 +428,9 @@ class LdkModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaMod
426428
userConfig,
427429
blockHash.hexa().reversedArray(),
428430
blockHeight.toInt(),
429-
keysManager!!,
431+
keysManager!!.as_EntropySource(),
432+
keysManager!!.as_NodeSigner(),
433+
keysManager!!.as_SignerProvider(),
430434
feeEstimator.feeEstimator,
431435
chainMonitor,
432436
networkGraph!!,

lib/android/src/main/java/com/reactnativeldk/classes/LdkChannelManagerPersister.kt

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,9 @@ class LdkChannelManagerPersister: ChannelManagerConstructor.EventHandler {
5959
body.putHexString("payment_id", paymentPathSuccessful.payment_id)
6060
body.putHexString("payment_hash", paymentPathSuccessful.payment_hash)
6161

62-
val path = Arguments.createArray()
63-
paymentPathSuccessful.path.iterator().forEach { path.pushMap(it.asJson) }
64-
body.putArray("path", path)
62+
val pathHops = Arguments.createArray()
63+
println(paymentPathSuccessful.path)
64+
body.putArray("path_hops", pathHops)
6565

6666
return LdkEventEmitter.send(EventTypes.channel_manager_payment_path_successful, body)
6767
}
@@ -72,9 +72,9 @@ class LdkChannelManagerPersister: ChannelManagerConstructor.EventHandler {
7272
body.putHexString("payment_hash", paymentPathFailed.payment_hash)
7373
body.putBoolean("payment_failed_permanently", paymentPathFailed.payment_failed_permanently)
7474
body.putInt("short_channel_id", (paymentPathFailed.short_channel_id as Option_u64Z.Some).some.toInt())
75-
val path = Arguments.createArray()
76-
paymentPathFailed.path.iterator().forEach { path.pushMap(it.asJson) }
77-
body.putArray("path", path)
75+
// val path = Arguments.createArray()
76+
// paymentPathFailed.path.iterator().forEach { path.pushMap(it.asJson) }
77+
// body.putArray("path_hops", path)
7878

7979
return LdkEventEmitter.send(EventTypes.channel_manager_payment_path_failed, body)
8080
}
@@ -154,9 +154,9 @@ class LdkChannelManagerPersister: ChannelManagerConstructor.EventHandler {
154154
}
155155

156156
override fun persist_scorer(p0: ByteArray?) {
157-
// if (p0 != null && LdkModule.accountStoragePath != "") {
158-
// File(LdkModule.accountStoragePath + "/" + LdkFileNames.scorer.fileName).writeBytes(p0)
159-
// LdkEventEmitter.send(EventTypes.native_log, "Persisted scorer to disk")
160-
// }
157+
if (p0 != null && LdkModule.accountStoragePath != "") {
158+
File(LdkModule.accountStoragePath + "/" + LdkFileNames.scorer.fileName).writeBytes(p0)
159+
LdkEventEmitter.send(EventTypes.native_log, "Persisted scorer to disk")
160+
}
161161
}
162162
}

lib/ios/Classes/LdkChannelManagerPersister.swift

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ class LdkChannelManagerPersister: Persister, ExtendedChannelManagerPersister {
9797
body: [
9898
"payment_id": Data(paymentPathSuccessful.getPaymentId()).hexEncodedString(),
9999
"payment_hash": Data(paymentPathSuccessful.getPaymentHash()).hexEncodedString(),
100-
"path": paymentPathSuccessful.getPath().map { $0.asJson },
100+
"path_hops": paymentPathSuccessful.getPath().getHops().map { $0.asJson },
101101
]
102102
)
103103
return
@@ -113,7 +113,7 @@ class LdkChannelManagerPersister: Persister, ExtendedChannelManagerPersister {
113113
"payment_hash": Data(paymentPathFailed.getPaymentHash()).hexEncodedString(),
114114
"payment_failed_permanently": paymentPathFailed.getPaymentFailedPermanently(),
115115
"short_channel_id": String(paymentPathFailed.getShortChannelId() ?? 0),
116-
"path": paymentPathFailed.getPath().map { $0.asJson }
116+
"path_hops": paymentPathFailed.getPath().getHops().map { $0.asJson }
117117
]
118118
)
119119
return
@@ -244,18 +244,17 @@ class LdkChannelManagerPersister: Persister, ExtendedChannelManagerPersister {
244244
}
245245

246246
override func persistScorer(scorer: WriteableScore) -> Bindings.Result_NoneErrorZ {
247-
return Result_NoneErrorZ.initWithOk()
248-
// guard let scorerStorage = Ldk.accountStoragePath?.appendingPathComponent(LdkFileNames.scorer.rawValue) else {
249-
// return Result_NoneErrorZ.initWithErr(e: .Other)
250-
// }
251-
//
252-
// do {
253-
// try Data(scorer.write()).write(to: scorerStorage)
254-
//
255-
// return Result_NoneErrorZ.initWithOk()
256-
// } catch {
257-
// LdkEventEmitter.shared.send(withEvent: .native_log, body: "Error. Failed to persist scorer to disk Error \(error.localizedDescription).")
258-
// return Result_NoneErrorZ.initWithErr(e: .Other)
259-
// }
247+
guard let scorerStorage = Ldk.accountStoragePath?.appendingPathComponent(LdkFileNames.scorer.rawValue) else {
248+
return Result_NoneErrorZ.initWithErr(e: .Other)
249+
}
250+
251+
do {
252+
try Data(scorer.write()).write(to: scorerStorage)
253+
254+
return Result_NoneErrorZ.initWithOk()
255+
} catch {
256+
LdkEventEmitter.shared.send(withEvent: .native_log, body: "Error. Failed to persist scorer to disk Error \(error.localizedDescription).")
257+
return Result_NoneErrorZ.initWithErr(e: .Other)
258+
}
260259
}
261260
}

lib/ios/Helpers.swift

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -53,17 +53,16 @@ func getProbabilisticScorer(path: URL, networkGraph: NetworkGraph, logger: LdkLo
5353
let scoringParams = ProbabilisticScoringParameters.initWithDefault()
5454

5555
var probabalisticScorer: ProbabilisticScorer?
56-
//TODO loading cached scorer currently broken
57-
// if let storedScorer = try? Data(contentsOf: path.appendingPathComponent(LdkFileNames.scorer.rawValue).standardizedFileURL) {
58-
// let scorerRead = ProbabilisticScorer.read(ser: [UInt8](storedScorer), argA: scoringParams, argB: networkGraph, argC: logger)
59-
//
60-
// if scorerRead.isOk() {
61-
// LdkEventEmitter.shared.send(withEvent: .native_log, body: "Loaded scorer from disk")
62-
// probabalisticScorer = scorerRead.getValue()
63-
// } else {
64-
// LdkEventEmitter.shared.send(withEvent: .native_log, body: "Failed to load cached scorer")
65-
// }
66-
// }
56+
if let storedScorer = try? Data(contentsOf: path.appendingPathComponent(LdkFileNames.scorer.rawValue).standardizedFileURL) {
57+
let scorerRead = ProbabilisticScorer.read(ser: [UInt8](storedScorer), argA: scoringParams, argB: networkGraph, argC: logger)
58+
59+
if scorerRead.isOk() {
60+
LdkEventEmitter.shared.send(withEvent: .native_log, body: "Loaded scorer from disk")
61+
probabalisticScorer = scorerRead.getValue()
62+
} else {
63+
LdkEventEmitter.shared.send(withEvent: .native_log, body: "Failed to load cached scorer")
64+
}
65+
}
6766

6867
//Doesn't exist or error reading it
6968
if probabalisticScorer == nil {
@@ -275,12 +274,14 @@ extension RapidGossipSync {
275274

276275
let url = URL(string: "\(downloadUrl)\(timestamp)")!
277276

278-
let task = url.downloadTask(destination: destinationFile) { error in
277+
let task = url.downloadTask(destination: destinationFile) { [weak self] error in
279278
if let error = error {
280279
return completion(error)
281280
}
282-
283-
let res = self.updateNetworkGraph(updateData: [UInt8](try! Data(contentsOf: destinationFile)))
281+
282+
guard let self = self else { return }
283+
284+
let res = self.updateNetworkGraphNoStd(updateData: [UInt8](try! Data(contentsOf: destinationFile)), currentTimeUnix: UInt64(Date().timeIntervalSince1970 * 1000))
284285
guard res.isOk() else {
285286
var errorMessage = "Failed to update network graph."
286287
switch res.getError()?.getValueType() {
@@ -324,7 +325,8 @@ extension ChannelHandshakeConfig {
324325
negotiateScidPrivacyArg: obj["negotiate_scid_privacy"] as? Bool ?? defaults.getNegotiateScidPrivacy(),
325326
announcedChannelArg: obj["announced_channel"] as? Bool ?? defaults.getAnnouncedChannel(),
326327
commitUpfrontShutdownPubkeyArg: obj["commit_upfront_shutdown_pubkey"] as? Bool ?? defaults.getCommitUpfrontShutdownPubkey(),
327-
theirChannelReserveProportionalMillionthsArg: obj["their_channel_reserve_proportional_millionths"] as? UInt32 ?? defaults.getTheirChannelReserveProportionalMillionths()
328+
theirChannelReserveProportionalMillionthsArg: obj["their_channel_reserve_proportional_millionths"] as? UInt32 ?? defaults.getTheirChannelReserveProportionalMillionths(),
329+
ourMaxAcceptedHtlcsArg: obj["our_max_accepted_htlcs_arg"] as? UInt16 ?? defaults.getOurMaxAcceptedHtlcs()
328330
)
329331
}
330332
}

lib/ios/Ldk.swift

Lines changed: 1 addition & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -404,7 +404,7 @@ class Ldk: NSObject {
404404
channelManagerConstructor = try ChannelManagerConstructor(
405405
channelManagerSerialized: [UInt8](channelManagerSerialized),
406406
channelMonitorsSerialized: channelMonitorsSerialized,
407-
netGraphSerialized: networkGraph.write(),
407+
networkGraph: NetworkGraphArgument.instance(networkGraph),
408408
filter: filter,
409409
params: params
410410
)
@@ -750,86 +750,6 @@ class Ldk: NSObject {
750750
}
751751
}
752752

753-
@objc
754-
func payWithRoute(_ route: NSArray, destinationNodeId: NSString, amountSats: NSInteger, cltvExpiryDelta: NSInteger, paymentHash: NSString, paymentSecret: NSString, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
755-
let paymentId = String(paymentHash).hexaBytes //TODO allow passing this through from JS but should default to payment hash
756-
757-
guard let channelManager = channelManager else {
758-
return handleReject(reject, .init_channel_manager)
759-
}
760-
761-
guard let networkGraph = networkGraph?.readOnly() else {
762-
return handleReject(reject, .init_network_graph)
763-
}
764-
765-
//TODO amountSats no longer required
766-
let amountMSats = UInt64(amountSats) * 1000
767-
var paths: [RouteHop] = []
768-
769-
for hop in route {
770-
print("HOP: ")
771-
772-
let decodedHop = hop as! [String: Any]
773-
774-
let pubKey = decodedHop["dest_node_id"]! as! String
775-
let shortChannelId = UInt64(decodedHop["short_channel_id"]! as! String)!
776-
let feeMsats = UInt64(exactly: decodedHop["fee_sats"]! as! Int)! * 1000
777-
778-
var channelFeatures = ChannelFeatures.initWithEmpty()
779-
var nodeFeatures = NodeFeatures.initWithEmpty()
780-
781-
//If it's the last hop then it's the full amount
782-
if pubKey == String(destinationNodeId) {
783-
//Assume public node
784-
let channel = networkGraph.channel(shortChannelId: shortChannelId)
785-
786-
if let cFeatures = channel?.getFeatures() {
787-
channelFeatures = cFeatures
788-
}
789-
790-
if let nFeatures = networkGraph.node(nodeId: NodeId.initWithPubkey(pubkey: pubKey.hexaBytes))?.getAnnouncementInfo()?.getFeatures() {
791-
nodeFeatures = nFeatures
792-
}
793-
}
794-
795-
channelManager.listChannels().forEach { channelDetails in
796-
channelDetails.getConfig()?.getForwardingFeeBaseMsat()
797-
if channelDetails.getShortChannelId() == shortChannelId {
798-
// nodeFeatures = = channelDetails.get_counterparty().get_features() //TODO convert this
799-
//TODO get channel features somehow?
800-
}
801-
}
802-
803-
//TODO Check if channel is ours instead of querying graph
804-
805-
let hop = RouteHop(
806-
pubkeyArg: pubKey.hexaBytes,
807-
nodeFeaturesArg: nodeFeatures,
808-
shortChannelIdArg: shortChannelId,
809-
channelFeaturesArg: channelFeatures,
810-
feeMsatArg: feeMsats,
811-
cltvExpiryDeltaArg: UInt32(cltvExpiryDelta)
812-
)
813-
814-
paths.append(hop)
815-
}
816-
817-
let payee = PaymentParameters.initWithNodeId(payeePubkey: String(destinationNodeId).hexaBytes, finalCltvExpiryDelta: UInt32(cltvExpiryDelta))
818-
819-
let route = Route(pathsArg: [paths], paymentParamsArg: payee)
820-
821-
let res = channelManager.sendPayment(route: route, paymentHash: String(paymentHash).hexaBytes, paymentSecret: String(paymentSecret).hexaBytes, paymentId: paymentId)
822-
if res.isOk() {
823-
return resolve(Data(paymentId).hexEncodedString())
824-
}
825-
826-
guard let error = res.getError() else {
827-
return handleReject(reject, .invoice_payment_fail_unknown)
828-
}
829-
830-
return handlePaymentSendFailure(reject, error: error)
831-
}
832-
833753
@objc
834754
func abandonPayment(_ paymentId: NSString, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
835755
guard let channelManager = channelManager else {

0 commit comments

Comments
 (0)