From 43f1046b5b812e432e20d5a707978117e11c40a9 Mon Sep 17 00:00:00 2001
From: Jono Wenger <jono@elixxir.io>
Date: Tue, 13 Sep 2022 10:29:32 -0700
Subject: [PATCH] Fix WaitForNetwork

---
 examples/sendE2E/sender.html |  2 +-
 examples/sendE2E/xxdk.js     | 53 ++++++++++++++++++------------------
 wasm/follow.go               | 13 +++++++--
 wasm/identity.go             |  4 +--
 4 files changed, 41 insertions(+), 31 deletions(-)

diff --git a/examples/sendE2E/sender.html b/examples/sendE2E/sender.html
index b84fa827..727b59eb 100644
--- a/examples/sendE2E/sender.html
+++ b/examples/sendE2E/sender.html
@@ -38,7 +38,7 @@
             const stopNetworkFollowerBtn = document.getElementById("stopNetworkFollowerBtn")
 
             // Client specific parameters
-            const recipientContactFile = '<xxc(2)I71lyX8LvKP6cJhedliFLIKzXN/2ArmBAfAxkk1QapADrgZ7Ugdw/BAr6RDo4K2MfHn7e06Kru7jW05ROtaaoNSyMIB3R77BIJy7xB/fvkzteTpxxmHtZdXPt9UpYVA9WKzbM57vkmy+U6BlRJIrN97tAlWbODIG1FGpjWI/BCdqwaLgu0wTYLzzEw38NNyax0E2MnvURgQoSfnX5V+m+Qd2sJBqfBKi9tlLuNcaFI+TGyKGbZdSs4AZdiL/Xm94w1/id4SDEoV73RaJb3RH+W+rEMIl1SnZ4U6Ifo39cZfRKevL2mXUZj/SE0NWGl4+10Jovy0Hp6NoW2iMH4zB30xv3fqyp8ATAYXYYO5ToFmHvP1fRLq7TKa+WtGnO70uiykBaYl219WcGYIz4jXDYyN3yNnOhihKo2tauyC0qGeGCSoACDxvzLGTHxHkS/cDA92L0MEsiXy3HIuv5+OYZBuiWl1dLxjkUKKo4f3VyDUaWjrlUFqVO95X29+Zuw++AK1TVnWtt/F4J+L91hwEfDGxYn5f2I6tNKLXnyXlPVDpa1EE6+d1LWznfXVHHzL58lBIK0Yk9MKGHQAAAgA7OaXVXCYpP2SfHIEp3s0tRA==xxc>';
+            const recipientContactFile = '<xxc(2)vL/3ePQKC3YZ/j5DjIdLC9TwEgB19PPvNSiJzv+TR4oDrgZ7Ugdw/BAr6Y/Ci8g9/nJQV3MVVMwJGVKoQSq4LVrJum1JBNHVwRJl/03bzAhV+YUnDYXEva1krP31gZ25pwuOlLqKyxy4gxicZZOKv5xcaqgIZeALbIUxpgAclHT1S/U1OTjdC9GnZoi+Ta/ftZhFcB/b8YIqLnp9+N9QGBCqYImr371cfhnSVSVNUhgKEReJkvQzfeeLXp6LHs9al9jvq8OR/uMLzjP+MqPaVc8/AXoPUMTSsQMhTQrbcgN7auK4mP0RcbIviKU1MIt8RGXrhLgPa2l1V1IinuMkpKoqwkolR13ZN6evw3rl57K7XEwK8di5bs2EisOceLd+IJPhQUxceaytKGCuqqOTlOj8f+tet4yZ92h//u3tWIIB7IoLyipxIj1Tq6Q+UDarf5+ReqIupTmiOjIxPJZxRqoMZGO45CcyPPdFEEMhozbH0WxyCruwKD352ZG9aKGoq97VclLxDOgE7Dx/oGmA3YvaJK5lUQPGO5egLHn23qmP7IN/8Pxn6D84Lovt8YddR4jjlIuY4qAhdAAAAgA7HsmlZr0oNSUMhb6OyUMn0A==xxc>';
             const myContactFileName = '';
             const statePath = 'statePathSender';
             const statePass = 'password';
diff --git a/examples/sendE2E/xxdk.js b/examples/sendE2E/xxdk.js
index 204036d5..c3104816 100644
--- a/examples/sendE2E/xxdk.js
+++ b/examples/sendE2E/xxdk.js
@@ -56,7 +56,7 @@ async function SendE2e(htmlConsole, stopNetworkFollowerBtn, ndf,
         htmlConsole.log("Getting reception identity.")
         identity = LoadReceptionIdentity(identityStorageKey, net.GetID());
     } catch (e) {
-        htmlConsole.log("No reception identity found. Generating a new one: " + e)
+        htmlConsole.log("No reception identity found. Generating a new one.")
 
         // If no extant xxdk.ReceptionIdentity, generate and store a new one
         identity = net.MakeReceptionIdentity();
@@ -88,7 +88,7 @@ async function SendE2e(htmlConsole, stopNetworkFollowerBtn, ndf,
 
             htmlConsole.log("Calling confirm on contact " + dec.decode(contact))
             const rid = await e2eClient.Confirm(contact)
-            htmlConsole.log("Called confirm on round " + rid) 
+            htmlConsole.log("Called confirm on round " + rid)
         }
     }
 
@@ -109,27 +109,26 @@ async function SendE2e(htmlConsole, stopNetworkFollowerBtn, ndf,
     htmlConsole.log("Started network follower")
 
     stopNetworkFollowerBtn.style.display = 'block';
-    stopNetworkFollowerBtn.addEventListener('click', () => {
+    stopNetworkFollowerBtn.addEventListener('click', async () => {
         htmlConsole.log("Stopping network follower")
-        net.StopNetworkFollower()
-    })
-
-    // Provide a callback that will be signalled when network health status changes
-    let health = false
-    net.AddHealthCallback({
-        Callback: function (healthy) {
-            health = healthy;
+        try {
+            await net.StopNetworkFollower()
+        } catch (e) {
+            htmlConsole.log("Failed to stop network follower: " + e)
         }
-    });
+    })
 
+    // Wait for network to become healthy
     htmlConsole.log("Waiting for network to be healthy")
-    try {
-        await sleepUntil(() => health === true, 25000);
-    } catch {
-        htmlConsole.error("Timed out. Network is not healthy: " + health)
-        throw new Error("Timed out. Network is not healthy: " + health)
-    }
-    htmlConsole.log("Network is healthy: " + health)
+    net.WaitForNetwork(25000).then(
+        () => {
+            htmlConsole.log("Network is healthy")
+        },
+        () => {
+            htmlConsole.error("Timed out. Network is not healthy.")
+            throw new Error("Timed out. Network is not healthy.")
+        }
+    )
 
 
     ////////////////////////////////////////////////////////////////////////////
@@ -160,7 +159,7 @@ async function SendE2e(htmlConsole, stopNetworkFollowerBtn, ndf,
     if (recipientContactFile !== '') {
         let exists = false;
         htmlConsole.log("getting ID from contact")
-        const recipientContactID = GetIDFromContact(recipientContactFile);
+        const recipientContactID = GetIDFromContact(enc.encode(recipientContactFile));
         const recipientContactIDBase64 = Uint8ArrayToBase64(recipientContactID)
 
         htmlConsole.log("Checking if partner " + recipientContactIDBase64 + " exists")
@@ -180,10 +179,10 @@ async function SendE2e(htmlConsole, stopNetworkFollowerBtn, ndf,
 
         // If the partner does not exist, send a request
         if (exists === false) {
-            htmlConsole.log("Partner does not exist, Request being sent to " + recipientContactIDBase64) 
+            htmlConsole.log("Partner does not exist, Request being sent to " + recipientContactIDBase64)
             const factList = enc.encode('[]')
             const rid = await e2eClient.Request(enc.encode(recipientContactFile), factList)
-            htmlConsole.log("Request sent on round " + rid) 
+            htmlConsole.log("Request sent on round " + rid)
 
 
             htmlConsole.log("Waiting to receive confirmation.")
@@ -195,12 +194,14 @@ async function SendE2e(htmlConsole, stopNetworkFollowerBtn, ndf,
                 throw new Error("Did not receive confirm: " + confirm)
             }
 
+            console.log("confirmContact: " + confirmContact)
+            console.log("confirmContact: " + dec.decode(confirmContact))
             const confirmContactID = GetIDFromContact(confirmContact)
             if (!Uint8ArrayEquals(recipientContactID, confirmContactID)) {
                 htmlConsole.log("contact ID from confirmation " +
                     Uint8ArrayToBase64(confirmContactID) +
-                    " does not match recipient ID " + recipientContactIDBase64) 
-               throw new Error("contact ID from confirmation " +
+                    " does not match recipient ID " + recipientContactIDBase64)
+                throw new Error("contact ID from confirmation " +
                     Uint8ArrayToBase64(confirmContactID) +
                     " does not match recipient ID " + recipientContactIDBase64)
             }
@@ -215,10 +216,10 @@ async function SendE2e(htmlConsole, stopNetworkFollowerBtn, ndf,
         // Test message
         const msgBody = "If this message is sent successfully, we'll have established contact with the recipient."
 
-        htmlConsole.log("Sending E2E message: " + msgBody) 
+        htmlConsole.log("Sending E2E message: " + msgBody)
         const e2eSendReport = await e2eClient.SendE2E(2, recipientContactID, enc.encode(msgBody), params)
 
-        htmlConsole.log("Send E2e message. Report: " + dec.decode(e2eSendReport)) 
+        htmlConsole.log("Send E2e message. Report: " + dec.decode(e2eSendReport))
     } else {
         htmlConsole.log("No recipient specified. Waiting for request")
     }
diff --git a/wasm/follow.go b/wasm/follow.go
index a21912fa..f3a4e7bd 100644
--- a/wasm/follow.go
+++ b/wasm/follow.go
@@ -88,9 +88,18 @@ func (c *Cmix) StopNetworkFollower(js.Value, []js.Value) interface{} {
 //  - args[0] - timeout when stopping threads in milliseconds (int)
 //
 // Returns:
-//  - returns true if the network is healthy (boolean)
+//  - A promise that resolves if the network is healthy and rejects if the
+//    network is not healthy.
 func (c *Cmix) WaitForNetwork(_ js.Value, args []js.Value) interface{} {
-	return c.api.WaitForNetwork(args[0].Int())
+	promiseFn := func(resolve, reject func(args ...interface{}) js.Value) {
+		if c.api.WaitForNetwork(args[0].Int()) {
+			resolve()
+		} else {
+			reject()
+		}
+	}
+
+	return utils.CreatePromise(promiseFn)
 }
 
 // NetworkFollowerStatus gets the state of the network follower. It returns a
diff --git a/wasm/identity.go b/wasm/identity.go
index c94de98d..83911a93 100644
--- a/wasm/identity.go
+++ b/wasm/identity.go
@@ -135,13 +135,13 @@ func GetContactFromReceptionIdentity(_ js.Value, args []js.Value) interface{} {
 // GetIDFromContact returns the ID in the [contact.Contact] object.
 //
 // Parameters:
-//  - args[0] - marshalled bytes of [contact.Contact] (string)
+//  - args[0] - marshalled bytes of [contact.Contact] (Uint8Array)
 //
 // Returns:
 //  - marshalled [id.ID] object (Uint8Array)
 //  - throws a TypeError if loading the ID from the contact file fails
 func GetIDFromContact(_ js.Value, args []js.Value) interface{} {
-	cID, err := bindings.GetIDFromContact([]byte(args[0].String()))
+	cID, err := bindings.GetIDFromContact(utils.CopyBytesToGo(args[0]))
 	if err != nil {
 		utils.Throw(utils.TypeError, err)
 		return nil
-- 
GitLab