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
18 changes: 12 additions & 6 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,21 +18,23 @@ use crate::gossip::GossipSource;
use crate::io::sqlite_store::SqliteStore;
use crate::io::utils::{read_node_metrics, write_node_metrics};
use crate::io::vss_store::VssStore;
use crate::io::{
self, PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE, PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE,
};
use crate::liquidity::{
LSPS1ClientConfig, LSPS2ClientConfig, LSPS2ServiceConfig, LiquiditySourceBuilder,
};
use crate::logger::{log_error, log_info, LdkLogger, LogLevel, LogWriter, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::store::PaymentStore;
use crate::peer_store::PeerStore;
use crate::tx_broadcaster::TransactionBroadcaster;
use crate::types::{
ChainMonitor, ChannelManager, DynStore, GossipSync, Graph, KeysManager, MessageRouter,
OnionMessenger, PeerManager,
OnionMessenger, PaymentStore, PeerManager,
};
use crate::wallet::persist::KVStoreWalletPersister;
use crate::wallet::Wallet;
use crate::{io, Node, NodeMetrics};
use crate::{Node, NodeMetrics};

use lightning::chain::{chainmonitor, BestBlock, Watch};
use lightning::io::Cursor;
Expand DownExpand Up@@ -1015,9 +1017,13 @@ fn build_with_store_internal(
let fee_estimator = Arc::new(OnchainFeeEstimator::new());

let payment_store = match io::utils::read_payments(Arc::clone(&kv_store), Arc::clone(&logger)) {
Ok(payments) => {
Arc::new(PaymentStore::new(payments, Arc::clone(&kv_store), Arc::clone(&logger)))
},
Ok(payments) => Arc::new(PaymentStore::new(
payments,
PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE.to_string(),
PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE.to_string(),
Arc::clone(&kv_store),
Arc::clone(&logger),
)),
Err(_) => {
return Err(BuildError::ReadFailed);
},
Expand Down
287 changes: 287 additions & 0 deletions src/data_store.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,287 @@
// This file is Copyright its original authors, visible in version control history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
// accordance with one or both of these licenses.

use crate::logger::{log_error, LdkLogger};
use crate::types::DynStore;
use crate::Error;

use lightning::util::ser::{Readable, Writeable};

use std::collections::hash_map;
use std::collections::HashMap;
use std::ops::Deref;
use std::sync::{Arc, Mutex};

pub(crate) trait StorableObject: Clone + Readable + Writeable {
type Id: StorableObjectId;
type Update: StorableObjectUpdate<Self>;

fn id(&self) -> Self::Id;
fn update(&mut self, update: &Self::Update) -> bool;
fn to_update(&self) -> Self::Update;
}

pub(crate) trait StorableObjectId: std::hash::Hash + PartialEq + Eq {
fn encode_to_hex_str(&self) -> String;
}

pub(crate) trait StorableObjectUpdate<SO: StorableObject> {
fn id(&self) -> SO::Id;
}

#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub(crate) enum DataStoreUpdateResult {
Updated,
Unchanged,
NotFound,
}

pub(crate) struct DataStore<SO: StorableObject, L: Deref>
where
L::Target: LdkLogger,
{
objects: Mutex<HashMap<SO::Id, SO>>,
primary_namespace: String,
secondary_namespace: String,
kv_store: Arc<DynStore>,
logger: L,
}

impl<SO: StorableObject, L: Deref> DataStore<SO, L>
where
L::Target: LdkLogger,
{
pub(crate) fn new(
objects: Vec<SO>, primary_namespace: String, secondary_namespace: String,
kv_store: Arc<DynStore>, logger: L,
) -> Self {
let objects =
Mutex::new(HashMap::from_iter(objects.into_iter().map(|obj| (obj.id(), obj))));
Self { objects, primary_namespace, secondary_namespace, kv_store, logger }
}

pub(crate) fn insert(&self, object: SO) -> Result<bool, Error> {
let mut locked_objects = self.objects.lock().unwrap();

self.persist(&object)?;
let updated = locked_objects.insert(object.id(), object).is_some();
Comment on lines +70 to +71

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the order matter here? The opposite order is used in insert_or_update, so there we could have the object in memory but fail persisting.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, this one used to be the other way around, but I changed it here (actually should be the only behavioral diff I snuck in, IIRC), exactly because it would be preferable to not update the in-memory version if persistence failed. However, for insert_or_update/update we won't know whether the update is necessary at all until StorableObject::update returns, which is why we unfortunately can't first persist.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For insert_or_update/update, it seems we log an error but continue. I suppose this predates the PR, but I wonder if we should do something else like have a queue of ids that still need persistence. Though if we eventually crash that information would be loss. Maybe this is more of a storage implementation concern.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, we could do that eventually, although it probably would somehow need to fit into a "halt everything on (remote) persistence failure, and resume/restart once we reestablish connectivity" scheme.

Ok(updated)
}

pub(crate) fn insert_or_update(&self, object: SO) -> Result<bool, Error> {
let mut locked_objects = self.objects.lock().unwrap();

let updated;
match locked_objects.entry(object.id()) {
hash_map::Entry::Occupied(mut e) => {
let update = object.to_update();
updated = e.get_mut().update(&update);
if updated {
self.persist(&e.get())?;
}
},
hash_map::Entry::Vacant(e) => {
e.insert(object.clone());
self.persist(&object)?;
updated = true;
},
}

Ok(updated)
}

pub(crate) fn remove(&self, id: &SO::Id) -> Result<(), Error> {
let removed = self.objects.lock().unwrap().remove(id).is_some();
if removed {
let store_key = id.encode_to_hex_str();
self.kv_store
.remove(&self.primary_namespace, &self.secondary_namespace, &store_key, false)
.map_err(|e| {
log_error!(
self.logger,
"Removing object data for key {}/{}/{} failed due to: {}",
&self.primary_namespace,
&self.secondary_namespace,
store_key,
e
);
Error::PersistenceFailed
})?;
}
Ok(())
}

pub(crate) fn get(&self, id: &SO::Id) -> Option<SO> {
self.objects.lock().unwrap().get(id).cloned()
}

pub(crate) fn update(&self, update: &SO::Update) -> Result<DataStoreUpdateResult, Error> {
let mut locked_objects = self.objects.lock().unwrap();

if let Some(object) = locked_objects.get_mut(&update.id()) {
let updated = object.update(update);
if updated {
self.persist(&object)?;
Ok(DataStoreUpdateResult::Updated)
} else {
Ok(DataStoreUpdateResult::Unchanged)
}
} else {
Ok(DataStoreUpdateResult::NotFound)
}
}

pub(crate) fn list_filter<F: FnMut(&&SO) -> bool>(&self, f: F) -> Vec<SO> {
self.objects.lock().unwrap().values().filter(f).cloned().collect::<Vec<SO>>()
}

fn persist(&self, object: &SO) -> Result<(), Error> {
let store_key = object.id().encode_to_hex_str();
let data = object.encode();
self.kv_store
.write(&self.primary_namespace, &self.secondary_namespace, &store_key, &data)
.map_err(|e| {
log_error!(
self.logger,
"Write for key {}/{}/{} failed due to: {}",
&self.primary_namespace,
&self.secondary_namespace,
store_key,
e
);
Error::PersistenceFailed
})?;
Ok(())
}
}

#[cfg(test)]
mod tests {
use lightning::impl_writeable_tlv_based;
use lightning::util::test_utils::{TestLogger, TestStore};

use crate::hex_utils;

use super::*;

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct TestObjectId {
id: [u8; 4],
}

impl StorableObjectId for TestObjectId {
fn encode_to_hex_str(&self) -> String {
hex_utils::to_string(&self.id)
}
}
impl_writeable_tlv_based!(TestObjectId, { (0, id, required) });

struct TestObjectUpdate {
id: TestObjectId,
data: [u8; 3],
}
impl StorableObjectUpdate<TestObject> for TestObjectUpdate {
fn id(&self) -> TestObjectId {
self.id
}
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct TestObject {
id: TestObjectId,
data: [u8; 3],
}

impl StorableObject for TestObject {
type Id = TestObjectId;
type Update = TestObjectUpdate;

fn id(&self) -> Self::Id {
self.id
}

fn update(&mut self, update: &Self::Update) -> bool {
if self.data != update.data {
self.data = update.data;
true
} else {
false
}
}

fn to_update(&self) -> Self::Update {
Self::Update { id: self.id, data: self.data }
}
}

impl_writeable_tlv_based!(TestObject, {
(0, id, required),
(2, data, required),
});

#[test]
fn data_is_persisted() {
let store: Arc<DynStore> = Arc::new(TestStore::new(false));
let logger = Arc::new(TestLogger::new());
let primary_namespace = "datastore_test_primary".to_string();
let secondary_namespace = "datastore_test_secondary".to_string();
let data_store: DataStore<TestObject, Arc<TestLogger>> = DataStore::new(
Vec::new(),
primary_namespace.clone(),
secondary_namespace.clone(),
Arc::clone(&store),
logger,
);

let id = TestObjectId { id: [42u8; 4] };
assert!(data_store.get(&id).is_none());

let store_key = id.encode_to_hex_str();

// Check we start empty.
assert!(store.read(&primary_namespace, &secondary_namespace, &store_key).is_err());

// Check we successfully store an object and return `false`
let object = TestObject { id, data: [23u8; 3] };
assert_eq!(Ok(false), data_store.insert(object.clone()));
assert_eq!(Some(object), data_store.get(&id));
assert!(store.read(&primary_namespace, &secondary_namespace, &store_key).is_ok());

// Test re-insertion returns `true`
let mut override_object = object.clone();
override_object.data = [24u8; 3];
assert_eq!(Ok(true), data_store.insert(override_object));
assert_eq!(Some(override_object), data_store.get(&id));

// Check update returns `Updated`
let update = TestObjectUpdate { id, data: [25u8; 3] };
assert_eq!(Ok(DataStoreUpdateResult::Updated), data_store.update(&update));
assert_eq!(data_store.get(&id).unwrap().data, [25u8; 3]);

// Check no-op update yields `Unchanged`
let update = TestObjectUpdate { id, data: [25u8; 3] };
assert_eq!(Ok(DataStoreUpdateResult::Unchanged), data_store.update(&update));

// Check bogus update yields `NotFound`
let bogus_id = TestObjectId { id: [84u8; 4] };
let update = TestObjectUpdate { id: bogus_id, data: [12u8; 3] };
assert_eq!(Ok(DataStoreUpdateResult::NotFound), data_store.update(&update));

// Check `insert_or_update` inserts unknown objects
let iou_id = TestObjectId { id: [55u8; 4] };
let iou_object = TestObject { id: iou_id, data: [34u8; 3] };
assert_eq!(Ok(true), data_store.insert_or_update(iou_object.clone()));

// Check `insert_or_update` doesn't update the same object
assert_eq!(Ok(false), data_store.insert_or_update(iou_object.clone()));

// Check `insert_or_update` updates if object changed
let mut new_iou_object = iou_object;
new_iou_object.data[0] += 1;
assert_eq!(Ok(true), data_store.insert_or_update(new_iou_object));
}
}
13 changes: 6 additions & 7 deletions src/event.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,7 +5,7 @@
// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
// accordance with one or both of these licenses.

use crate::types::{CustomTlvRecord, DynStore, Sweeper, Wallet};
use crate::types::{CustomTlvRecord, DynStore, PaymentStore, Sweeper, Wallet};

use crate::{
hex_utils, BumpTransactionEventHandler, ChannelManager, Error, Graph, PeerInfo, PeerStore,
Expand All@@ -14,13 +14,13 @@ use crate::{

use crate::config::{may_announce_channel, Config};
use crate::connection::ConnectionManager;
use crate::data_store::DataStoreUpdateResult;
use crate::fee_estimator::ConfirmationTarget;
use crate::liquidity::LiquiditySource;
use crate::logger::Logger;

use crate::payment::store::{
PaymentDetails, PaymentDetailsUpdate, PaymentDirection, PaymentKind, PaymentStatus,
PaymentStore, PaymentStoreUpdateResult,
};

use crate::io::{
Expand DownExpand Up@@ -449,7 +449,7 @@ where
output_sweeper: Arc<Sweeper>,
network_graph: Arc<Graph>,
liquidity_source: Option<Arc<LiquiditySource<Arc<Logger>>>>,
payment_store: Arc<PaymentStore<L>>,
payment_store: Arc<PaymentStore>,
peer_store: Arc<PeerStore<L>>,
runtime: Arc<RwLock<Option<Arc<tokio::runtime::Runtime>>>>,
logger: L,
Expand All@@ -466,7 +466,7 @@ where
channel_manager: Arc<ChannelManager>, connection_manager: Arc<ConnectionManager<L>>,
output_sweeper: Arc<Sweeper>, network_graph: Arc<Graph>,
liquidity_source: Option<Arc<LiquiditySource<Arc<Logger>>>>,
payment_store: Arc<PaymentStore<L>>, peer_store: Arc<PeerStore<L>>,
payment_store: Arc<PaymentStore>, peer_store: Arc<PeerStore<L>>,
runtime: Arc<RwLock<Option<Arc<tokio::runtime::Runtime>>>>, logger: L, config: Arc<Config>,
) -> Self {
Self {
Expand DownExpand Up@@ -906,12 +906,11 @@ where
};

match self.payment_store.update(&update) {
Ok(PaymentStoreUpdateResult::Updated)
| Ok(PaymentStoreUpdateResult::Unchanged) => (
Ok(DataStoreUpdateResult::Updated) | Ok(DataStoreUpdateResult::Unchanged) => (
// No need to do anything if the idempotent update was applied, which might
// be the result of a replayed event.
),
Ok(PaymentStoreUpdateResult::NotFound) => {
Ok(DataStoreUpdateResult::NotFound) => {
log_error!(
self.logger,
"Claimed payment with ID {} couldn't be found in store",
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
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
18 changes: 12 additions & 6 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,21 +18,23 @@ use crate::gossip::GossipSource;
use crate::io::sqlite_store::SqliteStore;
use crate::io::utils::{read_node_metrics, write_node_metrics};
use crate::io::vss_store::VssStore;
use crate::io::{
self, PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE, PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE,
};
use crate::liquidity::{
LSPS1ClientConfig, LSPS2ClientConfig, LSPS2ServiceConfig, LiquiditySourceBuilder,
};
use crate::logger::{log_error, log_info, LdkLogger, LogLevel, LogWriter, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::store::PaymentStore;
use crate::peer_store::PeerStore;
use crate::tx_broadcaster::TransactionBroadcaster;
use crate::types::{
ChainMonitor, ChannelManager, DynStore, GossipSync, Graph, KeysManager, MessageRouter,
OnionMessenger, PeerManager,
OnionMessenger, PaymentStore, PeerManager,
};
use crate::wallet::persist::KVStoreWalletPersister;
use crate::wallet::Wallet;
use crate::{io, Node, NodeMetrics};
use crate::{Node, NodeMetrics};

use lightning::chain::{chainmonitor, BestBlock, Watch};
use lightning::io::Cursor;
Expand DownExpand Up@@ -1015,9 +1017,13 @@ fn build_with_store_internal(
let fee_estimator = Arc::new(OnchainFeeEstimator::new());

let payment_store = match io::utils::read_payments(Arc::clone(&kv_store), Arc::clone(&logger)) {
Ok(payments) => {
Arc::new(PaymentStore::new(payments, Arc::clone(&kv_store), Arc::clone(&logger)))
},
Ok(payments) => Arc::new(PaymentStore::new(
payments,
PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE.to_string(),
PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE.to_string(),
Arc::clone(&kv_store),
Arc::clone(&logger),
)),
Err(_) => {
return Err(BuildError::ReadFailed);
},
Expand Down
287 changes: 287 additions & 0 deletions src/data_store.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,287 @@
// This file is Copyright its original authors, visible in version control history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
// accordance with one or both of these licenses.

use crate::logger::{log_error, LdkLogger};
use crate::types::DynStore;
use crate::Error;

use lightning::util::ser::{Readable, Writeable};

use std::collections::hash_map;
use std::collections::HashMap;
use std::ops::Deref;
use std::sync::{Arc, Mutex};

pub(crate) trait StorableObject: Clone + Readable + Writeable {
type Id: StorableObjectId;
type Update: StorableObjectUpdate<Self>;

fn id(&self) -> Self::Id;
fn update(&mut self, update: &Self::Update) -> bool;
fn to_update(&self) -> Self::Update;
}

pub(crate) trait StorableObjectId: std::hash::Hash + PartialEq + Eq {
fn encode_to_hex_str(&self) -> String;
}

pub(crate) trait StorableObjectUpdate<SO: StorableObject> {
fn id(&self) -> SO::Id;
}

#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub(crate) enum DataStoreUpdateResult {
Updated,
Unchanged,
NotFound,
}

pub(crate) struct DataStore<SO: StorableObject, L: Deref>
where
L::Target: LdkLogger,
{
objects: Mutex<HashMap<SO::Id, SO>>,
primary_namespace: String,
secondary_namespace: String,
kv_store: Arc<DynStore>,
logger: L,
}

impl<SO: StorableObject, L: Deref> DataStore<SO, L>
where
L::Target: LdkLogger,
{
pub(crate) fn new(
objects: Vec<SO>, primary_namespace: String, secondary_namespace: String,
kv_store: Arc<DynStore>, logger: L,
) -> Self {
let objects =
Mutex::new(HashMap::from_iter(objects.into_iter().map(|obj| (obj.id(), obj))));
Self { objects, primary_namespace, secondary_namespace, kv_store, logger }
}

pub(crate) fn insert(&self, object: SO) -> Result<bool, Error> {
let mut locked_objects = self.objects.lock().unwrap();

self.persist(&object)?;
let updated = locked_objects.insert(object.id(), object).is_some();
Comment on lines +70 to +71

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the order matter here? The opposite order is used in insert_or_update, so there we could have the object in memory but fail persisting.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, this one used to be the other way around, but I changed it here (actually should be the only behavioral diff I snuck in, IIRC), exactly because it would be preferable to not update the in-memory version if persistence failed. However, for insert_or_update/update we won't know whether the update is necessary at all until StorableObject::update returns, which is why we unfortunately can't first persist.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For insert_or_update/update, it seems we log an error but continue. I suppose this predates the PR, but I wonder if we should do something else like have a queue of ids that still need persistence. Though if we eventually crash that information would be loss. Maybe this is more of a storage implementation concern.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, we could do that eventually, although it probably would somehow need to fit into a "halt everything on (remote) persistence failure, and resume/restart once we reestablish connectivity" scheme.

Ok(updated)
}

pub(crate) fn insert_or_update(&self, object: SO) -> Result<bool, Error> {
let mut locked_objects = self.objects.lock().unwrap();

let updated;
match locked_objects.entry(object.id()) {
hash_map::Entry::Occupied(mut e) => {
let update = object.to_update();
updated = e.get_mut().update(&update);
if updated {
self.persist(&e.get())?;
}
},
hash_map::Entry::Vacant(e) => {
e.insert(object.clone());
self.persist(&object)?;
updated = true;
},
}

Ok(updated)
}

pub(crate) fn remove(&self, id: &SO::Id) -> Result<(), Error> {
let removed = self.objects.lock().unwrap().remove(id).is_some();
if removed {
let store_key = id.encode_to_hex_str();
self.kv_store
.remove(&self.primary_namespace, &self.secondary_namespace, &store_key, false)
.map_err(|e| {
log_error!(
self.logger,
"Removing object data for key {}/{}/{} failed due to: {}",
&self.primary_namespace,
&self.secondary_namespace,
store_key,
e
);
Error::PersistenceFailed
})?;
}
Ok(())
}

pub(crate) fn get(&self, id: &SO::Id) -> Option<SO> {
self.objects.lock().unwrap().get(id).cloned()
}

pub(crate) fn update(&self, update: &SO::Update) -> Result<DataStoreUpdateResult, Error> {
let mut locked_objects = self.objects.lock().unwrap();

if let Some(object) = locked_objects.get_mut(&update.id()) {
let updated = object.update(update);
if updated {
self.persist(&object)?;
Ok(DataStoreUpdateResult::Updated)
} else {
Ok(DataStoreUpdateResult::Unchanged)
}
} else {
Ok(DataStoreUpdateResult::NotFound)
}
}

pub(crate) fn list_filter<F: FnMut(&&SO) -> bool>(&self, f: F) -> Vec<SO> {
self.objects.lock().unwrap().values().filter(f).cloned().collect::<Vec<SO>>()
}

fn persist(&self, object: &SO) -> Result<(), Error> {
let store_key = object.id().encode_to_hex_str();
let data = object.encode();
self.kv_store
.write(&self.primary_namespace, &self.secondary_namespace, &store_key, &data)
.map_err(|e| {
log_error!(
self.logger,
"Write for key {}/{}/{} failed due to: {}",
&self.primary_namespace,
&self.secondary_namespace,
store_key,
e
);
Error::PersistenceFailed
})?;
Ok(())
}
}

#[cfg(test)]
mod tests {
use lightning::impl_writeable_tlv_based;
use lightning::util::test_utils::{TestLogger, TestStore};

use crate::hex_utils;

use super::*;

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct TestObjectId {
id: [u8; 4],
}

impl StorableObjectId for TestObjectId {
fn encode_to_hex_str(&self) -> String {
hex_utils::to_string(&self.id)
}
}
impl_writeable_tlv_based!(TestObjectId, { (0, id, required) });

struct TestObjectUpdate {
id: TestObjectId,
data: [u8; 3],
}
impl StorableObjectUpdate<TestObject> for TestObjectUpdate {
fn id(&self) -> TestObjectId {
self.id
}
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct TestObject {
id: TestObjectId,
data: [u8; 3],
}

impl StorableObject for TestObject {
type Id = TestObjectId;
type Update = TestObjectUpdate;

fn id(&self) -> Self::Id {
self.id
}

fn update(&mut self, update: &Self::Update) -> bool {
if self.data != update.data {
self.data = update.data;
true
} else {
false
}
}

fn to_update(&self) -> Self::Update {
Self::Update { id: self.id, data: self.data }
}
}

impl_writeable_tlv_based!(TestObject, {
(0, id, required),
(2, data, required),
});

#[test]
fn data_is_persisted() {
let store: Arc<DynStore> = Arc::new(TestStore::new(false));
let logger = Arc::new(TestLogger::new());
let primary_namespace = "datastore_test_primary".to_string();
let secondary_namespace = "datastore_test_secondary".to_string();
let data_store: DataStore<TestObject, Arc<TestLogger>> = DataStore::new(
Vec::new(),
primary_namespace.clone(),
secondary_namespace.clone(),
Arc::clone(&store),
logger,
);

let id = TestObjectId { id: [42u8; 4] };
assert!(data_store.get(&id).is_none());

let store_key = id.encode_to_hex_str();

// Check we start empty.
assert!(store.read(&primary_namespace, &secondary_namespace, &store_key).is_err());

// Check we successfully store an object and return `false`
let object = TestObject { id, data: [23u8; 3] };
assert_eq!(Ok(false), data_store.insert(object.clone()));
assert_eq!(Some(object), data_store.get(&id));
assert!(store.read(&primary_namespace, &secondary_namespace, &store_key).is_ok());

// Test re-insertion returns `true`
let mut override_object = object.clone();
override_object.data = [24u8; 3];
assert_eq!(Ok(true), data_store.insert(override_object));
assert_eq!(Some(override_object), data_store.get(&id));

// Check update returns `Updated`
let update = TestObjectUpdate { id, data: [25u8; 3] };
assert_eq!(Ok(DataStoreUpdateResult::Updated), data_store.update(&update));
assert_eq!(data_store.get(&id).unwrap().data, [25u8; 3]);

// Check no-op update yields `Unchanged`
let update = TestObjectUpdate { id, data: [25u8; 3] };
assert_eq!(Ok(DataStoreUpdateResult::Unchanged), data_store.update(&update));

// Check bogus update yields `NotFound`
let bogus_id = TestObjectId { id: [84u8; 4] };
let update = TestObjectUpdate { id: bogus_id, data: [12u8; 3] };
assert_eq!(Ok(DataStoreUpdateResult::NotFound), data_store.update(&update));

// Check `insert_or_update` inserts unknown objects
let iou_id = TestObjectId { id: [55u8; 4] };
let iou_object = TestObject { id: iou_id, data: [34u8; 3] };
assert_eq!(Ok(true), data_store.insert_or_update(iou_object.clone()));

// Check `insert_or_update` doesn't update the same object
assert_eq!(Ok(false), data_store.insert_or_update(iou_object.clone()));

// Check `insert_or_update` updates if object changed
let mut new_iou_object = iou_object;
new_iou_object.data[0] += 1;
assert_eq!(Ok(true), data_store.insert_or_update(new_iou_object));
}
}
13 changes: 6 additions & 7 deletions src/event.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,7 +5,7 @@
// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
// accordance with one or both of these licenses.

use crate::types::{CustomTlvRecord, DynStore, Sweeper, Wallet};
use crate::types::{CustomTlvRecord, DynStore, PaymentStore, Sweeper, Wallet};

use crate::{
hex_utils, BumpTransactionEventHandler, ChannelManager, Error, Graph, PeerInfo, PeerStore,
Expand All@@ -14,13 +14,13 @@ use crate::{

use crate::config::{may_announce_channel, Config};
use crate::connection::ConnectionManager;
use crate::data_store::DataStoreUpdateResult;
use crate::fee_estimator::ConfirmationTarget;
use crate::liquidity::LiquiditySource;
use crate::logger::Logger;

use crate::payment::store::{
PaymentDetails, PaymentDetailsUpdate, PaymentDirection, PaymentKind, PaymentStatus,
PaymentStore, PaymentStoreUpdateResult,
};

use crate::io::{
Expand DownExpand Up@@ -449,7 +449,7 @@ where
output_sweeper: Arc<Sweeper>,
network_graph: Arc<Graph>,
liquidity_source: Option<Arc<LiquiditySource<Arc<Logger>>>>,
payment_store: Arc<PaymentStore<L>>,
payment_store: Arc<PaymentStore>,
peer_store: Arc<PeerStore<L>>,
runtime: Arc<RwLock<Option<Arc<tokio::runtime::Runtime>>>>,
logger: L,
Expand All@@ -466,7 +466,7 @@ where
channel_manager: Arc<ChannelManager>, connection_manager: Arc<ConnectionManager<L>>,
output_sweeper: Arc<Sweeper>, network_graph: Arc<Graph>,
liquidity_source: Option<Arc<LiquiditySource<Arc<Logger>>>>,
payment_store: Arc<PaymentStore<L>>, peer_store: Arc<PeerStore<L>>,
payment_store: Arc<PaymentStore>, peer_store: Arc<PeerStore<L>>,
runtime: Arc<RwLock<Option<Arc<tokio::runtime::Runtime>>>>, logger: L, config: Arc<Config>,
) -> Self {
Self {
Expand DownExpand Up@@ -906,12 +906,11 @@ where
};

match self.payment_store.update(&update) {
Ok(PaymentStoreUpdateResult::Updated)
| Ok(PaymentStoreUpdateResult::Unchanged) => (
Ok(DataStoreUpdateResult::Updated) | Ok(DataStoreUpdateResult::Unchanged) => (
// No need to do anything if the idempotent update was applied, which might
// be the result of a replayed event.
),
Ok(PaymentStoreUpdateResult::NotFound) => {
Ok(DataStoreUpdateResult::NotFound) => {
log_error!(
self.logger,
"Claimed payment with ID {} couldn't be found in store",
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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
18 changes: 12 additions & 6 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,21 +18,23 @@ use crate::gossip::GossipSource;
use crate::io::sqlite_store::SqliteStore;
use crate::io::utils::{read_node_metrics, write_node_metrics};
use crate::io::vss_store::VssStore;
use crate::io::{
self, PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE, PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE,
};
use crate::liquidity::{
LSPS1ClientConfig, LSPS2ClientConfig, LSPS2ServiceConfig, LiquiditySourceBuilder,
};
use crate::logger::{log_error, log_info, LdkLogger, LogLevel, LogWriter, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::store::PaymentStore;
use crate::peer_store::PeerStore;
use crate::tx_broadcaster::TransactionBroadcaster;
use crate::types::{
ChainMonitor, ChannelManager, DynStore, GossipSync, Graph, KeysManager, MessageRouter,
OnionMessenger, PeerManager,
OnionMessenger, PaymentStore, PeerManager,
};
use crate::wallet::persist::KVStoreWalletPersister;
use crate::wallet::Wallet;
use crate::{io, Node, NodeMetrics};
use crate::{Node, NodeMetrics};

use lightning::chain::{chainmonitor, BestBlock, Watch};
use lightning::io::Cursor;
Expand DownExpand Up@@ -1015,9 +1017,13 @@ fn build_with_store_internal(
let fee_estimator = Arc::new(OnchainFeeEstimator::new());

let payment_store = match io::utils::read_payments(Arc::clone(&kv_store), Arc::clone(&logger)) {
Ok(payments) => {
Arc::new(PaymentStore::new(payments, Arc::clone(&kv_store), Arc::clone(&logger)))
},
Ok(payments) => Arc::new(PaymentStore::new(
payments,
PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE.to_string(),
PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE.to_string(),
Arc::clone(&kv_store),
Arc::clone(&logger),
)),
Err(_) => {
return Err(BuildError::ReadFailed);
},
Expand Down
287 changes: 287 additions & 0 deletions src/data_store.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,287 @@
// This file is Copyright its original authors, visible in version control history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
// accordance with one or both of these licenses.

use crate::logger::{log_error, LdkLogger};
use crate::types::DynStore;
use crate::Error;

use lightning::util::ser::{Readable, Writeable};

use std::collections::hash_map;
use std::collections::HashMap;
use std::ops::Deref;
use std::sync::{Arc, Mutex};

pub(crate) trait StorableObject: Clone + Readable + Writeable {
type Id: StorableObjectId;
type Update: StorableObjectUpdate<Self>;

fn id(&self) -> Self::Id;
fn update(&mut self, update: &Self::Update) -> bool;
fn to_update(&self) -> Self::Update;
}

pub(crate) trait StorableObjectId: std::hash::Hash + PartialEq + Eq {
fn encode_to_hex_str(&self) -> String;
}

pub(crate) trait StorableObjectUpdate<SO: StorableObject> {
fn id(&self) -> SO::Id;
}

#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub(crate) enum DataStoreUpdateResult {
Updated,
Unchanged,
NotFound,
}

pub(crate) struct DataStore<SO: StorableObject, L: Deref>
where
L::Target: LdkLogger,
{
objects: Mutex<HashMap<SO::Id, SO>>,
primary_namespace: String,
secondary_namespace: String,
kv_store: Arc<DynStore>,
logger: L,
}

impl<SO: StorableObject, L: Deref> DataStore<SO, L>
where
L::Target: LdkLogger,
{
pub(crate) fn new(
objects: Vec<SO>, primary_namespace: String, secondary_namespace: String,
kv_store: Arc<DynStore>, logger: L,
) -> Self {
let objects =
Mutex::new(HashMap::from_iter(objects.into_iter().map(|obj| (obj.id(), obj))));
Self { objects, primary_namespace, secondary_namespace, kv_store, logger }
}

pub(crate) fn insert(&self, object: SO) -> Result<bool, Error> {
let mut locked_objects = self.objects.lock().unwrap();

self.persist(&object)?;
let updated = locked_objects.insert(object.id(), object).is_some();
Comment on lines +70 to +71

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the order matter here? The opposite order is used in insert_or_update, so there we could have the object in memory but fail persisting.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, this one used to be the other way around, but I changed it here (actually should be the only behavioral diff I snuck in, IIRC), exactly because it would be preferable to not update the in-memory version if persistence failed. However, for insert_or_update/update we won't know whether the update is necessary at all until StorableObject::update returns, which is why we unfortunately can't first persist.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For insert_or_update/update, it seems we log an error but continue. I suppose this predates the PR, but I wonder if we should do something else like have a queue of ids that still need persistence. Though if we eventually crash that information would be loss. Maybe this is more of a storage implementation concern.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, we could do that eventually, although it probably would somehow need to fit into a "halt everything on (remote) persistence failure, and resume/restart once we reestablish connectivity" scheme.

Ok(updated)
}

pub(crate) fn insert_or_update(&self, object: SO) -> Result<bool, Error> {
let mut locked_objects = self.objects.lock().unwrap();

let updated;
match locked_objects.entry(object.id()) {
hash_map::Entry::Occupied(mut e) => {
let update = object.to_update();
updated = e.get_mut().update(&update);
if updated {
self.persist(&e.get())?;
}
},
hash_map::Entry::Vacant(e) => {
e.insert(object.clone());
self.persist(&object)?;
updated = true;
},
}

Ok(updated)
}

pub(crate) fn remove(&self, id: &SO::Id) -> Result<(), Error> {
let removed = self.objects.lock().unwrap().remove(id).is_some();
if removed {
let store_key = id.encode_to_hex_str();
self.kv_store
.remove(&self.primary_namespace, &self.secondary_namespace, &store_key, false)
.map_err(|e| {
log_error!(
self.logger,
"Removing object data for key {}/{}/{} failed due to: {}",
&self.primary_namespace,
&self.secondary_namespace,
store_key,
e
);
Error::PersistenceFailed
})?;
}
Ok(())
}

pub(crate) fn get(&self, id: &SO::Id) -> Option<SO> {
self.objects.lock().unwrap().get(id).cloned()
}

pub(crate) fn update(&self, update: &SO::Update) -> Result<DataStoreUpdateResult, Error> {
let mut locked_objects = self.objects.lock().unwrap();

if let Some(object) = locked_objects.get_mut(&update.id()) {
let updated = object.update(update);
if updated {
self.persist(&object)?;
Ok(DataStoreUpdateResult::Updated)
} else {
Ok(DataStoreUpdateResult::Unchanged)
}
} else {
Ok(DataStoreUpdateResult::NotFound)
}
}

pub(crate) fn list_filter<F: FnMut(&&SO) -> bool>(&self, f: F) -> Vec<SO> {
self.objects.lock().unwrap().values().filter(f).cloned().collect::<Vec<SO>>()
}

fn persist(&self, object: &SO) -> Result<(), Error> {
let store_key = object.id().encode_to_hex_str();
let data = object.encode();
self.kv_store
.write(&self.primary_namespace, &self.secondary_namespace, &store_key, &data)
.map_err(|e| {
log_error!(
self.logger,
"Write for key {}/{}/{} failed due to: {}",
&self.primary_namespace,
&self.secondary_namespace,
store_key,
e
);
Error::PersistenceFailed
})?;
Ok(())
}
}

#[cfg(test)]
mod tests {
use lightning::impl_writeable_tlv_based;
use lightning::util::test_utils::{TestLogger, TestStore};

use crate::hex_utils;

use super::*;

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct TestObjectId {
id: [u8; 4],
}

impl StorableObjectId for TestObjectId {
fn encode_to_hex_str(&self) -> String {
hex_utils::to_string(&self.id)
}
}
impl_writeable_tlv_based!(TestObjectId, { (0, id, required) });

struct TestObjectUpdate {
id: TestObjectId,
data: [u8; 3],
}
impl StorableObjectUpdate<TestObject> for TestObjectUpdate {
fn id(&self) -> TestObjectId {
self.id
}
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct TestObject {
id: TestObjectId,
data: [u8; 3],
}

impl StorableObject for TestObject {
type Id = TestObjectId;
type Update = TestObjectUpdate;

fn id(&self) -> Self::Id {
self.id
}

fn update(&mut self, update: &Self::Update) -> bool {
if self.data != update.data {
self.data = update.data;
true
} else {
false
}
}

fn to_update(&self) -> Self::Update {
Self::Update { id: self.id, data: self.data }
}
}

impl_writeable_tlv_based!(TestObject, {
(0, id, required),
(2, data, required),
});

#[test]
fn data_is_persisted() {
let store: Arc<DynStore> = Arc::new(TestStore::new(false));
let logger = Arc::new(TestLogger::new());
let primary_namespace = "datastore_test_primary".to_string();
let secondary_namespace = "datastore_test_secondary".to_string();
let data_store: DataStore<TestObject, Arc<TestLogger>> = DataStore::new(
Vec::new(),
primary_namespace.clone(),
secondary_namespace.clone(),
Arc::clone(&store),
logger,
);

let id = TestObjectId { id: [42u8; 4] };
assert!(data_store.get(&id).is_none());

let store_key = id.encode_to_hex_str();

// Check we start empty.
assert!(store.read(&primary_namespace, &secondary_namespace, &store_key).is_err());

// Check we successfully store an object and return `false`
let object = TestObject { id, data: [23u8; 3] };
assert_eq!(Ok(false), data_store.insert(object.clone()));
assert_eq!(Some(object), data_store.get(&id));
assert!(store.read(&primary_namespace, &secondary_namespace, &store_key).is_ok());

// Test re-insertion returns `true`
let mut override_object = object.clone();
override_object.data = [24u8; 3];
assert_eq!(Ok(true), data_store.insert(override_object));
assert_eq!(Some(override_object), data_store.get(&id));

// Check update returns `Updated`
let update = TestObjectUpdate { id, data: [25u8; 3] };
assert_eq!(Ok(DataStoreUpdateResult::Updated), data_store.update(&update));
assert_eq!(data_store.get(&id).unwrap().data, [25u8; 3]);

// Check no-op update yields `Unchanged`
let update = TestObjectUpdate { id, data: [25u8; 3] };
assert_eq!(Ok(DataStoreUpdateResult::Unchanged), data_store.update(&update));

// Check bogus update yields `NotFound`
let bogus_id = TestObjectId { id: [84u8; 4] };
let update = TestObjectUpdate { id: bogus_id, data: [12u8; 3] };
assert_eq!(Ok(DataStoreUpdateResult::NotFound), data_store.update(&update));

// Check `insert_or_update` inserts unknown objects
let iou_id = TestObjectId { id: [55u8; 4] };
let iou_object = TestObject { id: iou_id, data: [34u8; 3] };
assert_eq!(Ok(true), data_store.insert_or_update(iou_object.clone()));

// Check `insert_or_update` doesn't update the same object
assert_eq!(Ok(false), data_store.insert_or_update(iou_object.clone()));

// Check `insert_or_update` updates if object changed
let mut new_iou_object = iou_object;
new_iou_object.data[0] += 1;
assert_eq!(Ok(true), data_store.insert_or_update(new_iou_object));
}
}
13 changes: 6 additions & 7 deletions src/event.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,7 +5,7 @@
// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
// accordance with one or both of these licenses.

use crate::types::{CustomTlvRecord, DynStore, Sweeper, Wallet};
use crate::types::{CustomTlvRecord, DynStore, PaymentStore, Sweeper, Wallet};

use crate::{
hex_utils, BumpTransactionEventHandler, ChannelManager, Error, Graph, PeerInfo, PeerStore,
Expand All@@ -14,13 +14,13 @@ use crate::{

use crate::config::{may_announce_channel, Config};
use crate::connection::ConnectionManager;
use crate::data_store::DataStoreUpdateResult;
use crate::fee_estimator::ConfirmationTarget;
use crate::liquidity::LiquiditySource;
use crate::logger::Logger;

use crate::payment::store::{
PaymentDetails, PaymentDetailsUpdate, PaymentDirection, PaymentKind, PaymentStatus,
PaymentStore, PaymentStoreUpdateResult,
};

use crate::io::{
Expand DownExpand Up@@ -449,7 +449,7 @@ where
output_sweeper: Arc<Sweeper>,
network_graph: Arc<Graph>,
liquidity_source: Option<Arc<LiquiditySource<Arc<Logger>>>>,
payment_store: Arc<PaymentStore<L>>,
payment_store: Arc<PaymentStore>,
peer_store: Arc<PeerStore<L>>,
runtime: Arc<RwLock<Option<Arc<tokio::runtime::Runtime>>>>,
logger: L,
Expand All@@ -466,7 +466,7 @@ where
channel_manager: Arc<ChannelManager>, connection_manager: Arc<ConnectionManager<L>>,
output_sweeper: Arc<Sweeper>, network_graph: Arc<Graph>,
liquidity_source: Option<Arc<LiquiditySource<Arc<Logger>>>>,
payment_store: Arc<PaymentStore<L>>, peer_store: Arc<PeerStore<L>>,
payment_store: Arc<PaymentStore>, peer_store: Arc<PeerStore<L>>,
runtime: Arc<RwLock<Option<Arc<tokio::runtime::Runtime>>>>, logger: L, config: Arc<Config>,
) -> Self {
Self {
Expand DownExpand Up@@ -906,12 +906,11 @@ where
};

match self.payment_store.update(&update) {
Ok(PaymentStoreUpdateResult::Updated)
| Ok(PaymentStoreUpdateResult::Unchanged) => (
Ok(DataStoreUpdateResult::Updated) | Ok(DataStoreUpdateResult::Unchanged) => (
// No need to do anything if the idempotent update was applied, which might
// be the result of a replayed event.
),
Ok(PaymentStoreUpdateResult::NotFound) => {
Ok(DataStoreUpdateResult::NotFound) => {
log_error!(
self.logger,
"Claimed payment with ID {} couldn't be found in store",
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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
18 changes: 12 additions & 6 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,21 +18,23 @@ use crate::gossip::GossipSource;
use crate::io::sqlite_store::SqliteStore;
use crate::io::utils::{read_node_metrics, write_node_metrics};
use crate::io::vss_store::VssStore;
use crate::io::{
self, PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE, PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE,
};
use crate::liquidity::{
LSPS1ClientConfig, LSPS2ClientConfig, LSPS2ServiceConfig, LiquiditySourceBuilder,
};
use crate::logger::{log_error, log_info, LdkLogger, LogLevel, LogWriter, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::store::PaymentStore;
use crate::peer_store::PeerStore;
use crate::tx_broadcaster::TransactionBroadcaster;
use crate::types::{
ChainMonitor, ChannelManager, DynStore, GossipSync, Graph, KeysManager, MessageRouter,
OnionMessenger, PeerManager,
OnionMessenger, PaymentStore, PeerManager,
};
use crate::wallet::persist::KVStoreWalletPersister;
use crate::wallet::Wallet;
use crate::{io, Node, NodeMetrics};
use crate::{Node, NodeMetrics};

use lightning::chain::{chainmonitor, BestBlock, Watch};
use lightning::io::Cursor;
Expand DownExpand Up@@ -1015,9 +1017,13 @@ fn build_with_store_internal(
let fee_estimator = Arc::new(OnchainFeeEstimator::new());

let payment_store = match io::utils::read_payments(Arc::clone(&kv_store), Arc::clone(&logger)) {
Ok(payments) => {
Arc::new(PaymentStore::new(payments, Arc::clone(&kv_store), Arc::clone(&logger)))
},
Ok(payments) => Arc::new(PaymentStore::new(
payments,
PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE.to_string(),
PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE.to_string(),
Arc::clone(&kv_store),
Arc::clone(&logger),
)),
Err(_) => {
return Err(BuildError::ReadFailed);
},
Expand Down
287 changes: 287 additions & 0 deletions src/data_store.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,287 @@
// This file is Copyright its original authors, visible in version control history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
// accordance with one or both of these licenses.

use crate::logger::{log_error, LdkLogger};
use crate::types::DynStore;
use crate::Error;

use lightning::util::ser::{Readable, Writeable};

use std::collections::hash_map;
use std::collections::HashMap;
use std::ops::Deref;
use std::sync::{Arc, Mutex};

pub(crate) trait StorableObject: Clone + Readable + Writeable {
type Id: StorableObjectId;
type Update: StorableObjectUpdate<Self>;

fn id(&self) -> Self::Id;
fn update(&mut self, update: &Self::Update) -> bool;
fn to_update(&self) -> Self::Update;
}

pub(crate) trait StorableObjectId: std::hash::Hash + PartialEq + Eq {
fn encode_to_hex_str(&self) -> String;
}

pub(crate) trait StorableObjectUpdate<SO: StorableObject> {
fn id(&self) -> SO::Id;
}

#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub(crate) enum DataStoreUpdateResult {
Updated,
Unchanged,
NotFound,
}

pub(crate) struct DataStore<SO: StorableObject, L: Deref>
where
L::Target: LdkLogger,
{
objects: Mutex<HashMap<SO::Id, SO>>,
primary_namespace: String,
secondary_namespace: String,
kv_store: Arc<DynStore>,
logger: L,
}

impl<SO: StorableObject, L: Deref> DataStore<SO, L>
where
L::Target: LdkLogger,
{
pub(crate) fn new(
objects: Vec<SO>, primary_namespace: String, secondary_namespace: String,
kv_store: Arc<DynStore>, logger: L,
) -> Self {
let objects =
Mutex::new(HashMap::from_iter(objects.into_iter().map(|obj| (obj.id(), obj))));
Self { objects, primary_namespace, secondary_namespace, kv_store, logger }
}

pub(crate) fn insert(&self, object: SO) -> Result<bool, Error> {
let mut locked_objects = self.objects.lock().unwrap();

self.persist(&object)?;
let updated = locked_objects.insert(object.id(), object).is_some();
Comment on lines +70 to +71

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the order matter here? The opposite order is used in insert_or_update, so there we could have the object in memory but fail persisting.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, this one used to be the other way around, but I changed it here (actually should be the only behavioral diff I snuck in, IIRC), exactly because it would be preferable to not update the in-memory version if persistence failed. However, for insert_or_update/update we won't know whether the update is necessary at all until StorableObject::update returns, which is why we unfortunately can't first persist.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For insert_or_update/update, it seems we log an error but continue. I suppose this predates the PR, but I wonder if we should do something else like have a queue of ids that still need persistence. Though if we eventually crash that information would be loss. Maybe this is more of a storage implementation concern.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, we could do that eventually, although it probably would somehow need to fit into a "halt everything on (remote) persistence failure, and resume/restart once we reestablish connectivity" scheme.

Ok(updated)
}

pub(crate) fn insert_or_update(&self, object: SO) -> Result<bool, Error> {
let mut locked_objects = self.objects.lock().unwrap();

let updated;
match locked_objects.entry(object.id()) {
hash_map::Entry::Occupied(mut e) => {
let update = object.to_update();
updated = e.get_mut().update(&update);
if updated {
self.persist(&e.get())?;
}
},
hash_map::Entry::Vacant(e) => {
e.insert(object.clone());
self.persist(&object)?;
updated = true;
},
}

Ok(updated)
}

pub(crate) fn remove(&self, id: &SO::Id) -> Result<(), Error> {
let removed = self.objects.lock().unwrap().remove(id).is_some();
if removed {
let store_key = id.encode_to_hex_str();
self.kv_store
.remove(&self.primary_namespace, &self.secondary_namespace, &store_key, false)
.map_err(|e| {
log_error!(
self.logger,
"Removing object data for key {}/{}/{} failed due to: {}",
&self.primary_namespace,
&self.secondary_namespace,
store_key,
e
);
Error::PersistenceFailed
})?;
}
Ok(())
}

pub(crate) fn get(&self, id: &SO::Id) -> Option<SO> {
self.objects.lock().unwrap().get(id).cloned()
}

pub(crate) fn update(&self, update: &SO::Update) -> Result<DataStoreUpdateResult, Error> {
let mut locked_objects = self.objects.lock().unwrap();

if let Some(object) = locked_objects.get_mut(&update.id()) {
let updated = object.update(update);
if updated {
self.persist(&object)?;
Ok(DataStoreUpdateResult::Updated)
} else {
Ok(DataStoreUpdateResult::Unchanged)
}
} else {
Ok(DataStoreUpdateResult::NotFound)
}
}

pub(crate) fn list_filter<F: FnMut(&&SO) -> bool>(&self, f: F) -> Vec<SO> {
self.objects.lock().unwrap().values().filter(f).cloned().collect::<Vec<SO>>()
}

fn persist(&self, object: &SO) -> Result<(), Error> {
let store_key = object.id().encode_to_hex_str();
let data = object.encode();
self.kv_store
.write(&self.primary_namespace, &self.secondary_namespace, &store_key, &data)
.map_err(|e| {
log_error!(
self.logger,
"Write for key {}/{}/{} failed due to: {}",
&self.primary_namespace,
&self.secondary_namespace,
store_key,
e
);
Error::PersistenceFailed
})?;
Ok(())
}
}

#[cfg(test)]
mod tests {
use lightning::impl_writeable_tlv_based;
use lightning::util::test_utils::{TestLogger, TestStore};

use crate::hex_utils;

use super::*;

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct TestObjectId {
id: [u8; 4],
}

impl StorableObjectId for TestObjectId {
fn encode_to_hex_str(&self) -> String {
hex_utils::to_string(&self.id)
}
}
impl_writeable_tlv_based!(TestObjectId, { (0, id, required) });

struct TestObjectUpdate {
id: TestObjectId,
data: [u8; 3],
}
impl StorableObjectUpdate<TestObject> for TestObjectUpdate {
fn id(&self) -> TestObjectId {
self.id
}
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct TestObject {
id: TestObjectId,
data: [u8; 3],
}

impl StorableObject for TestObject {
type Id = TestObjectId;
type Update = TestObjectUpdate;

fn id(&self) -> Self::Id {
self.id
}

fn update(&mut self, update: &Self::Update) -> bool {
if self.data != update.data {
self.data = update.data;
true
} else {
false
}
}

fn to_update(&self) -> Self::Update {
Self::Update { id: self.id, data: self.data }
}
}

impl_writeable_tlv_based!(TestObject, {
(0, id, required),
(2, data, required),
});

#[test]
fn data_is_persisted() {
let store: Arc<DynStore> = Arc::new(TestStore::new(false));
let logger = Arc::new(TestLogger::new());
let primary_namespace = "datastore_test_primary".to_string();
let secondary_namespace = "datastore_test_secondary".to_string();
let data_store: DataStore<TestObject, Arc<TestLogger>> = DataStore::new(
Vec::new(),
primary_namespace.clone(),
secondary_namespace.clone(),
Arc::clone(&store),
logger,
);

let id = TestObjectId { id: [42u8; 4] };
assert!(data_store.get(&id).is_none());

let store_key = id.encode_to_hex_str();

// Check we start empty.
assert!(store.read(&primary_namespace, &secondary_namespace, &store_key).is_err());

// Check we successfully store an object and return `false`
let object = TestObject { id, data: [23u8; 3] };
assert_eq!(Ok(false), data_store.insert(object.clone()));
assert_eq!(Some(object), data_store.get(&id));
assert!(store.read(&primary_namespace, &secondary_namespace, &store_key).is_ok());

// Test re-insertion returns `true`
let mut override_object = object.clone();
override_object.data = [24u8; 3];
assert_eq!(Ok(true), data_store.insert(override_object));
assert_eq!(Some(override_object), data_store.get(&id));

// Check update returns `Updated`
let update = TestObjectUpdate { id, data: [25u8; 3] };
assert_eq!(Ok(DataStoreUpdateResult::Updated), data_store.update(&update));
assert_eq!(data_store.get(&id).unwrap().data, [25u8; 3]);

// Check no-op update yields `Unchanged`
let update = TestObjectUpdate { id, data: [25u8; 3] };
assert_eq!(Ok(DataStoreUpdateResult::Unchanged), data_store.update(&update));

// Check bogus update yields `NotFound`
let bogus_id = TestObjectId { id: [84u8; 4] };
let update = TestObjectUpdate { id: bogus_id, data: [12u8; 3] };
assert_eq!(Ok(DataStoreUpdateResult::NotFound), data_store.update(&update));

// Check `insert_or_update` inserts unknown objects
let iou_id = TestObjectId { id: [55u8; 4] };
let iou_object = TestObject { id: iou_id, data: [34u8; 3] };
assert_eq!(Ok(true), data_store.insert_or_update(iou_object.clone()));

// Check `insert_or_update` doesn't update the same object
assert_eq!(Ok(false), data_store.insert_or_update(iou_object.clone()));

// Check `insert_or_update` updates if object changed
let mut new_iou_object = iou_object;
new_iou_object.data[0] += 1;
assert_eq!(Ok(true), data_store.insert_or_update(new_iou_object));
}
}
13 changes: 6 additions & 7 deletions src/event.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,7 +5,7 @@
// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
// accordance with one or both of these licenses.

use crate::types::{CustomTlvRecord, DynStore, Sweeper, Wallet};
use crate::types::{CustomTlvRecord, DynStore, PaymentStore, Sweeper, Wallet};

use crate::{
hex_utils, BumpTransactionEventHandler, ChannelManager, Error, Graph, PeerInfo, PeerStore,
Expand All@@ -14,13 +14,13 @@ use crate::{

use crate::config::{may_announce_channel, Config};
use crate::connection::ConnectionManager;
use crate::data_store::DataStoreUpdateResult;
use crate::fee_estimator::ConfirmationTarget;
use crate::liquidity::LiquiditySource;
use crate::logger::Logger;

use crate::payment::store::{
PaymentDetails, PaymentDetailsUpdate, PaymentDirection, PaymentKind, PaymentStatus,
PaymentStore, PaymentStoreUpdateResult,
};

use crate::io::{
Expand DownExpand Up@@ -449,7 +449,7 @@ where
output_sweeper: Arc<Sweeper>,
network_graph: Arc<Graph>,
liquidity_source: Option<Arc<LiquiditySource<Arc<Logger>>>>,
payment_store: Arc<PaymentStore<L>>,
payment_store: Arc<PaymentStore>,
peer_store: Arc<PeerStore<L>>,
runtime: Arc<RwLock<Option<Arc<tokio::runtime::Runtime>>>>,
logger: L,
Expand All@@ -466,7 +466,7 @@ where
channel_manager: Arc<ChannelManager>, connection_manager: Arc<ConnectionManager<L>>,
output_sweeper: Arc<Sweeper>, network_graph: Arc<Graph>,
liquidity_source: Option<Arc<LiquiditySource<Arc<Logger>>>>,
payment_store: Arc<PaymentStore<L>>, peer_store: Arc<PeerStore<L>>,
payment_store: Arc<PaymentStore>, peer_store: Arc<PeerStore<L>>,
runtime: Arc<RwLock<Option<Arc<tokio::runtime::Runtime>>>>, logger: L, config: Arc<Config>,
) -> Self {
Self {
Expand DownExpand Up@@ -906,12 +906,11 @@ where
};

match self.payment_store.update(&update) {
Ok(PaymentStoreUpdateResult::Updated)
| Ok(PaymentStoreUpdateResult::Unchanged) => (
Ok(DataStoreUpdateResult::Updated) | Ok(DataStoreUpdateResult::Unchanged) => (
// No need to do anything if the idempotent update was applied, which might
// be the result of a replayed event.
),
Ok(PaymentStoreUpdateResult::NotFound) => {
Ok(DataStoreUpdateResult::NotFound) => {
log_error!(
self.logger,
"Claimed payment with ID {} couldn't be found in store",
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
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
18 changes: 12 additions & 6 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,21 +18,23 @@ use crate::gossip::GossipSource;
use crate::io::sqlite_store::SqliteStore;
use crate::io::utils::{read_node_metrics, write_node_metrics};
use crate::io::vss_store::VssStore;
use crate::io::{
self, PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE, PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE,
};
use crate::liquidity::{
LSPS1ClientConfig, LSPS2ClientConfig, LSPS2ServiceConfig, LiquiditySourceBuilder,
};
use crate::logger::{log_error, log_info, LdkLogger, LogLevel, LogWriter, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::store::PaymentStore;
use crate::peer_store::PeerStore;
use crate::tx_broadcaster::TransactionBroadcaster;
use crate::types::{
ChainMonitor, ChannelManager, DynStore, GossipSync, Graph, KeysManager, MessageRouter,
OnionMessenger, PeerManager,
OnionMessenger, PaymentStore, PeerManager,
};
use crate::wallet::persist::KVStoreWalletPersister;
use crate::wallet::Wallet;
use crate::{io, Node, NodeMetrics};
use crate::{Node, NodeMetrics};

use lightning::chain::{chainmonitor, BestBlock, Watch};
use lightning::io::Cursor;
Expand DownExpand Up@@ -1015,9 +1017,13 @@ fn build_with_store_internal(
let fee_estimator = Arc::new(OnchainFeeEstimator::new());

let payment_store = match io::utils::read_payments(Arc::clone(&kv_store), Arc::clone(&logger)) {
Ok(payments) => {
Arc::new(PaymentStore::new(payments, Arc::clone(&kv_store), Arc::clone(&logger)))
},
Ok(payments) => Arc::new(PaymentStore::new(
payments,
PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE.to_string(),
PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE.to_string(),
Arc::clone(&kv_store),
Arc::clone(&logger),
)),
Err(_) => {
return Err(BuildError::ReadFailed);
},
Expand Down
287 changes: 287 additions & 0 deletions src/data_store.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,287 @@
// This file is Copyright its original authors, visible in version control history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
// accordance with one or both of these licenses.

use crate::logger::{log_error, LdkLogger};
use crate::types::DynStore;
use crate::Error;

use lightning::util::ser::{Readable, Writeable};

use std::collections::hash_map;
use std::collections::HashMap;
use std::ops::Deref;
use std::sync::{Arc, Mutex};

pub(crate) trait StorableObject: Clone + Readable + Writeable {
type Id: StorableObjectId;
type Update: StorableObjectUpdate<Self>;

fn id(&self) -> Self::Id;
fn update(&mut self, update: &Self::Update) -> bool;
fn to_update(&self) -> Self::Update;
}

pub(crate) trait StorableObjectId: std::hash::Hash + PartialEq + Eq {
fn encode_to_hex_str(&self) -> String;
}

pub(crate) trait StorableObjectUpdate<SO: StorableObject> {
fn id(&self) -> SO::Id;
}

#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub(crate) enum DataStoreUpdateResult {
Updated,
Unchanged,
NotFound,
}

pub(crate) struct DataStore<SO: StorableObject, L: Deref>
where
L::Target: LdkLogger,
{
objects: Mutex<HashMap<SO::Id, SO>>,
primary_namespace: String,
secondary_namespace: String,
kv_store: Arc<DynStore>,
logger: L,
}

impl<SO: StorableObject, L: Deref> DataStore<SO, L>
where
L::Target: LdkLogger,
{
pub(crate) fn new(
objects: Vec<SO>, primary_namespace: String, secondary_namespace: String,
kv_store: Arc<DynStore>, logger: L,
) -> Self {
let objects =
Mutex::new(HashMap::from_iter(objects.into_iter().map(|obj| (obj.id(), obj))));
Self { objects, primary_namespace, secondary_namespace, kv_store, logger }
}

pub(crate) fn insert(&self, object: SO) -> Result<bool, Error> {
let mut locked_objects = self.objects.lock().unwrap();

self.persist(&object)?;
let updated = locked_objects.insert(object.id(), object).is_some();
Comment on lines +70 to +71

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the order matter here? The opposite order is used in insert_or_update, so there we could have the object in memory but fail persisting.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, this one used to be the other way around, but I changed it here (actually should be the only behavioral diff I snuck in, IIRC), exactly because it would be preferable to not update the in-memory version if persistence failed. However, for insert_or_update/update we won't know whether the update is necessary at all until StorableObject::update returns, which is why we unfortunately can't first persist.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For insert_or_update/update, it seems we log an error but continue. I suppose this predates the PR, but I wonder if we should do something else like have a queue of ids that still need persistence. Though if we eventually crash that information would be loss. Maybe this is more of a storage implementation concern.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, we could do that eventually, although it probably would somehow need to fit into a "halt everything on (remote) persistence failure, and resume/restart once we reestablish connectivity" scheme.

Ok(updated)
}

pub(crate) fn insert_or_update(&self, object: SO) -> Result<bool, Error> {
let mut locked_objects = self.objects.lock().unwrap();

let updated;
match locked_objects.entry(object.id()) {
hash_map::Entry::Occupied(mut e) => {
let update = object.to_update();
updated = e.get_mut().update(&update);
if updated {
self.persist(&e.get())?;
}
},
hash_map::Entry::Vacant(e) => {
e.insert(object.clone());
self.persist(&object)?;
updated = true;
},
}

Ok(updated)
}

pub(crate) fn remove(&self, id: &SO::Id) -> Result<(), Error> {
let removed = self.objects.lock().unwrap().remove(id).is_some();
if removed {
let store_key = id.encode_to_hex_str();
self.kv_store
.remove(&self.primary_namespace, &self.secondary_namespace, &store_key, false)
.map_err(|e| {
log_error!(
self.logger,
"Removing object data for key {}/{}/{} failed due to: {}",
&self.primary_namespace,
&self.secondary_namespace,
store_key,
e
);
Error::PersistenceFailed
})?;
}
Ok(())
}

pub(crate) fn get(&self, id: &SO::Id) -> Option<SO> {
self.objects.lock().unwrap().get(id).cloned()
}

pub(crate) fn update(&self, update: &SO::Update) -> Result<DataStoreUpdateResult, Error> {
let mut locked_objects = self.objects.lock().unwrap();

if let Some(object) = locked_objects.get_mut(&update.id()) {
let updated = object.update(update);
if updated {
self.persist(&object)?;
Ok(DataStoreUpdateResult::Updated)
} else {
Ok(DataStoreUpdateResult::Unchanged)
}
} else {
Ok(DataStoreUpdateResult::NotFound)
}
}

pub(crate) fn list_filter<F: FnMut(&&SO) -> bool>(&self, f: F) -> Vec<SO> {
self.objects.lock().unwrap().values().filter(f).cloned().collect::<Vec<SO>>()
}

fn persist(&self, object: &SO) -> Result<(), Error> {
let store_key = object.id().encode_to_hex_str();
let data = object.encode();
self.kv_store
.write(&self.primary_namespace, &self.secondary_namespace, &store_key, &data)
.map_err(|e| {
log_error!(
self.logger,
"Write for key {}/{}/{} failed due to: {}",
&self.primary_namespace,
&self.secondary_namespace,
store_key,
e
);
Error::PersistenceFailed
})?;
Ok(())
}
}

#[cfg(test)]
mod tests {
use lightning::impl_writeable_tlv_based;
use lightning::util::test_utils::{TestLogger, TestStore};

use crate::hex_utils;

use super::*;

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct TestObjectId {
id: [u8; 4],
}

impl StorableObjectId for TestObjectId {
fn encode_to_hex_str(&self) -> String {
hex_utils::to_string(&self.id)
}
}
impl_writeable_tlv_based!(TestObjectId, { (0, id, required) });

struct TestObjectUpdate {
id: TestObjectId,
data: [u8; 3],
}
impl StorableObjectUpdate<TestObject> for TestObjectUpdate {
fn id(&self) -> TestObjectId {
self.id
}
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct TestObject {
id: TestObjectId,
data: [u8; 3],
}

impl StorableObject for TestObject {
type Id = TestObjectId;
type Update = TestObjectUpdate;

fn id(&self) -> Self::Id {
self.id
}

fn update(&mut self, update: &Self::Update) -> bool {
if self.data != update.data {
self.data = update.data;
true
} else {
false
}
}

fn to_update(&self) -> Self::Update {
Self::Update { id: self.id, data: self.data }
}
}

impl_writeable_tlv_based!(TestObject, {
(0, id, required),
(2, data, required),
});

#[test]
fn data_is_persisted() {
let store: Arc<DynStore> = Arc::new(TestStore::new(false));
let logger = Arc::new(TestLogger::new());
let primary_namespace = "datastore_test_primary".to_string();
let secondary_namespace = "datastore_test_secondary".to_string();
let data_store: DataStore<TestObject, Arc<TestLogger>> = DataStore::new(
Vec::new(),
primary_namespace.clone(),
secondary_namespace.clone(),
Arc::clone(&store),
logger,
);

let id = TestObjectId { id: [42u8; 4] };
assert!(data_store.get(&id).is_none());

let store_key = id.encode_to_hex_str();

// Check we start empty.
assert!(store.read(&primary_namespace, &secondary_namespace, &store_key).is_err());

// Check we successfully store an object and return `false`
let object = TestObject { id, data: [23u8; 3] };
assert_eq!(Ok(false), data_store.insert(object.clone()));
assert_eq!(Some(object), data_store.get(&id));
assert!(store.read(&primary_namespace, &secondary_namespace, &store_key).is_ok());

// Test re-insertion returns `true`
let mut override_object = object.clone();
override_object.data = [24u8; 3];
assert_eq!(Ok(true), data_store.insert(override_object));
assert_eq!(Some(override_object), data_store.get(&id));

// Check update returns `Updated`
let update = TestObjectUpdate { id, data: [25u8; 3] };
assert_eq!(Ok(DataStoreUpdateResult::Updated), data_store.update(&update));
assert_eq!(data_store.get(&id).unwrap().data, [25u8; 3]);

// Check no-op update yields `Unchanged`
let update = TestObjectUpdate { id, data: [25u8; 3] };
assert_eq!(Ok(DataStoreUpdateResult::Unchanged), data_store.update(&update));

// Check bogus update yields `NotFound`
let bogus_id = TestObjectId { id: [84u8; 4] };
let update = TestObjectUpdate { id: bogus_id, data: [12u8; 3] };
assert_eq!(Ok(DataStoreUpdateResult::NotFound), data_store.update(&update));

// Check `insert_or_update` inserts unknown objects
let iou_id = TestObjectId { id: [55u8; 4] };
let iou_object = TestObject { id: iou_id, data: [34u8; 3] };
assert_eq!(Ok(true), data_store.insert_or_update(iou_object.clone()));

// Check `insert_or_update` doesn't update the same object
assert_eq!(Ok(false), data_store.insert_or_update(iou_object.clone()));

// Check `insert_or_update` updates if object changed
let mut new_iou_object = iou_object;
new_iou_object.data[0] += 1;
assert_eq!(Ok(true), data_store.insert_or_update(new_iou_object));
}
}
13 changes: 6 additions & 7 deletions src/event.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,7 +5,7 @@
// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
// accordance with one or both of these licenses.

use crate::types::{CustomTlvRecord, DynStore, Sweeper, Wallet};
use crate::types::{CustomTlvRecord, DynStore, PaymentStore, Sweeper, Wallet};

use crate::{
hex_utils, BumpTransactionEventHandler, ChannelManager, Error, Graph, PeerInfo, PeerStore,
Expand All@@ -14,13 +14,13 @@ use crate::{

use crate::config::{may_announce_channel, Config};
use crate::connection::ConnectionManager;
use crate::data_store::DataStoreUpdateResult;
use crate::fee_estimator::ConfirmationTarget;
use crate::liquidity::LiquiditySource;
use crate::logger::Logger;

use crate::payment::store::{
PaymentDetails, PaymentDetailsUpdate, PaymentDirection, PaymentKind, PaymentStatus,
PaymentStore, PaymentStoreUpdateResult,
};

use crate::io::{
Expand DownExpand Up@@ -449,7 +449,7 @@ where
output_sweeper: Arc<Sweeper>,
network_graph: Arc<Graph>,
liquidity_source: Option<Arc<LiquiditySource<Arc<Logger>>>>,
payment_store: Arc<PaymentStore<L>>,
payment_store: Arc<PaymentStore>,
peer_store: Arc<PeerStore<L>>,
runtime: Arc<RwLock<Option<Arc<tokio::runtime::Runtime>>>>,
logger: L,
Expand All@@ -466,7 +466,7 @@ where
channel_manager: Arc<ChannelManager>, connection_manager: Arc<ConnectionManager<L>>,
output_sweeper: Arc<Sweeper>, network_graph: Arc<Graph>,
liquidity_source: Option<Arc<LiquiditySource<Arc<Logger>>>>,
payment_store: Arc<PaymentStore<L>>, peer_store: Arc<PeerStore<L>>,
payment_store: Arc<PaymentStore>, peer_store: Arc<PeerStore<L>>,
runtime: Arc<RwLock<Option<Arc<tokio::runtime::Runtime>>>>, logger: L, config: Arc<Config>,
) -> Self {
Self {
Expand DownExpand Up@@ -906,12 +906,11 @@ where
};

match self.payment_store.update(&update) {
Ok(PaymentStoreUpdateResult::Updated)
| Ok(PaymentStoreUpdateResult::Unchanged) => (
Ok(DataStoreUpdateResult::Updated) | Ok(DataStoreUpdateResult::Unchanged) => (
// No need to do anything if the idempotent update was applied, which might
// be the result of a replayed event.
),
Ok(PaymentStoreUpdateResult::NotFound) => {
Ok(DataStoreUpdateResult::NotFound) => {
log_error!(
self.logger,
"Claimed payment with ID {} couldn't be found in store",
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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
18 changes: 12 additions & 6 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,21 +18,23 @@ use crate::gossip::GossipSource;
use crate::io::sqlite_store::SqliteStore;
use crate::io::utils::{read_node_metrics, write_node_metrics};
use crate::io::vss_store::VssStore;
use crate::io::{
self, PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE, PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE,
};
use crate::liquidity::{
LSPS1ClientConfig, LSPS2ClientConfig, LSPS2ServiceConfig, LiquiditySourceBuilder,
};
use crate::logger::{log_error, log_info, LdkLogger, LogLevel, LogWriter, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::store::PaymentStore;
use crate::peer_store::PeerStore;
use crate::tx_broadcaster::TransactionBroadcaster;
use crate::types::{
ChainMonitor, ChannelManager, DynStore, GossipSync, Graph, KeysManager, MessageRouter,
OnionMessenger, PeerManager,
OnionMessenger, PaymentStore, PeerManager,
};
use crate::wallet::persist::KVStoreWalletPersister;
use crate::wallet::Wallet;
use crate::{io, Node, NodeMetrics};
use crate::{Node, NodeMetrics};

use lightning::chain::{chainmonitor, BestBlock, Watch};
use lightning::io::Cursor;
Expand DownExpand Up@@ -1015,9 +1017,13 @@ fn build_with_store_internal(
let fee_estimator = Arc::new(OnchainFeeEstimator::new());

let payment_store = match io::utils::read_payments(Arc::clone(&kv_store), Arc::clone(&logger)) {
Ok(payments) => {
Arc::new(PaymentStore::new(payments, Arc::clone(&kv_store), Arc::clone(&logger)))
},
Ok(payments) => Arc::new(PaymentStore::new(
payments,
PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE.to_string(),
PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE.to_string(),
Arc::clone(&kv_store),
Arc::clone(&logger),
)),
Err(_) => {
return Err(BuildError::ReadFailed);
},
Expand Down
287 changes: 287 additions & 0 deletions src/data_store.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,287 @@
// This file is Copyright its original authors, visible in version control history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
// accordance with one or both of these licenses.

use crate::logger::{log_error, LdkLogger};
use crate::types::DynStore;
use crate::Error;

use lightning::util::ser::{Readable, Writeable};

use std::collections::hash_map;
use std::collections::HashMap;
use std::ops::Deref;
use std::sync::{Arc, Mutex};

pub(crate) trait StorableObject: Clone + Readable + Writeable {
type Id: StorableObjectId;
type Update: StorableObjectUpdate<Self>;

fn id(&self) -> Self::Id;
fn update(&mut self, update: &Self::Update) -> bool;
fn to_update(&self) -> Self::Update;
}

pub(crate) trait StorableObjectId: std::hash::Hash + PartialEq + Eq {
fn encode_to_hex_str(&self) -> String;
}

pub(crate) trait StorableObjectUpdate<SO: StorableObject> {
fn id(&self) -> SO::Id;
}

#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub(crate) enum DataStoreUpdateResult {
Updated,
Unchanged,
NotFound,
}

pub(crate) struct DataStore<SO: StorableObject, L: Deref>
where
L::Target: LdkLogger,
{
objects: Mutex<HashMap<SO::Id, SO>>,
primary_namespace: String,
secondary_namespace: String,
kv_store: Arc<DynStore>,
logger: L,
}

impl<SO: StorableObject, L: Deref> DataStore<SO, L>
where
L::Target: LdkLogger,
{
pub(crate) fn new(
objects: Vec<SO>, primary_namespace: String, secondary_namespace: String,
kv_store: Arc<DynStore>, logger: L,
) -> Self {
let objects =
Mutex::new(HashMap::from_iter(objects.into_iter().map(|obj| (obj.id(), obj))));
Self { objects, primary_namespace, secondary_namespace, kv_store, logger }
}

pub(crate) fn insert(&self, object: SO) -> Result<bool, Error> {
let mut locked_objects = self.objects.lock().unwrap();

self.persist(&object)?;
let updated = locked_objects.insert(object.id(), object).is_some();
Comment on lines +70 to +71

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the order matter here? The opposite order is used in insert_or_update, so there we could have the object in memory but fail persisting.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, this one used to be the other way around, but I changed it here (actually should be the only behavioral diff I snuck in, IIRC), exactly because it would be preferable to not update the in-memory version if persistence failed. However, for insert_or_update/update we won't know whether the update is necessary at all until StorableObject::update returns, which is why we unfortunately can't first persist.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For insert_or_update/update, it seems we log an error but continue. I suppose this predates the PR, but I wonder if we should do something else like have a queue of ids that still need persistence. Though if we eventually crash that information would be loss. Maybe this is more of a storage implementation concern.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, we could do that eventually, although it probably would somehow need to fit into a "halt everything on (remote) persistence failure, and resume/restart once we reestablish connectivity" scheme.

Ok(updated)
}

pub(crate) fn insert_or_update(&self, object: SO) -> Result<bool, Error> {
let mut locked_objects = self.objects.lock().unwrap();

let updated;
match locked_objects.entry(object.id()) {
hash_map::Entry::Occupied(mut e) => {
let update = object.to_update();
updated = e.get_mut().update(&update);
if updated {
self.persist(&e.get())?;
}
},
hash_map::Entry::Vacant(e) => {
e.insert(object.clone());
self.persist(&object)?;
updated = true;
},
}

Ok(updated)
}

pub(crate) fn remove(&self, id: &SO::Id) -> Result<(), Error> {
let removed = self.objects.lock().unwrap().remove(id).is_some();
if removed {
let store_key = id.encode_to_hex_str();
self.kv_store
.remove(&self.primary_namespace, &self.secondary_namespace, &store_key, false)
.map_err(|e| {
log_error!(
self.logger,
"Removing object data for key {}/{}/{} failed due to: {}",
&self.primary_namespace,
&self.secondary_namespace,
store_key,
e
);
Error::PersistenceFailed
})?;
}
Ok(())
}

pub(crate) fn get(&self, id: &SO::Id) -> Option<SO> {
self.objects.lock().unwrap().get(id).cloned()
}

pub(crate) fn update(&self, update: &SO::Update) -> Result<DataStoreUpdateResult, Error> {
let mut locked_objects = self.objects.lock().unwrap();

if let Some(object) = locked_objects.get_mut(&update.id()) {
let updated = object.update(update);
if updated {
self.persist(&object)?;
Ok(DataStoreUpdateResult::Updated)
} else {
Ok(DataStoreUpdateResult::Unchanged)
}
} else {
Ok(DataStoreUpdateResult::NotFound)
}
}

pub(crate) fn list_filter<F: FnMut(&&SO) -> bool>(&self, f: F) -> Vec<SO> {
self.objects.lock().unwrap().values().filter(f).cloned().collect::<Vec<SO>>()
}

fn persist(&self, object: &SO) -> Result<(), Error> {
let store_key = object.id().encode_to_hex_str();
let data = object.encode();
self.kv_store
.write(&self.primary_namespace, &self.secondary_namespace, &store_key, &data)
.map_err(|e| {
log_error!(
self.logger,
"Write for key {}/{}/{} failed due to: {}",
&self.primary_namespace,
&self.secondary_namespace,
store_key,
e
);
Error::PersistenceFailed
})?;
Ok(())
}
}

#[cfg(test)]
mod tests {
use lightning::impl_writeable_tlv_based;
use lightning::util::test_utils::{TestLogger, TestStore};

use crate::hex_utils;

use super::*;

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct TestObjectId {
id: [u8; 4],
}

impl StorableObjectId for TestObjectId {
fn encode_to_hex_str(&self) -> String {
hex_utils::to_string(&self.id)
}
}
impl_writeable_tlv_based!(TestObjectId, { (0, id, required) });

struct TestObjectUpdate {
id: TestObjectId,
data: [u8; 3],
}
impl StorableObjectUpdate<TestObject> for TestObjectUpdate {
fn id(&self) -> TestObjectId {
self.id
}
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct TestObject {
id: TestObjectId,
data: [u8; 3],
}

impl StorableObject for TestObject {
type Id = TestObjectId;
type Update = TestObjectUpdate;

fn id(&self) -> Self::Id {
self.id
}

fn update(&mut self, update: &Self::Update) -> bool {
if self.data != update.data {
self.data = update.data;
true
} else {
false
}
}

fn to_update(&self) -> Self::Update {
Self::Update { id: self.id, data: self.data }
}
}

impl_writeable_tlv_based!(TestObject, {
(0, id, required),
(2, data, required),
});

#[test]
fn data_is_persisted() {
let store: Arc<DynStore> = Arc::new(TestStore::new(false));
let logger = Arc::new(TestLogger::new());
let primary_namespace = "datastore_test_primary".to_string();
let secondary_namespace = "datastore_test_secondary".to_string();
let data_store: DataStore<TestObject, Arc<TestLogger>> = DataStore::new(
Vec::new(),
primary_namespace.clone(),
secondary_namespace.clone(),
Arc::clone(&store),
logger,
);

let id = TestObjectId { id: [42u8; 4] };
assert!(data_store.get(&id).is_none());

let store_key = id.encode_to_hex_str();

// Check we start empty.
assert!(store.read(&primary_namespace, &secondary_namespace, &store_key).is_err());

// Check we successfully store an object and return `false`
let object = TestObject { id, data: [23u8; 3] };
assert_eq!(Ok(false), data_store.insert(object.clone()));
assert_eq!(Some(object), data_store.get(&id));
assert!(store.read(&primary_namespace, &secondary_namespace, &store_key).is_ok());

// Test re-insertion returns `true`
let mut override_object = object.clone();
override_object.data = [24u8; 3];
assert_eq!(Ok(true), data_store.insert(override_object));
assert_eq!(Some(override_object), data_store.get(&id));

// Check update returns `Updated`
let update = TestObjectUpdate { id, data: [25u8; 3] };
assert_eq!(Ok(DataStoreUpdateResult::Updated), data_store.update(&update));
assert_eq!(data_store.get(&id).unwrap().data, [25u8; 3]);

// Check no-op update yields `Unchanged`
let update = TestObjectUpdate { id, data: [25u8; 3] };
assert_eq!(Ok(DataStoreUpdateResult::Unchanged), data_store.update(&update));

// Check bogus update yields `NotFound`
let bogus_id = TestObjectId { id: [84u8; 4] };
let update = TestObjectUpdate { id: bogus_id, data: [12u8; 3] };
assert_eq!(Ok(DataStoreUpdateResult::NotFound), data_store.update(&update));

// Check `insert_or_update` inserts unknown objects
let iou_id = TestObjectId { id: [55u8; 4] };
let iou_object = TestObject { id: iou_id, data: [34u8; 3] };
assert_eq!(Ok(true), data_store.insert_or_update(iou_object.clone()));

// Check `insert_or_update` doesn't update the same object
assert_eq!(Ok(false), data_store.insert_or_update(iou_object.clone()));

// Check `insert_or_update` updates if object changed
let mut new_iou_object = iou_object;
new_iou_object.data[0] += 1;
assert_eq!(Ok(true), data_store.insert_or_update(new_iou_object));
}
}
13 changes: 6 additions & 7 deletions src/event.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,7 +5,7 @@
// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
// accordance with one or both of these licenses.

use crate::types::{CustomTlvRecord, DynStore, Sweeper, Wallet};
use crate::types::{CustomTlvRecord, DynStore, PaymentStore, Sweeper, Wallet};

use crate::{
hex_utils, BumpTransactionEventHandler, ChannelManager, Error, Graph, PeerInfo, PeerStore,
Expand All@@ -14,13 +14,13 @@ use crate::{

use crate::config::{may_announce_channel, Config};
use crate::connection::ConnectionManager;
use crate::data_store::DataStoreUpdateResult;
use crate::fee_estimator::ConfirmationTarget;
use crate::liquidity::LiquiditySource;
use crate::logger::Logger;

use crate::payment::store::{
PaymentDetails, PaymentDetailsUpdate, PaymentDirection, PaymentKind, PaymentStatus,
PaymentStore, PaymentStoreUpdateResult,
};

use crate::io::{
Expand DownExpand Up@@ -449,7 +449,7 @@ where
output_sweeper: Arc<Sweeper>,
network_graph: Arc<Graph>,
liquidity_source: Option<Arc<LiquiditySource<Arc<Logger>>>>,
payment_store: Arc<PaymentStore<L>>,
payment_store: Arc<PaymentStore>,
peer_store: Arc<PeerStore<L>>,
runtime: Arc<RwLock<Option<Arc<tokio::runtime::Runtime>>>>,
logger: L,
Expand All@@ -466,7 +466,7 @@ where
channel_manager: Arc<ChannelManager>, connection_manager: Arc<ConnectionManager<L>>,
output_sweeper: Arc<Sweeper>, network_graph: Arc<Graph>,
liquidity_source: Option<Arc<LiquiditySource<Arc<Logger>>>>,
payment_store: Arc<PaymentStore<L>>, peer_store: Arc<PeerStore<L>>,
payment_store: Arc<PaymentStore>, peer_store: Arc<PeerStore<L>>,
runtime: Arc<RwLock<Option<Arc<tokio::runtime::Runtime>>>>, logger: L, config: Arc<Config>,
) -> Self {
Self {
Expand DownExpand Up@@ -906,12 +906,11 @@ where
};

match self.payment_store.update(&update) {
Ok(PaymentStoreUpdateResult::Updated)
| Ok(PaymentStoreUpdateResult::Unchanged) => (
Ok(DataStoreUpdateResult::Updated) | Ok(DataStoreUpdateResult::Unchanged) => (
// No need to do anything if the idempotent update was applied, which might
// be the result of a replayed event.
),
Ok(PaymentStoreUpdateResult::NotFound) => {
Ok(DataStoreUpdateResult::NotFound) => {
log_error!(
self.logger,
"Claimed payment with ID {} couldn't be found in store",
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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
18 changes: 12 additions & 6 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,21 +18,23 @@ use crate::gossip::GossipSource;
use crate::io::sqlite_store::SqliteStore;
use crate::io::utils::{read_node_metrics, write_node_metrics};
use crate::io::vss_store::VssStore;
use crate::io::{
self, PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE, PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE,
};
use crate::liquidity::{
LSPS1ClientConfig, LSPS2ClientConfig, LSPS2ServiceConfig, LiquiditySourceBuilder,
};
use crate::logger::{log_error, log_info, LdkLogger, LogLevel, LogWriter, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::store::PaymentStore;
use crate::peer_store::PeerStore;
use crate::tx_broadcaster::TransactionBroadcaster;
use crate::types::{
ChainMonitor, ChannelManager, DynStore, GossipSync, Graph, KeysManager, MessageRouter,
OnionMessenger, PeerManager,
OnionMessenger, PaymentStore, PeerManager,
};
use crate::wallet::persist::KVStoreWalletPersister;
use crate::wallet::Wallet;
use crate::{io, Node, NodeMetrics};
use crate::{Node, NodeMetrics};

use lightning::chain::{chainmonitor, BestBlock, Watch};
use lightning::io::Cursor;
Expand DownExpand Up@@ -1015,9 +1017,13 @@ fn build_with_store_internal(
let fee_estimator = Arc::new(OnchainFeeEstimator::new());

let payment_store = match io::utils::read_payments(Arc::clone(&kv_store), Arc::clone(&logger)) {
Ok(payments) => {
Arc::new(PaymentStore::new(payments, Arc::clone(&kv_store), Arc::clone(&logger)))
},
Ok(payments) => Arc::new(PaymentStore::new(
payments,
PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE.to_string(),
PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE.to_string(),
Arc::clone(&kv_store),
Arc::clone(&logger),
)),
Err(_) => {
return Err(BuildError::ReadFailed);
},
Expand Down
287 changes: 287 additions & 0 deletions src/data_store.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,287 @@
// This file is Copyright its original authors, visible in version control history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
// accordance with one or both of these licenses.

use crate::logger::{log_error, LdkLogger};
use crate::types::DynStore;
use crate::Error;

use lightning::util::ser::{Readable, Writeable};

use std::collections::hash_map;
use std::collections::HashMap;
use std::ops::Deref;
use std::sync::{Arc, Mutex};

pub(crate) trait StorableObject: Clone + Readable + Writeable {
type Id: StorableObjectId;
type Update: StorableObjectUpdate<Self>;

fn id(&self) -> Self::Id;
fn update(&mut self, update: &Self::Update) -> bool;
fn to_update(&self) -> Self::Update;
}

pub(crate) trait StorableObjectId: std::hash::Hash + PartialEq + Eq {
fn encode_to_hex_str(&self) -> String;
}

pub(crate) trait StorableObjectUpdate<SO: StorableObject> {
fn id(&self) -> SO::Id;
}

#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub(crate) enum DataStoreUpdateResult {
Updated,
Unchanged,
NotFound,
}

pub(crate) struct DataStore<SO: StorableObject, L: Deref>
where
L::Target: LdkLogger,
{
objects: Mutex<HashMap<SO::Id, SO>>,
primary_namespace: String,
secondary_namespace: String,
kv_store: Arc<DynStore>,
logger: L,
}

impl<SO: StorableObject, L: Deref> DataStore<SO, L>
where
L::Target: LdkLogger,
{
pub(crate) fn new(
objects: Vec<SO>, primary_namespace: String, secondary_namespace: String,
kv_store: Arc<DynStore>, logger: L,
) -> Self {
let objects =
Mutex::new(HashMap::from_iter(objects.into_iter().map(|obj| (obj.id(), obj))));
Self { objects, primary_namespace, secondary_namespace, kv_store, logger }
}

pub(crate) fn insert(&self, object: SO) -> Result<bool, Error> {
let mut locked_objects = self.objects.lock().unwrap();

self.persist(&object)?;
let updated = locked_objects.insert(object.id(), object).is_some();
Comment on lines +70 to +71

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the order matter here? The opposite order is used in insert_or_update, so there we could have the object in memory but fail persisting.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, this one used to be the other way around, but I changed it here (actually should be the only behavioral diff I snuck in, IIRC), exactly because it would be preferable to not update the in-memory version if persistence failed. However, for insert_or_update/update we won't know whether the update is necessary at all until StorableObject::update returns, which is why we unfortunately can't first persist.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For insert_or_update/update, it seems we log an error but continue. I suppose this predates the PR, but I wonder if we should do something else like have a queue of ids that still need persistence. Though if we eventually crash that information would be loss. Maybe this is more of a storage implementation concern.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, we could do that eventually, although it probably would somehow need to fit into a "halt everything on (remote) persistence failure, and resume/restart once we reestablish connectivity" scheme.

Ok(updated)
}

pub(crate) fn insert_or_update(&self, object: SO) -> Result<bool, Error> {
let mut locked_objects = self.objects.lock().unwrap();

let updated;
match locked_objects.entry(object.id()) {
hash_map::Entry::Occupied(mut e) => {
let update = object.to_update();
updated = e.get_mut().update(&update);
if updated {
self.persist(&e.get())?;
}
},
hash_map::Entry::Vacant(e) => {
e.insert(object.clone());
self.persist(&object)?;
updated = true;
},
}

Ok(updated)
}

pub(crate) fn remove(&self, id: &SO::Id) -> Result<(), Error> {
let removed = self.objects.lock().unwrap().remove(id).is_some();
if removed {
let store_key = id.encode_to_hex_str();
self.kv_store
.remove(&self.primary_namespace, &self.secondary_namespace, &store_key, false)
.map_err(|e| {
log_error!(
self.logger,
"Removing object data for key {}/{}/{} failed due to: {}",
&self.primary_namespace,
&self.secondary_namespace,
store_key,
e
);
Error::PersistenceFailed
})?;
}
Ok(())
}

pub(crate) fn get(&self, id: &SO::Id) -> Option<SO> {
self.objects.lock().unwrap().get(id).cloned()
}

pub(crate) fn update(&self, update: &SO::Update) -> Result<DataStoreUpdateResult, Error> {
let mut locked_objects = self.objects.lock().unwrap();

if let Some(object) = locked_objects.get_mut(&update.id()) {
let updated = object.update(update);
if updated {
self.persist(&object)?;
Ok(DataStoreUpdateResult::Updated)
} else {
Ok(DataStoreUpdateResult::Unchanged)
}
} else {
Ok(DataStoreUpdateResult::NotFound)
}
}

pub(crate) fn list_filter<F: FnMut(&&SO) -> bool>(&self, f: F) -> Vec<SO> {
self.objects.lock().unwrap().values().filter(f).cloned().collect::<Vec<SO>>()
}

fn persist(&self, object: &SO) -> Result<(), Error> {
let store_key = object.id().encode_to_hex_str();
let data = object.encode();
self.kv_store
.write(&self.primary_namespace, &self.secondary_namespace, &store_key, &data)
.map_err(|e| {
log_error!(
self.logger,
"Write for key {}/{}/{} failed due to: {}",
&self.primary_namespace,
&self.secondary_namespace,
store_key,
e
);
Error::PersistenceFailed
})?;
Ok(())
}
}

#[cfg(test)]
mod tests {
use lightning::impl_writeable_tlv_based;
use lightning::util::test_utils::{TestLogger, TestStore};

use crate::hex_utils;

use super::*;

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct TestObjectId {
id: [u8; 4],
}

impl StorableObjectId for TestObjectId {
fn encode_to_hex_str(&self) -> String {
hex_utils::to_string(&self.id)
}
}
impl_writeable_tlv_based!(TestObjectId, { (0, id, required) });

struct TestObjectUpdate {
id: TestObjectId,
data: [u8; 3],
}
impl StorableObjectUpdate<TestObject> for TestObjectUpdate {
fn id(&self) -> TestObjectId {
self.id
}
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct TestObject {
id: TestObjectId,
data: [u8; 3],
}

impl StorableObject for TestObject {
type Id = TestObjectId;
type Update = TestObjectUpdate;

fn id(&self) -> Self::Id {
self.id
}

fn update(&mut self, update: &Self::Update) -> bool {
if self.data != update.data {
self.data = update.data;
true
} else {
false
}
}

fn to_update(&self) -> Self::Update {
Self::Update { id: self.id, data: self.data }
}
}

impl_writeable_tlv_based!(TestObject, {
(0, id, required),
(2, data, required),
});

#[test]
fn data_is_persisted() {
let store: Arc<DynStore> = Arc::new(TestStore::new(false));
let logger = Arc::new(TestLogger::new());
let primary_namespace = "datastore_test_primary".to_string();
let secondary_namespace = "datastore_test_secondary".to_string();
let data_store: DataStore<TestObject, Arc<TestLogger>> = DataStore::new(
Vec::new(),
primary_namespace.clone(),
secondary_namespace.clone(),
Arc::clone(&store),
logger,
);

let id = TestObjectId { id: [42u8; 4] };
assert!(data_store.get(&id).is_none());

let store_key = id.encode_to_hex_str();

// Check we start empty.
assert!(store.read(&primary_namespace, &secondary_namespace, &store_key).is_err());

// Check we successfully store an object and return `false`
let object = TestObject { id, data: [23u8; 3] };
assert_eq!(Ok(false), data_store.insert(object.clone()));
assert_eq!(Some(object), data_store.get(&id));
assert!(store.read(&primary_namespace, &secondary_namespace, &store_key).is_ok());

// Test re-insertion returns `true`
let mut override_object = object.clone();
override_object.data = [24u8; 3];
assert_eq!(Ok(true), data_store.insert(override_object));
assert_eq!(Some(override_object), data_store.get(&id));

// Check update returns `Updated`
let update = TestObjectUpdate { id, data: [25u8; 3] };
assert_eq!(Ok(DataStoreUpdateResult::Updated), data_store.update(&update));
assert_eq!(data_store.get(&id).unwrap().data, [25u8; 3]);

// Check no-op update yields `Unchanged`
let update = TestObjectUpdate { id, data: [25u8; 3] };
assert_eq!(Ok(DataStoreUpdateResult::Unchanged), data_store.update(&update));

// Check bogus update yields `NotFound`
let bogus_id = TestObjectId { id: [84u8; 4] };
let update = TestObjectUpdate { id: bogus_id, data: [12u8; 3] };
assert_eq!(Ok(DataStoreUpdateResult::NotFound), data_store.update(&update));

// Check `insert_or_update` inserts unknown objects
let iou_id = TestObjectId { id: [55u8; 4] };
let iou_object = TestObject { id: iou_id, data: [34u8; 3] };
assert_eq!(Ok(true), data_store.insert_or_update(iou_object.clone()));

// Check `insert_or_update` doesn't update the same object
assert_eq!(Ok(false), data_store.insert_or_update(iou_object.clone()));

// Check `insert_or_update` updates if object changed
let mut new_iou_object = iou_object;
new_iou_object.data[0] += 1;
assert_eq!(Ok(true), data_store.insert_or_update(new_iou_object));
}
}
13 changes: 6 additions & 7 deletions src/event.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,7 +5,7 @@
// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
// accordance with one or both of these licenses.

use crate::types::{CustomTlvRecord, DynStore, Sweeper, Wallet};
use crate::types::{CustomTlvRecord, DynStore, PaymentStore, Sweeper, Wallet};

use crate::{
hex_utils, BumpTransactionEventHandler, ChannelManager, Error, Graph, PeerInfo, PeerStore,
Expand All@@ -14,13 +14,13 @@ use crate::{

use crate::config::{may_announce_channel, Config};
use crate::connection::ConnectionManager;
use crate::data_store::DataStoreUpdateResult;
use crate::fee_estimator::ConfirmationTarget;
use crate::liquidity::LiquiditySource;
use crate::logger::Logger;

use crate::payment::store::{
PaymentDetails, PaymentDetailsUpdate, PaymentDirection, PaymentKind, PaymentStatus,
PaymentStore, PaymentStoreUpdateResult,
};

use crate::io::{
Expand DownExpand Up@@ -449,7 +449,7 @@ where
output_sweeper: Arc<Sweeper>,
network_graph: Arc<Graph>,
liquidity_source: Option<Arc<LiquiditySource<Arc<Logger>>>>,
payment_store: Arc<PaymentStore<L>>,
payment_store: Arc<PaymentStore>,
peer_store: Arc<PeerStore<L>>,
runtime: Arc<RwLock<Option<Arc<tokio::runtime::Runtime>>>>,
logger: L,
Expand All@@ -466,7 +466,7 @@ where
channel_manager: Arc<ChannelManager>, connection_manager: Arc<ConnectionManager<L>>,
output_sweeper: Arc<Sweeper>, network_graph: Arc<Graph>,
liquidity_source: Option<Arc<LiquiditySource<Arc<Logger>>>>,
payment_store: Arc<PaymentStore<L>>, peer_store: Arc<PeerStore<L>>,
payment_store: Arc<PaymentStore>, peer_store: Arc<PeerStore<L>>,
runtime: Arc<RwLock<Option<Arc<tokio::runtime::Runtime>>>>, logger: L, config: Arc<Config>,
) -> Self {
Self {
Expand DownExpand Up@@ -906,12 +906,11 @@ where
};

match self.payment_store.update(&update) {
Ok(PaymentStoreUpdateResult::Updated)
| Ok(PaymentStoreUpdateResult::Unchanged) => (
Ok(DataStoreUpdateResult::Updated) | Ok(DataStoreUpdateResult::Unchanged) => (
// No need to do anything if the idempotent update was applied, which might
// be the result of a replayed event.
),
Ok(PaymentStoreUpdateResult::NotFound) => {
Ok(DataStoreUpdateResult::NotFound) => {
log_error!(
self.logger,
"Claimed payment with ID {} couldn't be found in store",
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
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
18 changes: 12 additions & 6 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,21 +18,23 @@ use crate::gossip::GossipSource;
use crate::io::sqlite_store::SqliteStore;
use crate::io::utils::{read_node_metrics, write_node_metrics};
use crate::io::vss_store::VssStore;
use crate::io::{
self, PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE, PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE,
};
use crate::liquidity::{
LSPS1ClientConfig, LSPS2ClientConfig, LSPS2ServiceConfig, LiquiditySourceBuilder,
};
use crate::logger::{log_error, log_info, LdkLogger, LogLevel, LogWriter, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::store::PaymentStore;
use crate::peer_store::PeerStore;
use crate::tx_broadcaster::TransactionBroadcaster;
use crate::types::{
ChainMonitor, ChannelManager, DynStore, GossipSync, Graph, KeysManager, MessageRouter,
OnionMessenger, PeerManager,
OnionMessenger, PaymentStore, PeerManager,
};
use crate::wallet::persist::KVStoreWalletPersister;
use crate::wallet::Wallet;
use crate::{io, Node, NodeMetrics};
use crate::{Node, NodeMetrics};

use lightning::chain::{chainmonitor, BestBlock, Watch};
use lightning::io::Cursor;
Expand DownExpand Up@@ -1015,9 +1017,13 @@ fn build_with_store_internal(
let fee_estimator = Arc::new(OnchainFeeEstimator::new());

let payment_store = match io::utils::read_payments(Arc::clone(&kv_store), Arc::clone(&logger)) {
Ok(payments) => {
Arc::new(PaymentStore::new(payments, Arc::clone(&kv_store), Arc::clone(&logger)))
},
Ok(payments) => Arc::new(PaymentStore::new(
payments,
PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE.to_string(),
PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE.to_string(),
Arc::clone(&kv_store),
Arc::clone(&logger),
)),
Err(_) => {
return Err(BuildError::ReadFailed);
},
Expand Down
287 changes: 287 additions & 0 deletions src/data_store.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,287 @@
// This file is Copyright its original authors, visible in version control history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
// accordance with one or both of these licenses.

use crate::logger::{log_error, LdkLogger};
use crate::types::DynStore;
use crate::Error;

use lightning::util::ser::{Readable, Writeable};

use std::collections::hash_map;
use std::collections::HashMap;
use std::ops::Deref;
use std::sync::{Arc, Mutex};

pub(crate) trait StorableObject: Clone + Readable + Writeable {
type Id: StorableObjectId;
type Update: StorableObjectUpdate<Self>;

fn id(&self) -> Self::Id;
fn update(&mut self, update: &Self::Update) -> bool;
fn to_update(&self) -> Self::Update;
}

pub(crate) trait StorableObjectId: std::hash::Hash + PartialEq + Eq {
fn encode_to_hex_str(&self) -> String;
}

pub(crate) trait StorableObjectUpdate<SO: StorableObject> {
fn id(&self) -> SO::Id;
}

#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub(crate) enum DataStoreUpdateResult {
Updated,
Unchanged,
NotFound,
}

pub(crate) struct DataStore<SO: StorableObject, L: Deref>
where
L::Target: LdkLogger,
{
objects: Mutex<HashMap<SO::Id, SO>>,
primary_namespace: String,
secondary_namespace: String,
kv_store: Arc<DynStore>,
logger: L,
}

impl<SO: StorableObject, L: Deref> DataStore<SO, L>
where
L::Target: LdkLogger,
{
pub(crate) fn new(
objects: Vec<SO>, primary_namespace: String, secondary_namespace: String,
kv_store: Arc<DynStore>, logger: L,
) -> Self {
let objects =
Mutex::new(HashMap::from_iter(objects.into_iter().map(|obj| (obj.id(), obj))));
Self { objects, primary_namespace, secondary_namespace, kv_store, logger }
}

pub(crate) fn insert(&self, object: SO) -> Result<bool, Error> {
let mut locked_objects = self.objects.lock().unwrap();

self.persist(&object)?;
let updated = locked_objects.insert(object.id(), object).is_some();
Comment on lines +70 to +71

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the order matter here? The opposite order is used in insert_or_update, so there we could have the object in memory but fail persisting.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, this one used to be the other way around, but I changed it here (actually should be the only behavioral diff I snuck in, IIRC), exactly because it would be preferable to not update the in-memory version if persistence failed. However, for insert_or_update/update we won't know whether the update is necessary at all until StorableObject::update returns, which is why we unfortunately can't first persist.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For insert_or_update/update, it seems we log an error but continue. I suppose this predates the PR, but I wonder if we should do something else like have a queue of ids that still need persistence. Though if we eventually crash that information would be loss. Maybe this is more of a storage implementation concern.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, we could do that eventually, although it probably would somehow need to fit into a "halt everything on (remote) persistence failure, and resume/restart once we reestablish connectivity" scheme.

Ok(updated)
}

pub(crate) fn insert_or_update(&self, object: SO) -> Result<bool, Error> {
let mut locked_objects = self.objects.lock().unwrap();

let updated;
match locked_objects.entry(object.id()) {
hash_map::Entry::Occupied(mut e) => {
let update = object.to_update();
updated = e.get_mut().update(&update);
if updated {
self.persist(&e.get())?;
}
},
hash_map::Entry::Vacant(e) => {
e.insert(object.clone());
self.persist(&object)?;
updated = true;
},
}

Ok(updated)
}

pub(crate) fn remove(&self, id: &SO::Id) -> Result<(), Error> {
let removed = self.objects.lock().unwrap().remove(id).is_some();
if removed {
let store_key = id.encode_to_hex_str();
self.kv_store
.remove(&self.primary_namespace, &self.secondary_namespace, &store_key, false)
.map_err(|e| {
log_error!(
self.logger,
"Removing object data for key {}/{}/{} failed due to: {}",
&self.primary_namespace,
&self.secondary_namespace,
store_key,
e
);
Error::PersistenceFailed
})?;
}
Ok(())
}

pub(crate) fn get(&self, id: &SO::Id) -> Option<SO> {
self.objects.lock().unwrap().get(id).cloned()
}

pub(crate) fn update(&self, update: &SO::Update) -> Result<DataStoreUpdateResult, Error> {
let mut locked_objects = self.objects.lock().unwrap();

if let Some(object) = locked_objects.get_mut(&update.id()) {
let updated = object.update(update);
if updated {
self.persist(&object)?;
Ok(DataStoreUpdateResult::Updated)
} else {
Ok(DataStoreUpdateResult::Unchanged)
}
} else {
Ok(DataStoreUpdateResult::NotFound)
}
}

pub(crate) fn list_filter<F: FnMut(&&SO) -> bool>(&self, f: F) -> Vec<SO> {
self.objects.lock().unwrap().values().filter(f).cloned().collect::<Vec<SO>>()
}

fn persist(&self, object: &SO) -> Result<(), Error> {
let store_key = object.id().encode_to_hex_str();
let data = object.encode();
self.kv_store
.write(&self.primary_namespace, &self.secondary_namespace, &store_key, &data)
.map_err(|e| {
log_error!(
self.logger,
"Write for key {}/{}/{} failed due to: {}",
&self.primary_namespace,
&self.secondary_namespace,
store_key,
e
);
Error::PersistenceFailed
})?;
Ok(())
}
}

#[cfg(test)]
mod tests {
use lightning::impl_writeable_tlv_based;
use lightning::util::test_utils::{TestLogger, TestStore};

use crate::hex_utils;

use super::*;

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct TestObjectId {
id: [u8; 4],
}

impl StorableObjectId for TestObjectId {
fn encode_to_hex_str(&self) -> String {
hex_utils::to_string(&self.id)
}
}
impl_writeable_tlv_based!(TestObjectId, { (0, id, required) });

struct TestObjectUpdate {
id: TestObjectId,
data: [u8; 3],
}
impl StorableObjectUpdate<TestObject> for TestObjectUpdate {
fn id(&self) -> TestObjectId {
self.id
}
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct TestObject {
id: TestObjectId,
data: [u8; 3],
}

impl StorableObject for TestObject {
type Id = TestObjectId;
type Update = TestObjectUpdate;

fn id(&self) -> Self::Id {
self.id
}

fn update(&mut self, update: &Self::Update) -> bool {
if self.data != update.data {
self.data = update.data;
true
} else {
false
}
}

fn to_update(&self) -> Self::Update {
Self::Update { id: self.id, data: self.data }
}
}

impl_writeable_tlv_based!(TestObject, {
(0, id, required),
(2, data, required),
});

#[test]
fn data_is_persisted() {
let store: Arc<DynStore> = Arc::new(TestStore::new(false));
let logger = Arc::new(TestLogger::new());
let primary_namespace = "datastore_test_primary".to_string();
let secondary_namespace = "datastore_test_secondary".to_string();
let data_store: DataStore<TestObject, Arc<TestLogger>> = DataStore::new(
Vec::new(),
primary_namespace.clone(),
secondary_namespace.clone(),
Arc::clone(&store),
logger,
);

let id = TestObjectId { id: [42u8; 4] };
assert!(data_store.get(&id).is_none());

let store_key = id.encode_to_hex_str();

// Check we start empty.
assert!(store.read(&primary_namespace, &secondary_namespace, &store_key).is_err());

// Check we successfully store an object and return `false`
let object = TestObject { id, data: [23u8; 3] };
assert_eq!(Ok(false), data_store.insert(object.clone()));
assert_eq!(Some(object), data_store.get(&id));
assert!(store.read(&primary_namespace, &secondary_namespace, &store_key).is_ok());

// Test re-insertion returns `true`
let mut override_object = object.clone();
override_object.data = [24u8; 3];
assert_eq!(Ok(true), data_store.insert(override_object));
assert_eq!(Some(override_object), data_store.get(&id));

// Check update returns `Updated`
let update = TestObjectUpdate { id, data: [25u8; 3] };
assert_eq!(Ok(DataStoreUpdateResult::Updated), data_store.update(&update));
assert_eq!(data_store.get(&id).unwrap().data, [25u8; 3]);

// Check no-op update yields `Unchanged`
let update = TestObjectUpdate { id, data: [25u8; 3] };
assert_eq!(Ok(DataStoreUpdateResult::Unchanged), data_store.update(&update));

// Check bogus update yields `NotFound`
let bogus_id = TestObjectId { id: [84u8; 4] };
let update = TestObjectUpdate { id: bogus_id, data: [12u8; 3] };
assert_eq!(Ok(DataStoreUpdateResult::NotFound), data_store.update(&update));

// Check `insert_or_update` inserts unknown objects
let iou_id = TestObjectId { id: [55u8; 4] };
let iou_object = TestObject { id: iou_id, data: [34u8; 3] };
assert_eq!(Ok(true), data_store.insert_or_update(iou_object.clone()));

// Check `insert_or_update` doesn't update the same object
assert_eq!(Ok(false), data_store.insert_or_update(iou_object.clone()));

// Check `insert_or_update` updates if object changed
let mut new_iou_object = iou_object;
new_iou_object.data[0] += 1;
assert_eq!(Ok(true), data_store.insert_or_update(new_iou_object));
}
}
13 changes: 6 additions & 7 deletions src/event.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,7 +5,7 @@
// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
// accordance with one or both of these licenses.

use crate::types::{CustomTlvRecord, DynStore, Sweeper, Wallet};
use crate::types::{CustomTlvRecord, DynStore, PaymentStore, Sweeper, Wallet};

use crate::{
hex_utils, BumpTransactionEventHandler, ChannelManager, Error, Graph, PeerInfo, PeerStore,
Expand All@@ -14,13 +14,13 @@ use crate::{

use crate::config::{may_announce_channel, Config};
use crate::connection::ConnectionManager;
use crate::data_store::DataStoreUpdateResult;
use crate::fee_estimator::ConfirmationTarget;
use crate::liquidity::LiquiditySource;
use crate::logger::Logger;

use crate::payment::store::{
PaymentDetails, PaymentDetailsUpdate, PaymentDirection, PaymentKind, PaymentStatus,
PaymentStore, PaymentStoreUpdateResult,
};

use crate::io::{
Expand DownExpand Up@@ -449,7 +449,7 @@ where
output_sweeper: Arc<Sweeper>,
network_graph: Arc<Graph>,
liquidity_source: Option<Arc<LiquiditySource<Arc<Logger>>>>,
payment_store: Arc<PaymentStore<L>>,
payment_store: Arc<PaymentStore>,
peer_store: Arc<PeerStore<L>>,
runtime: Arc<RwLock<Option<Arc<tokio::runtime::Runtime>>>>,
logger: L,
Expand All@@ -466,7 +466,7 @@ where
channel_manager: Arc<ChannelManager>, connection_manager: Arc<ConnectionManager<L>>,
output_sweeper: Arc<Sweeper>, network_graph: Arc<Graph>,
liquidity_source: Option<Arc<LiquiditySource<Arc<Logger>>>>,
payment_store: Arc<PaymentStore<L>>, peer_store: Arc<PeerStore<L>>,
payment_store: Arc<PaymentStore>, peer_store: Arc<PeerStore<L>>,
runtime: Arc<RwLock<Option<Arc<tokio::runtime::Runtime>>>>, logger: L, config: Arc<Config>,
) -> Self {
Self {
Expand DownExpand Up@@ -906,12 +906,11 @@ where
};

match self.payment_store.update(&update) {
Ok(PaymentStoreUpdateResult::Updated)
| Ok(PaymentStoreUpdateResult::Unchanged) => (
Ok(DataStoreUpdateResult::Updated) | Ok(DataStoreUpdateResult::Unchanged) => (
// No need to do anything if the idempotent update was applied, which might
// be the result of a replayed event.
),
Ok(PaymentStoreUpdateResult::NotFound) => {
Ok(DataStoreUpdateResult::NotFound) => {
log_error!(
self.logger,
"Claimed payment with ID {} couldn't be found in store",
Expand Down
Loading