lightninglabs / lightning-node-connect

MIT License
78 stars 22 forks source link

wasm: allow non-global scope callbacks #72

Closed jamaljsr closed 1 year ago

jamaljsr commented 1 year ago

Currently, the JS callbacks for onlocalprivcreate, onremotekeyreceive, and onauthdata must be on the JS global scope for the WASM to call them. This adds a potential for race conditions when connecting to multiple nodes simultaneously because each connection will share the same callback functions that are defined on the global scope. Depending on the order in which the connections are established and callbacks are called, the local/remote keys returned may be associated with the wrong connection.

This PR allows the app to specify callbacks nested under a JS object, ex: '--onauthdata=myapp.onAuthData'. The app would have needed to create the nested object like this, for example:

window['myapp'] = {
  onAuthData: function(data) { ... }
}

The app can also leverage the support for namespaces by placing the callbacks on a JS object using the same name as the namespace, ex '--onauthdata=' + namespace + '.onAuthData'. This would eliminate the chances of a race condition because each connection would have its own callback function defined under a namespace scoped JS object.

I implemented this in a way that maintains backward compatibility, so apps can continue to use '--onauthdata=onAuthData' with the callback defined on the global scope if they choose to. It just now supports the option of using non-global scoped callbacks to handle the scenarios where multiple connections are established concurrently.