mirror of https://github.com/status-im/go-waku.git
feat: c-sharp example (#222)
This commit is contained in:
parent
b294ee6f6f
commit
f1a40fad73
|
@ -7,91 +7,12 @@
|
|||
#include "nxjson.c"
|
||||
#include "main.h"
|
||||
|
||||
|
||||
char *alicePrivKey = "0x4f012057e1a1458ce34189cb27daedbbe434f3df0825c1949475dec786e2c64e";
|
||||
char *alicePubKey = "0x0440f05847c4c7166f57ae8ecaaf72d31bddcbca345e26713ca9e26c93fb8362ddcd5ae7f4533ee956428ad08a89cd18b234c2911a3b1c7fbd1c0047610d987302";
|
||||
|
||||
|
||||
char *bobPrivKey = "0xb91d6b2df8fb6ef8b53b51b2b30a408c49d5e2b530502d58ac8f94e5c5de1453";
|
||||
char *bobPubKey = "0x045eef61a98ba1cf44a2736fac91183ea2bd86e67de20fe4bff467a71249a8a0c05f795dd7f28ced7c15eaa69c89d4212cc4f526ca5e9a62e88008f506d850cccd";
|
||||
|
||||
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
char *response;
|
||||
gowaku_set_event_callback(callBack);
|
||||
|
||||
char *configJSON = "{\"host\": \"0.0.0.0\", \"port\": 60000}";
|
||||
response = gowaku_new(configJSON); // configJSON can be NULL too to use defaults
|
||||
if (isError(response))
|
||||
return 1;
|
||||
int nodeID = getIntValue(response); // Obtain the nodeID from the response
|
||||
|
||||
|
||||
|
||||
response = gowaku_start(1); // Start the node, enabling the waku protocols
|
||||
if (isError(response))
|
||||
return 1;
|
||||
|
||||
|
||||
|
||||
response = gowaku_peerid(nodeID); // Obtain the node peerID
|
||||
if (isError(response))
|
||||
return 1;
|
||||
char *nodePeerID = getStrValue(response);
|
||||
printf("PeerID: %s\n", nodePeerID);
|
||||
|
||||
|
||||
/*
|
||||
response = gowaku_dial_peer(nodeID, "/dns4/node-01.gc-us-central1-a.wakuv2.test.statusim.net/tcp/30303/p2p/16Uiu2HAmJb2e28qLXxT5kZxVUUoJt72EMzNGXB47Rxx5hw3q4YjS", 0); // Connect to a node
|
||||
if (isError(response))
|
||||
return 1;
|
||||
*/
|
||||
|
||||
|
||||
response = gowaku_relay_subscribe(nodeID, NULL);
|
||||
if (isError(response))
|
||||
return 1;
|
||||
char *subscriptionID = getStrValue(response);
|
||||
printf("SubscriptionID: %s\n", subscriptionID);
|
||||
|
||||
|
||||
|
||||
int i = 0;
|
||||
int version = 1;
|
||||
while (true){
|
||||
i++;
|
||||
|
||||
char *msg = gowaku_utils_base64_encode("Hello World!");
|
||||
response = gowaku_encode_data(msg, ASYMMETRIC, bobPubKey, alicePrivKey, version); // Send a message encrypting it with Bob's PubK, and signing it with Alice PrivK
|
||||
if (isError(response))
|
||||
return 1;
|
||||
char *encodedData = getStrValue(response);
|
||||
|
||||
|
||||
char *contentTopic = gowaku_content_topic("example", 1, "default", "rfc26");
|
||||
|
||||
|
||||
char wakuMsg[1000];
|
||||
sprintf(wakuMsg, "{\"payload\":\"%s\",\"contentTopic\":\"%s\",\"version\":%d,\"timestamp\":%d}", encodedData, contentTopic, version, i);
|
||||
|
||||
response = gowaku_relay_publish(nodeID, wakuMsg, NULL, 0); // Broadcast a message
|
||||
if (isError(response))
|
||||
return 1;
|
||||
// char *messageID = getStrValue(response);
|
||||
|
||||
sleep(1);
|
||||
}
|
||||
|
||||
|
||||
|
||||
response = gowaku_stop(nodeID);
|
||||
if (isError(response))
|
||||
return 1;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void callBack(char *signal)
|
||||
{
|
||||
// This callback will be executed each time a new message is received
|
||||
|
@ -102,7 +23,6 @@ void callBack(char *signal)
|
|||
"type":"message",
|
||||
"event":{
|
||||
"pubsubTopic":"/waku/2/default-waku/proto",
|
||||
"subscriptionID": ".....",
|
||||
"messageID":"0x6496491e40dbe0b6c3a2198c2426b16301688a2daebc4f57ad7706115eac3ad1",
|
||||
"wakuMessage":{
|
||||
"payload":"BPABASUqWgRkgp73aW/FHIyGtJDYnStvaQvCoX9MdaNsOH39Vet0em6ipZc3lZ7kK9uFFtbJgIWfRaqTxSRjiFOPx88gXt1JeSm2SUwGSz+1gh2xTy0am8tXkc8OWSSjamdkEbXuVgAueLxHOnV3xlGwYt7nx2G5DWYqUu1BXv4yWHPOoiH2yx3fxX0OajgKGBwiMbadRNUuAUFPRM90f+bzG2y22ssHctDV/U6sXOa9ljNgpAx703Q3WIFleSRozto7ByNAdRFwWR0RGGV4l0btJXM7JpnrYcVC24dB0tJ3HVWuD0ZcwOM1zTL0wwc0hTezLHvI+f6bHSzsFGcCWIlc03KSoMjK1XENNL4dtDmSFI1DQCGgq09c2Bc3Je3Ci6XJHu+FP1F1pTnRzevv2WP8FSBJiTXpmJXdm6evB7V1Xxj4QlzQDvmHLRpBOL6PSttxf1Dc0IwC6BfZRN5g0dNmItNlS2pcY1MtZLxD5zpj",
|
||||
|
@ -116,77 +36,99 @@ void callBack(char *signal)
|
|||
const nx_json *json = nx_json_parse(signal, 0);
|
||||
const char *type = nx_json_get(json, "type")->text_value;
|
||||
|
||||
if (strcmp(type,"message") == 0){
|
||||
const char *encodedPayload = nx_json_get(nx_json_get(nx_json_get(json, "event"), "wakuMessage"), "payload")->text_value;
|
||||
int version = nx_json_get(nx_json_get(nx_json_get(json, "event"), "wakuMessage"), "version")->int_value;
|
||||
if (strcmp(type, "message") == 0)
|
||||
{
|
||||
char* msg = utils_extract_wakumessage_from_signal(json);
|
||||
char *decodedMsg = waku_decode_asymmetric(msg, bobPrivKey);
|
||||
free(msg);
|
||||
|
||||
char *decodedData = gowaku_decode_data((char*)encodedPayload, ASYMMETRIC, bobPrivKey, version);
|
||||
if(isError(decodedData)) return;
|
||||
if(isError(decodedMsg)) {
|
||||
free(decodedMsg);
|
||||
return;
|
||||
}
|
||||
|
||||
const nx_json *dataJson = nx_json_parse(decodedData, 0);
|
||||
|
||||
const nx_json *dataJson = nx_json_parse(decodedMsg, 0);
|
||||
const char *pubkey = nx_json_get(nx_json_get(dataJson, "result"), "pubkey")->text_value;
|
||||
const char *base64data = nx_json_get(nx_json_get(dataJson, "result"), "data")->text_value;
|
||||
char *data = gowaku_utils_base64_decode((char*)base64data);
|
||||
char *data = waku_utils_base64_decode((char*)base64data);
|
||||
|
||||
printf("Received \"%s\" from %s\n", getStrValue(data), pubkey);
|
||||
printf(">>> Received \"%s\" from %s\n", utils_get_str(data), pubkey);
|
||||
fflush(stdout);
|
||||
|
||||
nx_json_free(dataJson);
|
||||
free(data);
|
||||
}
|
||||
|
||||
nx_json_free(json);
|
||||
}
|
||||
|
||||
bool isError(char *input)
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
char *jsonStr = malloc(strlen(input) + 1);
|
||||
strcpy(jsonStr, input);
|
||||
const nx_json *json = nx_json_parse(jsonStr, 0);
|
||||
bool result = false;
|
||||
if (json)
|
||||
{
|
||||
const char *errTxt = nx_json_get(json, "error")->text_value;
|
||||
result = errTxt != NULL;
|
||||
if (result)
|
||||
{
|
||||
printf("ERROR: %s\n", errTxt);
|
||||
}
|
||||
}
|
||||
nx_json_free(json);
|
||||
free(jsonStr);
|
||||
return result;
|
||||
}
|
||||
char *response;
|
||||
waku_set_event_callback(callBack);
|
||||
|
||||
int getIntValue(char *input)
|
||||
{
|
||||
char *jsonStr = malloc(strlen(input) + 1);
|
||||
strcpy(jsonStr, input);
|
||||
const nx_json *json = nx_json_parse(jsonStr, 0);
|
||||
int result = -1;
|
||||
if (json)
|
||||
{
|
||||
result = nx_json_get(json, "result")->int_value;
|
||||
}
|
||||
nx_json_free(json);
|
||||
free(jsonStr);
|
||||
char *configJSON = "{\"host\": \"0.0.0.0\", \"port\": 60000}";
|
||||
response = waku_new(configJSON); // configJSON can be NULL too to use defaults
|
||||
if (isError(response))
|
||||
return 1;
|
||||
|
||||
return result;
|
||||
}
|
||||
response = waku_start(); // Start the node, enabling the waku protocols
|
||||
if (isError(response))
|
||||
return 1;
|
||||
|
||||
char* getStrValue(char *input)
|
||||
{
|
||||
char *jsonStr = malloc(strlen(input) + 1);
|
||||
strcpy(jsonStr, input);
|
||||
const nx_json *json = nx_json_parse(jsonStr, 0);
|
||||
char* result = "";
|
||||
if (json)
|
||||
response = waku_peerid(); // Obtain the node peerID
|
||||
if (isError(response))
|
||||
return 1;
|
||||
char *nodePeerID = utils_get_str(response);
|
||||
printf("PeerID: %s\n", nodePeerID);
|
||||
|
||||
|
||||
response = waku_connect("/dns4/node-01.gc-us-central1-a.wakuv2.test.statusim.net/tcp/30303/p2p/16Uiu2HAmJb2e28qLXxT5kZxVUUoJt72EMzNGXB47Rxx5hw3q4YjS", 0); // Connect to a node
|
||||
if (isError(response))
|
||||
return 1;
|
||||
|
||||
|
||||
/*
|
||||
// To see a store query in action:
|
||||
char query[1000];
|
||||
sprintf(query, "{\"pubsubTopic\":\"%s\", \"pagingOptions\":{\"pageSize\": 40, \"forward\":false}}", waku_default_pubsub_topic());
|
||||
response = waku_store_query(query, NULL, 0);
|
||||
if (isError(response))
|
||||
return 1;
|
||||
printf("%s\n",response);
|
||||
*/
|
||||
|
||||
response = waku_relay_subscribe(NULL);
|
||||
if (isError(response))
|
||||
return 1;
|
||||
|
||||
int i = 0;
|
||||
int version = 1;
|
||||
while (i < 5)
|
||||
{
|
||||
const char* text_value = nx_json_get(json, "result")->text_value;
|
||||
result = strdup(text_value);
|
||||
i++;
|
||||
|
||||
char wakuMsg[1000];
|
||||
char *msgPayload = waku_utils_base64_encode("Hello World!");
|
||||
char *contentTopic = waku_content_topic("example", 1, "default", "rfc26");
|
||||
sprintf(wakuMsg, "{\"payload\":\"%s\",\"contentTopic\":\"%s\",\"timestamp\":%d}", msgPayload, contentTopic, i);
|
||||
free(msgPayload);
|
||||
free(contentTopic);
|
||||
|
||||
|
||||
response = waku_relay_publish_enc_asymmetric(wakuMsg, NULL, bobPubKey, alicePrivKey, 0); // Broadcast via waku relay a message encrypting it with Bob's PubK, and signing it with Alice PrivK
|
||||
// response = waku_lightpush_publish_enc_asymmetric(wakuMsg, NULL, NULL, bobPubKey, alicePrivKey, 0); // Broadcast via waku lightpush a message encrypting it with Bob's PubK, and signing it with Alice PrivK
|
||||
if (isError(response))
|
||||
return 1;
|
||||
|
||||
// char *messageID = utils_get_str(response);
|
||||
// free(messageID);
|
||||
|
||||
sleep(1);
|
||||
}
|
||||
|
||||
nx_json_free(json);
|
||||
free(jsonStr);
|
||||
response = waku_stop();
|
||||
if (isError(response))
|
||||
return 1;
|
||||
|
||||
return result;
|
||||
return 0;
|
||||
}
|
||||
|
|
|
@ -2,13 +2,75 @@
|
|||
#define MAIN_H
|
||||
|
||||
#include <stdbool.h>
|
||||
#include "nxjson.c"
|
||||
|
||||
void callBack(char *signal);
|
||||
bool isError(char *input)
|
||||
{
|
||||
char *jsonStr = malloc(strlen(input) + 1);
|
||||
strcpy(jsonStr, input);
|
||||
const nx_json *json = nx_json_parse(jsonStr, 0);
|
||||
bool result = false;
|
||||
if (json)
|
||||
{
|
||||
const char *errTxt = nx_json_get(json, "error")->text_value;
|
||||
result = errTxt != NULL;
|
||||
if (result)
|
||||
{
|
||||
printf("ERROR: %s\n", errTxt);
|
||||
}
|
||||
}
|
||||
nx_json_free(json);
|
||||
free(jsonStr);
|
||||
return result;
|
||||
}
|
||||
|
||||
bool isError(char *input);
|
||||
|
||||
int getIntValue(char *input);
|
||||
char *utils_extract_wakumessage_from_signal(const nx_json *signal)
|
||||
{
|
||||
const nx_json *wakuMsgJson = nx_json_get(nx_json_get(signal, "event"), "wakuMessage");
|
||||
const char *payload = nx_json_get(wakuMsgJson, "payload")->text_value;
|
||||
const char *contentTopic = nx_json_get(wakuMsgJson, "contentTopic")->text_value;
|
||||
int version = nx_json_get(wakuMsgJson, "version")->int_value;
|
||||
long long timestamp = nx_json_get(wakuMsgJson, "timestamp")->int_value;
|
||||
char wakuMsg[1000];
|
||||
sprintf(wakuMsg, "{\"payload\":\"%s\",\"contentTopic\":\"%s\",\"timestamp\":%lld, \"version\":%d}", payload, contentTopic, timestamp, version);
|
||||
char *response = (char *)malloc(sizeof(char) * (strlen(wakuMsg) + 1));
|
||||
strcpy(response, wakuMsg);
|
||||
return response;
|
||||
}
|
||||
|
||||
char* getStrValue(char *input);
|
||||
long long utils_get_int(char *input)
|
||||
{
|
||||
char *jsonStr = malloc(strlen(input) + 1);
|
||||
strcpy(jsonStr, input);
|
||||
const nx_json *json = nx_json_parse(jsonStr, 0);
|
||||
long long result = -1;
|
||||
if (json)
|
||||
{
|
||||
result = nx_json_get(json, "result")->int_value;
|
||||
}
|
||||
nx_json_free(json);
|
||||
free(jsonStr);
|
||||
|
||||
#endif /* MAIN_H */
|
||||
return result;
|
||||
}
|
||||
|
||||
char *utils_get_str(char *input)
|
||||
{
|
||||
char *jsonStr = malloc(strlen(input) + 1);
|
||||
strcpy(jsonStr, input);
|
||||
const nx_json *json = nx_json_parse(jsonStr, 0);
|
||||
char *result = "";
|
||||
if (json)
|
||||
{
|
||||
const char *text_value = nx_json_get(json, "result")->text_value;
|
||||
result = strdup(text_value);
|
||||
}
|
||||
|
||||
nx_json_free(json);
|
||||
free(jsonStr);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
#endif /* MAIN_H */
|
|
@ -0,0 +1,402 @@
|
|||
## Ignore Visual Studio temporary files, build results, and
|
||||
## files generated by popular Visual Studio add-ons.
|
||||
##
|
||||
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
|
||||
|
||||
# User-specific files
|
||||
*.rsuser
|
||||
*.suo
|
||||
*.user
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
|
||||
# User-specific files (MonoDevelop/Xamarin Studio)
|
||||
*.userprefs
|
||||
|
||||
# Mono auto generated files
|
||||
mono_crash.*
|
||||
|
||||
# Build results
|
||||
[Dd]ebug/
|
||||
[Dd]ebugPublic/
|
||||
[Rr]elease/
|
||||
[Rr]eleases/
|
||||
x64/
|
||||
x86/
|
||||
[Ww][Ii][Nn]32/
|
||||
[Aa][Rr][Mm]/
|
||||
[Aa][Rr][Mm]64/
|
||||
bld/
|
||||
[Bb]in/
|
||||
[Oo]bj/
|
||||
[Ll]og/
|
||||
[Ll]ogs/
|
||||
|
||||
# Visual Studio 2015/2017 cache/options directory
|
||||
.vs/
|
||||
# Uncomment if you have tasks that create the project's static files in wwwroot
|
||||
#wwwroot/
|
||||
|
||||
# Visual Studio 2017 auto generated files
|
||||
Generated\ Files/
|
||||
|
||||
# MSTest test Results
|
||||
[Tt]est[Rr]esult*/
|
||||
[Bb]uild[Ll]og.*
|
||||
|
||||
# NUnit
|
||||
*.VisualState.xml
|
||||
TestResult.xml
|
||||
nunit-*.xml
|
||||
|
||||
# Build Results of an ATL Project
|
||||
[Dd]ebugPS/
|
||||
[Rr]eleasePS/
|
||||
dlldata.c
|
||||
|
||||
# Benchmark Results
|
||||
BenchmarkDotNet.Artifacts/
|
||||
|
||||
# .NET Core
|
||||
project.lock.json
|
||||
project.fragment.lock.json
|
||||
artifacts/
|
||||
|
||||
# ASP.NET Scaffolding
|
||||
ScaffoldingReadMe.txt
|
||||
|
||||
# StyleCop
|
||||
StyleCopReport.xml
|
||||
|
||||
# Files built by Visual Studio
|
||||
*_i.c
|
||||
*_p.c
|
||||
*_h.h
|
||||
*.ilk
|
||||
*.meta
|
||||
*.obj
|
||||
*.iobj
|
||||
*.pch
|
||||
*.pdb
|
||||
*.ipdb
|
||||
*.pgc
|
||||
*.pgd
|
||||
*.rsp
|
||||
*.sbr
|
||||
*.tlb
|
||||
*.tli
|
||||
*.tlh
|
||||
*.tmp
|
||||
*.tmp_proj
|
||||
*_wpftmp.csproj
|
||||
*.log
|
||||
*.tlog
|
||||
*.vspscc
|
||||
*.vssscc
|
||||
.builds
|
||||
*.pidb
|
||||
*.svclog
|
||||
*.scc
|
||||
|
||||
# Chutzpah Test files
|
||||
_Chutzpah*
|
||||
|
||||
# Visual C++ cache files
|
||||
ipch/
|
||||
*.aps
|
||||
*.ncb
|
||||
*.opendb
|
||||
*.opensdf
|
||||
*.sdf
|
||||
*.cachefile
|
||||
*.VC.db
|
||||
*.VC.VC.opendb
|
||||
|
||||
# Visual Studio profiler
|
||||
*.psess
|
||||
*.vsp
|
||||
*.vspx
|
||||
*.sap
|
||||
|
||||
# Visual Studio Trace Files
|
||||
*.e2e
|
||||
|
||||
# TFS 2012 Local Workspace
|
||||
$tf/
|
||||
|
||||
# Guidance Automation Toolkit
|
||||
*.gpState
|
||||
|
||||
# ReSharper is a .NET coding add-in
|
||||
_ReSharper*/
|
||||
*.[Rr]e[Ss]harper
|
||||
*.DotSettings.user
|
||||
|
||||
# TeamCity is a build add-in
|
||||
_TeamCity*
|
||||
|
||||
# DotCover is a Code Coverage Tool
|
||||
*.dotCover
|
||||
|
||||
# AxoCover is a Code Coverage Tool
|
||||
.axoCover/*
|
||||
!.axoCover/settings.json
|
||||
|
||||
# Coverlet is a free, cross platform Code Coverage Tool
|
||||
coverage*.json
|
||||
coverage*.xml
|
||||
coverage*.info
|
||||
|
||||
# Visual Studio code coverage results
|
||||
*.coverage
|
||||
*.coveragexml
|
||||
|
||||
# NCrunch
|
||||
_NCrunch_*
|
||||
.*crunch*.local.xml
|
||||
nCrunchTemp_*
|
||||
|
||||
# MightyMoose
|
||||
*.mm.*
|
||||
AutoTest.Net/
|
||||
|
||||
# Web workbench (sass)
|
||||
.sass-cache/
|
||||
|
||||
# Installshield output folder
|
||||
[Ee]xpress/
|
||||
|
||||
# DocProject is a documentation generator add-in
|
||||
DocProject/buildhelp/
|
||||
DocProject/Help/*.HxT
|
||||
DocProject/Help/*.HxC
|
||||
DocProject/Help/*.hhc
|
||||
DocProject/Help/*.hhk
|
||||
DocProject/Help/*.hhp
|
||||
DocProject/Help/Html2
|
||||
DocProject/Help/html
|
||||
|
||||
# Click-Once directory
|
||||
publish/
|
||||
|
||||
# Publish Web Output
|
||||
*.[Pp]ublish.xml
|
||||
*.azurePubxml
|
||||
# Note: Comment the next line if you want to checkin your web deploy settings,
|
||||
# but database connection strings (with potential passwords) will be unencrypted
|
||||
*.pubxml
|
||||
*.publishproj
|
||||
|
||||
# Microsoft Azure Web App publish settings. Comment the next line if you want to
|
||||
# checkin your Azure Web App publish settings, but sensitive information contained
|
||||
# in these scripts will be unencrypted
|
||||
PublishScripts/
|
||||
|
||||
# NuGet Packages
|
||||
*.nupkg
|
||||
# NuGet Symbol Packages
|
||||
*.snupkg
|
||||
# The packages folder can be ignored because of Package Restore
|
||||
**/[Pp]ackages/*
|
||||
# except build/, which is used as an MSBuild target.
|
||||
!**/[Pp]ackages/build/
|
||||
# Uncomment if necessary however generally it will be regenerated when needed
|
||||
#!**/[Pp]ackages/repositories.config
|
||||
# NuGet v3's project.json files produces more ignorable files
|
||||
*.nuget.props
|
||||
*.nuget.targets
|
||||
|
||||
# Microsoft Azure Build Output
|
||||
csx/
|
||||
*.build.csdef
|
||||
|
||||
# Microsoft Azure Emulator
|
||||
ecf/
|
||||
rcf/
|
||||
|
||||
# Windows Store app package directories and files
|
||||
AppPackages/
|
||||
BundleArtifacts/
|
||||
Package.StoreAssociation.xml
|
||||
_pkginfo.txt
|
||||
*.appx
|
||||
*.appxbundle
|
||||
*.appxupload
|
||||
|
||||
# Visual Studio cache files
|
||||
# files ending in .cache can be ignored
|
||||
*.[Cc]ache
|
||||
# but keep track of directories ending in .cache
|
||||
!?*.[Cc]ache/
|
||||
|
||||
# Others
|
||||
ClientBin/
|
||||
~$*
|
||||
*~
|
||||
*.dbmdl
|
||||
*.dbproj.schemaview
|
||||
*.jfm
|
||||
*.pfx
|
||||
*.publishsettings
|
||||
orleans.codegen.cs
|
||||
|
||||
# Including strong name files can present a security risk
|
||||
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
|
||||
#*.snk
|
||||
|
||||
# Since there are multiple workflows, uncomment next line to ignore bower_components
|
||||
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
|
||||
#bower_components/
|
||||
|
||||
# RIA/Silverlight projects
|
||||
Generated_Code/
|
||||
|
||||
# Backup & report files from converting an old project file
|
||||
# to a newer Visual Studio version. Backup files are not needed,
|
||||
# because we have git ;-)
|
||||
_UpgradeReport_Files/
|
||||
Backup*/
|
||||
UpgradeLog*.XML
|
||||
UpgradeLog*.htm
|
||||
ServiceFabricBackup/
|
||||
*.rptproj.bak
|
||||
|
||||
# SQL Server files
|
||||
*.mdf
|
||||
*.ldf
|
||||
*.ndf
|
||||
|
||||
# Business Intelligence projects
|
||||
*.rdl.data
|
||||
*.bim.layout
|
||||
*.bim_*.settings
|
||||
*.rptproj.rsuser
|
||||
*- [Bb]ackup.rdl
|
||||
*- [Bb]ackup ([0-9]).rdl
|
||||
*- [Bb]ackup ([0-9][0-9]).rdl
|
||||
|
||||
# Microsoft Fakes
|
||||
FakesAssemblies/
|
||||
|
||||
# GhostDoc plugin setting file
|
||||
*.GhostDoc.xml
|
||||
|
||||
# Node.js Tools for Visual Studio
|
||||
.ntvs_analysis.dat
|
||||
node_modules/
|
||||
|
||||
# Visual Studio 6 build log
|
||||
*.plg
|
||||
|
||||
# Visual Studio 6 workspace options file
|
||||
*.opt
|
||||
|
||||
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
|
||||
*.vbw
|
||||
|
||||
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
|
||||
*.vbp
|
||||
|
||||
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
|
||||
*.dsw
|
||||
*.dsp
|
||||
|
||||
# Visual Studio 6 technical files
|
||||
*.ncb
|
||||
*.aps
|
||||
|
||||
# Visual Studio LightSwitch build output
|
||||
**/*.HTMLClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/ModelManifest.xml
|
||||
**/*.Server/GeneratedArtifacts
|
||||
**/*.Server/ModelManifest.xml
|
||||
_Pvt_Extensions
|
||||
|
||||
# Paket dependency manager
|
||||
.paket/paket.exe
|
||||
paket-files/
|
||||
|
||||
# FAKE - F# Make
|
||||
.fake/
|
||||
|
||||
# CodeRush personal settings
|
||||
.cr/personal
|
||||
|
||||
# Python Tools for Visual Studio (PTVS)
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# Cake - Uncomment if you are using it
|
||||
# tools/**
|
||||
# !tools/packages.config
|
||||
|
||||
# Tabs Studio
|
||||
*.tss
|
||||
|
||||
# Telerik's JustMock configuration file
|
||||
*.jmconfig
|
||||
|
||||
# BizTalk build output
|
||||
*.btp.cs
|
||||
*.btm.cs
|
||||
*.odx.cs
|
||||
*.xsd.cs
|
||||
|
||||
# OpenCover UI analysis results
|
||||
OpenCover/
|
||||
|
||||
# Azure Stream Analytics local run output
|
||||
ASALocalRun/
|
||||
|
||||
# MSBuild Binary and Structured Log
|
||||
*.binlog
|
||||
|
||||
# NVidia Nsight GPU debugger configuration file
|
||||
*.nvuser
|
||||
|
||||
# MFractors (Xamarin productivity tool) working folder
|
||||
.mfractor/
|
||||
|
||||
# Local History for Visual Studio
|
||||
.localhistory/
|
||||
|
||||
# Visual Studio History (VSHistory) files
|
||||
.vshistory/
|
||||
|
||||
# BeatPulse healthcheck temp database
|
||||
healthchecksdb
|
||||
|
||||
# Backup folder for Package Reference Convert tool in Visual Studio 2017
|
||||
MigrationBackup/
|
||||
|
||||
# Ionide (cross platform F# VS Code tools) working folder
|
||||
.ionide/
|
||||
|
||||
# Fody - auto-generated XML schema
|
||||
FodyWeavers.xsd
|
||||
|
||||
# VS Code files for those working on multiple tools
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
*.code-workspace
|
||||
|
||||
# Local History for Visual Studio Code
|
||||
.history/
|
||||
|
||||
# Windows Installer files from build outputs
|
||||
*.cab
|
||||
*.msi
|
||||
*.msix
|
||||
*.msm
|
||||
*.msp
|
||||
|
||||
# JetBrains Rider
|
||||
*.sln.iml
|
||||
|
||||
|
||||
bin/
|
||||
obj/
|
|
@ -0,0 +1,43 @@
|
|||
# C Sharp Example
|
||||
|
||||
|
||||
## Requirements
|
||||
- git bash (which is installed as part of [Git](https://git-scm.com/downloads))
|
||||
- [chocolatey](https://chocolatey.org/install)
|
||||
- [make](https://community.chocolatey.org/packages/make)
|
||||
- [mingw](https://community.chocolatey.org/packages/mingw)
|
||||
- [go](https://go.dev/doc/install)
|
||||
|
||||
|
||||
## Running this example
|
||||
These instructions should be executed in git bash:
|
||||
```bash
|
||||
# Clone the repository
|
||||
git clone https://github.com/status-im/go-waku.git
|
||||
cd go-waku
|
||||
|
||||
# Build the .dll
|
||||
make dynamic-library
|
||||
|
||||
# Copy the library into `libs/` folder
|
||||
cp ./build/lib/libgowaku.* ./build/examples/waku-csharp/waku-csharp/libs/.
|
||||
```
|
||||
|
||||
Open the solution `waku-csharp.sln` in Visual Studio and run the program.
|
||||
|
||||
## Description
|
||||
The following files are available:
|
||||
- `Program.cs` contains an example program which uses the waku library
|
||||
- `Waku.cs`: file containing the `Waku` namespace with classes that allows you to instantiate a Go-Waku node
|
||||
- `Waku.Config`: class used to configure the waku node when instantiation
|
||||
- `Waku.Node`: waku node. The following methods are available:
|
||||
- `Node` - constructor. Initializes a waku node. Receives an optional `Waku.Config`
|
||||
- `Start` - mounts all the waku2 protocols
|
||||
- `Stop` - stops the waku node
|
||||
- `PeerId` - obtain the peer ID of the node.
|
||||
- `PeerCnt` - obtain the number of connected peers
|
||||
- `ListenAddresses` - obtain the multiaddresses the node is listening to
|
||||
|
||||
|
||||
## Help wanted!
|
||||
- Is it possible to build go-waku automatically by executing `make dynamic-library` and copying the .dll automatically into `libs/` in Visual Studio?
|
|
@ -0,0 +1,25 @@
|
|||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.1.32319.34
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "waku-csharp", "waku-csharp\waku-csharp.csproj", "{DF7E520D-8CD7-4E26-B364-323FB907200F}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{DF7E520D-8CD7-4E26-B364-323FB907200F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{DF7E520D-8CD7-4E26-B364-323FB907200F}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{DF7E520D-8CD7-4E26-B364-323FB907200F}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{DF7E520D-8CD7-4E26-B364-323FB907200F}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {CF131A12-1D34-4683-A5BE-DD7326B38FE3}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
|
@ -0,0 +1,86 @@
|
|||
using System.Text;
|
||||
|
||||
|
||||
string alicePrivKey = "0x4f012057e1a1458ce34189cb27daedbbe434f3df0825c1949475dec786e2c64e";
|
||||
string alicePubKey = "0x0440f05847c4c7166f57ae8ecaaf72d31bddcbca345e26713ca9e26c93fb8362ddcd5ae7f4533ee956428ad08a89cd18b234c2911a3b1c7fbd1c0047610d987302";
|
||||
|
||||
string bobPrivKey = "0xb91d6b2df8fb6ef8b53b51b2b30a408c49d5e2b530502d58ac8f94e5c5de1453";
|
||||
string bobPubKey = "0x045eef61a98ba1cf44a2736fac91183ea2bd86e67de20fe4bff467a71249a8a0c05f795dd7f28ced7c15eaa69c89d4212cc4f526ca5e9a62e88008f506d850cccd";
|
||||
|
||||
|
||||
|
||||
Waku.Config c = new(); // This configuration and its attributes are optional
|
||||
c.relay = true;
|
||||
c.host = "localhost";
|
||||
|
||||
Waku.Node node = new(c);
|
||||
|
||||
|
||||
// A callback must be registered to receive events
|
||||
void SignalHandler(Waku.Event evt)
|
||||
{
|
||||
Console.WriteLine(">>> Received a signal: " + evt.type);
|
||||
if (evt.type == Waku.EventType.Message)
|
||||
{
|
||||
Waku.MessageEvent msgEvt = (Waku.MessageEvent)evt; // Downcast to specific event type to access the event data
|
||||
Waku.DecodedPayload decodedPayload = node.RelayPublishDecodeAsymmetric(msgEvt.data.wakuMessage, bobPrivKey);
|
||||
|
||||
string message = Encoding.UTF8.GetString(decodedPayload.data);
|
||||
Console.WriteLine(">>> Message: " + message + " from: " + decodedPayload.pubkey);
|
||||
}
|
||||
}
|
||||
node.SetEventHandler(SignalHandler);
|
||||
|
||||
node.Start();
|
||||
|
||||
Console.WriteLine(">>> The node peer ID is " + node.PeerId());
|
||||
|
||||
foreach (string addr in node.ListenAddresses())
|
||||
{
|
||||
Console.WriteLine(">>> Listening on " + addr);
|
||||
}
|
||||
|
||||
Console.WriteLine(">>> Default pubsub topic: " + Waku.Utils.DefaultPubsubTopic());
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
node.Connect("/dns4/node-01.gc-us-central1-a.wakuv2.test.statusim.net/tcp/30303/p2p/16Uiu2HAmJb2e28qLXxT5kZxVUUoJt72EMzNGXB47Rxx5hw3q4YjS");
|
||||
Console.WriteLine(">>> Connected to Peer");
|
||||
|
||||
foreach (Waku.Peer peer in node.Peers())
|
||||
{
|
||||
Console.WriteLine(">>> Peer: " + peer.peerID);
|
||||
Console.WriteLine(">>> Protocols: " + String.Join(", ", peer.protocols.ToArray()));
|
||||
Console.WriteLine(">>> Addresses: " + String.Join(", ", peer.addrs.ToArray()));
|
||||
}
|
||||
|
||||
Waku.StoreQuery q = new();
|
||||
q.pubsubTopic = Waku.Utils.DefaultPubsubTopic();
|
||||
q.pagingOptions = new(3, null, false);
|
||||
Waku.StoreResponse response = node.StoreQuery(q);
|
||||
Console.WriteLine(">>> Retrieved " + response.messages.Count + " messages from store");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine(">>> Could not connect to peer: " + ex.Message);
|
||||
}
|
||||
|
||||
|
||||
node.RelaySubscribe();
|
||||
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
Waku.Message msg = new Waku.Message();
|
||||
msg.payload = Encoding.UTF8.GetBytes("Hello World - " + i);
|
||||
msg.timestamp = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds; // Nanoseconds
|
||||
msg.contentTopic = Waku.Utils.ContentTopic("example", 1, "example", "rfc26");
|
||||
string messageID = node.RelayPublishEncodeAsymmetric(msg, bobPubKey, alicePrivKey);
|
||||
|
||||
System.Threading.Thread.Sleep(1000);
|
||||
}
|
||||
|
||||
node.RelayUnsubscribe();
|
||||
|
||||
Console.ReadLine();
|
||||
node.Stop();
|
|
@ -0,0 +1,12 @@
|
|||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Waku
|
||||
{
|
||||
internal static class Constants
|
||||
{
|
||||
public const string dllName = "libs/libgowaku.dll";
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,480 @@
|
|||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Waku
|
||||
{
|
||||
public class Config
|
||||
{
|
||||
public string? host { get; set; }
|
||||
public int? port { get; set; }
|
||||
public string? advertiseAddr { get; set; }
|
||||
public string? nodeKey { get; set; }
|
||||
public int? keepAliveInterval { get; set; }
|
||||
public bool? relay { get; set; }
|
||||
}
|
||||
|
||||
public enum EventType
|
||||
{
|
||||
Unknown, Message
|
||||
}
|
||||
|
||||
public class Message
|
||||
{
|
||||
public byte[] payload { get; set; } = new byte[0];
|
||||
public string contentTopic { get; set; } = "";
|
||||
public int version { get; set; } = 0;
|
||||
public long? timestamp { get; set; }
|
||||
}
|
||||
|
||||
public class DecodedPayload
|
||||
{
|
||||
public string? pubkey { get; set; }
|
||||
public string? signature { get; set; }
|
||||
public byte[] data { get; set; } = new byte[0];
|
||||
public string? padding { get; set; }
|
||||
}
|
||||
|
||||
public class Peer
|
||||
{
|
||||
public string peerID { get; set; } = "";
|
||||
public bool connected { get; set; } = false;
|
||||
public IList<string> protocols { get; set; } = new List<string>();
|
||||
public IList<string> addrs { get; set; } = new List<string>();
|
||||
}
|
||||
|
||||
public class Event
|
||||
{
|
||||
public int nodeId { get; set; }
|
||||
|
||||
public EventType type { get; set; } = EventType.Unknown;
|
||||
}
|
||||
|
||||
public class MessageEventData
|
||||
{
|
||||
public string messageID { get; set; } = "";
|
||||
|
||||
public string subscriptionID { get; set; } = "";
|
||||
|
||||
public string pubsubTopic { get; set; } = Utils.DefaultPubsubTopic();
|
||||
|
||||
public Message wakuMessage { get; set; } = new Message();
|
||||
}
|
||||
|
||||
public class MessageEvent : Event
|
||||
{
|
||||
[JsonPropertyName("event")]
|
||||
public MessageEventData data { get; set; } = new();
|
||||
}
|
||||
|
||||
public class ContentFilter
|
||||
{
|
||||
public ContentFilter(string contentTopic)
|
||||
{
|
||||
this.contentTopic = contentTopic;
|
||||
}
|
||||
public string contentTopic { get; set; } = "";
|
||||
}
|
||||
|
||||
public class Cursor
|
||||
{
|
||||
public byte[] digest { get; set; } = new byte[0];
|
||||
public string pubsubTopic { get; set; } = Utils.DefaultPubsubTopic();
|
||||
public long receiverTime { get; set; } = 0;
|
||||
public long senderTime { get; set; } = 0;
|
||||
}
|
||||
|
||||
public class PagingOptions
|
||||
{
|
||||
public PagingOptions(int pageSize, Cursor? cursor, bool forward)
|
||||
{
|
||||
this.pageSize = pageSize;
|
||||
this.cursor = cursor;
|
||||
this.forward = forward;
|
||||
}
|
||||
public int pageSize { get; set; } = 100;
|
||||
public Cursor? cursor { get; set; } = new();
|
||||
public bool forward { get; set; } = true;
|
||||
}
|
||||
|
||||
public class StoreQuery
|
||||
{
|
||||
public string? pubsubTopic { get; set; } = Utils.DefaultPubsubTopic();
|
||||
public long? startTime { get; set; }
|
||||
public long? endTime { get; set; }
|
||||
public IList<ContentFilter>? contentFilters { get; set; }
|
||||
public PagingOptions? pagingOptions { get; set; }
|
||||
}
|
||||
|
||||
public class StoreResponse
|
||||
{
|
||||
public IList<Message> messages { get; set; } = new List<Message>();
|
||||
public PagingOptions? pagingInfo { get; set; }
|
||||
}
|
||||
|
||||
public class Node
|
||||
{
|
||||
private bool _running;
|
||||
private static SignalHandlerDelegate? _signalHandler;
|
||||
|
||||
[DllImport(Constants.dllName)]
|
||||
internal static extern IntPtr waku_new(string configJSON);
|
||||
|
||||
/// <summary>
|
||||
/// Initialize a go-waku node.
|
||||
/// </summary>
|
||||
/// <param name="c">Waku.Config containing the options used to initialize a go-waku node. It can be NULL to use defaults. All the keys from the configuration are optional </param>
|
||||
/// <returns>The node id</returns>
|
||||
public Node(Config? c = null)
|
||||
{
|
||||
string jsonString = "{}";
|
||||
if (c != null)
|
||||
{
|
||||
jsonString = JsonSerializer.Serialize(c);
|
||||
}
|
||||
|
||||
IntPtr ptr = waku_new(jsonString);
|
||||
|
||||
Response.HandleResponse(ptr);
|
||||
|
||||
SetEventCallback();
|
||||
}
|
||||
|
||||
~Node()
|
||||
{
|
||||
if (_running)
|
||||
{
|
||||
Stop();
|
||||
}
|
||||
}
|
||||
|
||||
private static void DefaultEventHandler(IntPtr signalJSON)
|
||||
{
|
||||
if (_signalHandler != null)
|
||||
{
|
||||
string signalStr = Response.PtrToStringUtf8(signalJSON, false);
|
||||
JsonSerializerOptions options = new JsonSerializerOptions();
|
||||
options.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase));
|
||||
|
||||
Event? evt = JsonSerializer.Deserialize<Event>(signalStr, options);
|
||||
if (evt == null) return;
|
||||
|
||||
switch (evt.type)
|
||||
{
|
||||
case EventType.Message:
|
||||
Event? msgEvt = JsonSerializer.Deserialize<MessageEvent>(signalStr, options);
|
||||
if (msgEvt != null) _signalHandler(msgEvt);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
|
||||
internal delegate void WakuEventHandlerDelegate(IntPtr signalJSON);
|
||||
|
||||
[DllImport(Constants.dllName, CallingConvention = CallingConvention.Cdecl)]
|
||||
internal static extern void waku_set_event_callback(WakuEventHandlerDelegate cb);
|
||||
|
||||
private void SetEventCallback()
|
||||
{
|
||||
waku_set_event_callback(DefaultEventHandler);
|
||||
}
|
||||
|
||||
public delegate void SignalHandlerDelegate(Event evt);
|
||||
|
||||
/// <summary>
|
||||
/// Register callback to act as signal handler and receive application signals which are used to react to asyncronous events in waku.
|
||||
/// <param name="h">SignalHandler with the signature `void SignalHandler(Waku.Event evt){ }`</param>
|
||||
public void SetEventHandler(SignalHandlerDelegate h)
|
||||
{
|
||||
_signalHandler = h;
|
||||
}
|
||||
|
||||
[DllImport(Constants.dllName)]
|
||||
internal static extern IntPtr waku_start();
|
||||
|
||||
/// <summary>
|
||||
/// Initialize a go-waku node mounting all the protocols that were enabled during the waku node initialization.
|
||||
/// </summary>
|
||||
public void Start()
|
||||
{
|
||||
IntPtr ptr = waku_start();
|
||||
Response.HandleResponse(ptr);
|
||||
|
||||
_running = true;
|
||||
}
|
||||
|
||||
[DllImport(Constants.dllName)]
|
||||
internal static extern IntPtr waku_stop();
|
||||
|
||||
/// <summary>
|
||||
/// Stops a go-waku node
|
||||
/// </summary>
|
||||
public void Stop()
|
||||
{
|
||||
IntPtr ptr = waku_stop();
|
||||
Response.HandleResponse(ptr);
|
||||
|
||||
_running = false;
|
||||
}
|
||||
|
||||
[DllImport(Constants.dllName)]
|
||||
internal static extern IntPtr waku_peerid();
|
||||
|
||||
/// <summary>
|
||||
/// Obtain the peer ID of the go-waku node.
|
||||
/// </summary>
|
||||
/// <returns>The base58 encoded peer Id</returns>
|
||||
public string PeerId()
|
||||
{
|
||||
IntPtr ptr = waku_peerid();
|
||||
return Response.HandleResponse(ptr, "could not obtain the peerId");
|
||||
}
|
||||
|
||||
[DllImport(Constants.dllName)]
|
||||
internal static extern IntPtr waku_peer_cnt();
|
||||
|
||||
/// <summary>
|
||||
/// Obtain number of connected peers
|
||||
/// </summary>
|
||||
/// <returns>The number of peers connected to this node</returns>
|
||||
public int PeerCnt()
|
||||
{
|
||||
IntPtr ptr = waku_start();
|
||||
return Response.HandleResponse<int>(ptr, "could not obtain the peer count");
|
||||
}
|
||||
|
||||
|
||||
[DllImport(Constants.dllName)]
|
||||
internal static extern IntPtr waku_listen_addresses();
|
||||
|
||||
/// <summary>
|
||||
/// Obtain the multiaddresses the wakunode is listening to
|
||||
/// </summary>
|
||||
/// <returns>List of multiaddresses</returns>
|
||||
public IList<string> ListenAddresses()
|
||||
{
|
||||
IntPtr ptr = waku_listen_addresses();
|
||||
return Response.HandleListResponse<string>(ptr, "could not obtain the addresses");
|
||||
}
|
||||
|
||||
[DllImport(Constants.dllName)]
|
||||
internal static extern IntPtr waku_add_peer(string address, string protocolId);
|
||||
|
||||
/// <summary>
|
||||
/// Add node multiaddress and protocol to the wakunode peerstore
|
||||
/// </summary>
|
||||
/// <param name="address">multiaddress of the peer being added</param>
|
||||
/// <param name="protocolId">protocol supported by the peer</param>
|
||||
/// <returns>Base58 encoded peer Id</returns>
|
||||
public string AddPeer(string address, string protocolId)
|
||||
{
|
||||
IntPtr ptr = waku_add_peer(address, protocolId);
|
||||
return Response.HandleResponse(ptr, "could not obtain the peer id");
|
||||
}
|
||||
|
||||
[DllImport(Constants.dllName)]
|
||||
internal static extern IntPtr waku_connect(string address, int ms);
|
||||
|
||||
/// <summary>
|
||||
/// Connect to peer at multiaddress.
|
||||
/// </summary>
|
||||
/// <param name="address">multiaddress of the peer being dialed</param>
|
||||
/// <param name="ms">max duration in milliseconds this function might take to execute. If the function execution takes longer than this value, the execution will be canceled and an error returned. Use 0 for unlimited duration</param>
|
||||
public void Connect(string address, int ms = 0)
|
||||
{
|
||||
IntPtr ptr = waku_connect(address, ms);
|
||||
Response.HandleResponse(ptr);
|
||||
}
|
||||
|
||||
[DllImport(Constants.dllName)]
|
||||
internal static extern IntPtr waku_connect_peerid( string peerId, int ms);
|
||||
|
||||
/// <summary>
|
||||
/// Connect to peer using peerID.
|
||||
/// </summary>
|
||||
/// <param name="peerId"> peerID to dial. The peer must be already known, added with `AddPeer`</param>
|
||||
/// <param name="ms">max duration in milliseconds this function might take to execute. If the function execution takes longer than this value, the execution will be canceled and an error returned. Use 0 for unlimited duration</param>
|
||||
public void ConnectPeerId(string peerId, int ms = 0)
|
||||
{
|
||||
IntPtr ptr = waku_connect_peerid(peerId, ms);
|
||||
Response.HandleResponse(ptr);
|
||||
}
|
||||
|
||||
[DllImport(Constants.dllName)]
|
||||
internal static extern IntPtr waku_disconnect(string peerID);
|
||||
|
||||
/// <summary>
|
||||
/// Close connection to a known peer by peerID
|
||||
/// </summary>
|
||||
/// <param name="peerId">Base58 encoded peer ID to disconnect</param>
|
||||
public void Disconnect(string peerId)
|
||||
{
|
||||
IntPtr ptr = waku_disconnect(peerId);
|
||||
Response.HandleResponse(ptr);
|
||||
}
|
||||
|
||||
[DllImport(Constants.dllName)]
|
||||
internal static extern IntPtr waku_relay_publish(string messageJSON, string? topic, int ms);
|
||||
|
||||
/// <summary>
|
||||
/// Publish a message using waku relay.
|
||||
/// </summary>
|
||||
/// <param name="msg">Message to broadcast</param>
|
||||
/// <param name="topic">Pubsub topic. Set to `null` to use the default pubsub topic</param>
|
||||
/// <param name="ms">If ms is greater than 0, the broadcast of the message must happen before the timeout (in milliseconds) is reached, or an error will be returned</param>
|
||||
/// <returns></returns>
|
||||
public string RelayPublish(Message msg, string? topic = null, int ms = 0)
|
||||
{
|
||||
string jsonMsg = JsonSerializer.Serialize(msg);
|
||||
IntPtr ptr = waku_relay_publish(jsonMsg, topic, ms);
|
||||
return Response.HandleResponse(ptr, "could not obtain the message id");
|
||||
}
|
||||
|
||||
|
||||
[DllImport(Constants.dllName)]
|
||||
internal static extern IntPtr waku_relay_publish_enc_asymmetric(string messageJSON, string? topic, string publicKey, string? optionalSigningKey, int ms);
|
||||
|
||||
/// <summary>
|
||||
/// Publish a message encrypted with an secp256k1 public key using waku relay.
|
||||
/// </summary>
|
||||
/// <param name="msg">Message to broadcast</param>
|
||||
/// <param name="publicKey">Secp256k1 public key</param>
|
||||
/// <param name="optionalSigningKey">Optional secp256k1 private key for signing the message</param>
|
||||
/// <param name="topic">Pubsub topic. Set to `null` to use the default pubsub topic</param>
|
||||
/// <param name="ms">If ms is greater than 0, the broadcast of the message must happen before the timeout (in milliseconds) is reached, or an error will be returned</param>
|
||||
/// <returns></returns>
|
||||
public string RelayPublishEncodeAsymmetric(Message msg, string publicKey, string? optionalSigningKey = null, string? topic = null, int ms = 0)
|
||||
{
|
||||
string jsonMsg = JsonSerializer.Serialize(msg);
|
||||
IntPtr ptr = waku_relay_publish_enc_asymmetric(jsonMsg, topic, publicKey, optionalSigningKey, ms);
|
||||
return Response.HandleResponse(ptr, "could not obtain the message id");
|
||||
}
|
||||
|
||||
[DllImport(Constants.dllName)]
|
||||
internal static extern IntPtr waku_relay_publish_enc_symmetric(string messageJSON, string? topic, string symmetricKey, string? optionalSigningKey, int ms);
|
||||
|
||||
/// <summary>
|
||||
/// Publish a message encrypted with a 32 bytes symmetric key using waku relay.
|
||||
/// </summary>
|
||||
/// <param name="msg">Message to broadcast</param>
|
||||
/// <param name="symmetricKey">32 byte hex string containing a symmetric key</param>
|
||||
/// <param name="optionalSigningKey">Optional secp256k1 private key for signing the message</param>
|
||||
/// <param name="topic">Pubsub topic. Set to `null` to use the default pubsub topic</param>
|
||||
/// <param name="ms">If ms is greater than 0, the broadcast of the message must happen before the timeout (in milliseconds) is reached, or an error will be returned</param>
|
||||
/// <returns></returns>
|
||||
public string RelayPublishEncodeSymmetric(Message msg, string symmetricKey, string? optionalSigningKey = null, string? topic = null, int ms = 0)
|
||||
{
|
||||
string jsonMsg = JsonSerializer.Serialize(msg);
|
||||
IntPtr ptr = waku_relay_publish_enc_symmetric(jsonMsg, topic, symmetricKey, optionalSigningKey, ms);
|
||||
return Response.HandleResponse(ptr, "could not obtain the message id");
|
||||
}
|
||||
|
||||
[DllImport(Constants.dllName)]
|
||||
internal static extern IntPtr waku_decode_symmetric(string messageJSON, string symmetricKey);
|
||||
|
||||
/// <summary>
|
||||
/// Decode a waku message using a symmetric key
|
||||
/// </summary>
|
||||
/// <param name="msg">Message to decode</param>
|
||||
/// <param name="symmetricKey">Symmetric key used to decode the message</param>
|
||||
/// <returns>DecodedPayload containing the decrypted message, padding, public key and signature (if available)</returns>
|
||||
public DecodedPayload RelayPublishDecodeSymmetric(Message msg, string symmetricKey)
|
||||
{
|
||||
string jsonMsg = JsonSerializer.Serialize(msg);
|
||||
IntPtr ptr = waku_decode_symmetric(jsonMsg, symmetricKey);
|
||||
return Response.HandleDecodedPayloadResponse(ptr, "could not decode message");
|
||||
}
|
||||
|
||||
[DllImport(Constants.dllName)]
|
||||
internal static extern IntPtr waku_decode_asymmetric(string messageJSON, string privateKey);
|
||||
|
||||
/// <summary>
|
||||
/// Decode a waku message using an asymmetric key
|
||||
/// </summary>
|
||||
/// <param name="msg">Message to decode</param>
|
||||
/// <param name="privateKey">Secp256k1 private key used to decode the message</param>
|
||||
/// <returns>DecodedPayload containing the decrypted message, padding, public key and signature (if available)</returns>
|
||||
public DecodedPayload RelayPublishDecodeAsymmetric(Message msg, string privateKey)
|
||||
{
|
||||
string jsonMsg = JsonSerializer.Serialize(msg);
|
||||
IntPtr ptr = waku_decode_asymmetric(jsonMsg, privateKey);
|
||||
return Response.HandleDecodedPayloadResponse(ptr, "could not decode message");
|
||||
}
|
||||
|
||||
[DllImport(Constants.dllName)]
|
||||
internal static extern IntPtr waku_relay_enough_peers(string topic);
|
||||
|
||||
/// <summary>
|
||||
/// Determine if there are enough peers to publish a message on a topic.
|
||||
/// </summary>
|
||||
/// <param name="topic">pubsub topic to verify. Use NULL to verify the number of peers in the default pubsub topic</param>
|
||||
/// <returns>boolean indicating if there are enough peers or not</returns>
|
||||
public bool RelayEnoughPeers(string topic = null)
|
||||
{
|
||||
IntPtr ptr = waku_relay_enough_peers(topic);
|
||||
return Response.HandleResponse<bool>(ptr, "could not determine if there are enough peers");
|
||||
}
|
||||
|
||||
[DllImport(Constants.dllName)]
|
||||
internal static extern IntPtr waku_relay_subscribe(string? topic);
|
||||
|
||||
/// <summary>
|
||||
/// Subscribe to a WakuRelay topic to receive messages.
|
||||
/// </summary>
|
||||
/// <param name="topic">Pubsub topic to subscribe to. Use NULL for subscribing to the default pubsub topic</param>
|
||||
/// <returns>Subscription Id</returns>
|
||||
public void RelaySubscribe(string? topic = null)
|
||||
{
|
||||
IntPtr ptr = waku_relay_subscribe(topic);
|
||||
Response.HandleResponse(ptr);
|
||||
}
|
||||
|
||||
[DllImport(Constants.dllName)]
|
||||
internal static extern IntPtr waku_relay_unsubscribe(string? topic);
|
||||
|
||||
/// <summary>
|
||||
/// Closes the pubsub subscription to a pubsub topic.
|
||||
/// </summary>
|
||||
/// <param name="topic">Pubsub topic to unsubscribe. Use NULL for unsubscribe from the default pubsub topic</param>
|
||||
public void RelayUnsubscribe(string? topic = null)
|
||||
{
|
||||
IntPtr ptr = waku_relay_unsubscribe(topic);
|
||||
Response.HandleResponse(ptr);
|
||||
}
|
||||
|
||||
[DllImport(Constants.dllName)]
|
||||
internal static extern IntPtr waku_peers();
|
||||
|
||||
/// <summary>
|
||||
/// Get Peers
|
||||
/// </summary>
|
||||
/// <returns>Retrieve list of peers and their supported protocols</returns>
|
||||
public IList<Peer> Peers()
|
||||
{
|
||||
IntPtr ptr = waku_peers();
|
||||
return Response.HandleListResponse<Peer>(ptr, "could not obtain the peers");
|
||||
}
|
||||
|
||||
[DllImport(Constants.dllName)]
|
||||
internal static extern IntPtr waku_store_query(string queryJSON, string? peerID, int ms);
|
||||
/// <summary>
|
||||
/// Query message history
|
||||
/// </summary>
|
||||
/// <param name="query">Query</param>
|
||||
/// <param name="peerID">PeerID to ask the history from. Use NULL to automatically select a peer</param>
|
||||
/// <param name="ms">If ms is greater than 0, the broadcast of the message must happen before the timeout (in milliseconds) is reached, or an error will be returned</param>
|
||||
/// <returns>Response containing the messages and cursor for pagination. Use the cursor in further queries to retrieve more results</returns>
|
||||
public StoreResponse StoreQuery(StoreQuery query, string? peerID = null, int ms = 0)
|
||||
{
|
||||
string queryJSON = JsonSerializer.Serialize(query);
|
||||
IntPtr ptr = waku_store_query(queryJSON, peerID, ms);
|
||||
|
||||
return Response.HandleStoreResponse(ptr, "could not extract query response");
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,132 @@
|
|||
using System.Runtime.InteropServices;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Waku
|
||||
{
|
||||
internal static class Response
|
||||
{
|
||||
internal class JsonResponse<T>
|
||||
{
|
||||
public string? error { get; set; }
|
||||
public T? result { get; set; }
|
||||
}
|
||||
|
||||
[DllImport(Constants.dllName)]
|
||||
internal static extern IntPtr waku_utils_free(IntPtr ptr);
|
||||
|
||||
internal static string PtrToStringUtf8(IntPtr ptr, bool free = true) // aPtr is nul-terminated
|
||||
{
|
||||
if (ptr == IntPtr.Zero)
|
||||
{
|
||||
waku_utils_free(ptr);
|
||||
return "";
|
||||
}
|
||||
|
||||
int len = 0;
|
||||
while (System.Runtime.InteropServices.Marshal.ReadByte(ptr, len) != 0)
|
||||
len++;
|
||||
|
||||
if (len == 0)
|
||||
{
|
||||
waku_utils_free(ptr);
|
||||
return "";
|
||||
}
|
||||
|
||||
byte[] array = new byte[len];
|
||||
System.Runtime.InteropServices.Marshal.Copy(ptr, array, 0, len);
|
||||
string result = System.Text.Encoding.UTF8.GetString(array);
|
||||
|
||||
if (free)
|
||||
{
|
||||
waku_utils_free(ptr);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
internal static T HandleResponse<T>(IntPtr ptr, string errNoValue) where T : struct
|
||||
{
|
||||
string strResponse = PtrToStringUtf8(ptr);
|
||||
|
||||
JsonResponse<T?>? response = JsonSerializer.Deserialize<JsonResponse<T?>>(strResponse);
|
||||
|
||||
if (response == null) throw new Exception("unknown waku error");
|
||||
|
||||
if (response.error != null) throw new Exception(response.error);
|
||||
|
||||
if (!response.result.HasValue) throw new Exception(errNoValue);
|
||||
|
||||
return response.result.Value;
|
||||
}
|
||||
|
||||
internal static void HandleResponse(IntPtr ptr)
|
||||
{
|
||||
string strResponse = PtrToStringUtf8(ptr);
|
||||
|
||||
JsonResponse<string>? response = JsonSerializer.Deserialize<JsonResponse<string>>(strResponse);
|
||||
|
||||
if (response == null) throw new Exception("unknown waku error");
|
||||
|
||||
if (response.error != null) throw new Exception(response.error);
|
||||
}
|
||||
|
||||
internal static string HandleResponse(IntPtr ptr, string errNoValue)
|
||||
{
|
||||
string strResponse = PtrToStringUtf8(ptr);
|
||||
|
||||
JsonResponse<string>? response = JsonSerializer.Deserialize<JsonResponse<string>>(strResponse);
|
||||
|
||||
if (response == null) throw new Exception("unknown waku error");
|
||||
|
||||
if (response.error != null) throw new Exception(response.error);
|
||||
|
||||
if (String.IsNullOrEmpty(response.result)) throw new Exception(errNoValue);
|
||||
|
||||
return response.result;
|
||||
}
|
||||
|
||||
internal static DecodedPayload HandleDecodedPayloadResponse(IntPtr ptr, string errNoValue)
|
||||
{
|
||||
string strResponse = PtrToStringUtf8(ptr);
|
||||
|
||||
JsonResponse<DecodedPayload>? response = JsonSerializer.Deserialize<JsonResponse<DecodedPayload>>(strResponse);
|
||||
|
||||
if (response == null) throw new Exception("unknown waku error");
|
||||
|
||||
if (response.error != null) throw new Exception(response.error);
|
||||
|
||||
if (response.result == null) throw new Exception(errNoValue);
|
||||
|
||||
return response.result;
|
||||
}
|
||||
|
||||
internal static IList<T> HandleListResponse<T>(IntPtr ptr, string errNoValue)
|
||||
{
|
||||
string strResponse = PtrToStringUtf8(ptr);
|
||||
|
||||
JsonResponse<IList<T>>? response = JsonSerializer.Deserialize<JsonResponse<IList<T>>>(strResponse);
|
||||
|
||||
if (response == null) throw new Exception("unknown waku error");
|
||||
|
||||
if (response.error != null) throw new Exception(response.error);
|
||||
|
||||
if (response.result == null) throw new Exception(errNoValue);
|
||||
|
||||
return response.result;
|
||||
}
|
||||
|
||||
internal static StoreResponse HandleStoreResponse(IntPtr ptr, string errNoValue)
|
||||
{
|
||||
string strResponse = PtrToStringUtf8(ptr);
|
||||
Console.WriteLine(strResponse);
|
||||
JsonResponse<StoreResponse>? response = JsonSerializer.Deserialize<JsonResponse<StoreResponse>>(strResponse);
|
||||
|
||||
if (response == null) throw new Exception("unknown waku error");
|
||||
|
||||
if (response.error != null) throw new Exception(response.error);
|
||||
|
||||
if (response.result == null) throw new Exception(errNoValue);
|
||||
|
||||
return response.result;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Waku
|
||||
{
|
||||
public static class Utils
|
||||
{
|
||||
[DllImport(Constants.dllName)]
|
||||
internal static extern IntPtr waku_default_pubsub_topic();
|
||||
|
||||
/// <summary>
|
||||
/// Get default pubsub topic
|
||||
/// </summary>
|
||||
/// <returns>Default pubsub topic used for exchanging waku messages defined in RFC 10</returns>
|
||||
public static string DefaultPubsubTopic()
|
||||
{
|
||||
IntPtr ptr = waku_default_pubsub_topic();
|
||||
return Response.PtrToStringUtf8(ptr);
|
||||
}
|
||||
|
||||
[DllImport(Constants.dllName)]
|
||||
internal static extern IntPtr waku_content_topic(string applicationName, uint applicationVersion, string contentTopicName, string encoding);
|
||||
|
||||
/// <summary>
|
||||
/// Create a content topic string
|
||||
/// </summary>
|
||||
/// <param name="applicationName"></param>
|
||||
/// <param name="applicationVersion"></param>
|
||||
/// <param name="contentTopicName"></param>
|
||||
/// <param name="encoding"></param>
|
||||
/// <returns>Content topic string according to RFC 23</returns>
|
||||
public static string ContentTopic(string applicationName, uint applicationVersion, string contentTopicName, string encoding)
|
||||
{
|
||||
IntPtr ptr = waku_content_topic(applicationName, applicationVersion, contentTopicName, encoding);
|
||||
return Response.PtrToStringUtf8(ptr);
|
||||
}
|
||||
|
||||
[DllImport(Constants.dllName)]
|
||||
internal static extern IntPtr waku_pubsub_topic(string name, string encoding);
|
||||
|
||||
/// <summary>
|
||||
/// Create a pubsub topic string
|
||||
/// </summary>
|
||||
/// <param name="name"></param>
|
||||
/// <param name="encoding"></param>
|
||||
/// <returns>Pubsub topic string according to RFC 23</returns>
|
||||
public static string PubsubTopic(string name, string encoding)
|
||||
{
|
||||
IntPtr ptr = waku_pubsub_topic(name, encoding);
|
||||
return Response.PtrToStringUtf8(ptr);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="libs\" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="libs\libgowaku.dll">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
1
go.mod
1
go.mod
|
@ -11,7 +11,6 @@ require (
|
|||
github.com/ethereum/go-ethereum v1.10.16
|
||||
github.com/gogo/protobuf v1.3.2
|
||||
github.com/golang/protobuf v1.5.2
|
||||
github.com/google/uuid v1.3.0
|
||||
github.com/gorilla/rpc v1.2.0
|
||||
github.com/ipfs/go-ds-sql v0.3.0
|
||||
github.com/ipfs/go-log v1.0.5
|
||||
|
|
505
library/api.go
505
library/api.go
|
@ -3,15 +3,6 @@ package main
|
|||
/*
|
||||
#include <stdlib.h>
|
||||
#include <stddef.h>
|
||||
|
||||
typedef struct {
|
||||
size_t len;
|
||||
char* data;
|
||||
} ByteArray;
|
||||
|
||||
#define SYMMETRIC "Symmetric"
|
||||
#define ASYMMETRIC "Asymmetric"
|
||||
#define NONE "None"
|
||||
*/
|
||||
import "C"
|
||||
import (
|
||||
|
@ -28,24 +19,18 @@ import (
|
|||
"time"
|
||||
"unsafe"
|
||||
|
||||
"sync"
|
||||
|
||||
"github.com/ethereum/go-ethereum/common/hexutil"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/ethereum/go-ethereum/crypto/secp256k1"
|
||||
"github.com/google/uuid"
|
||||
"github.com/libp2p/go-libp2p-core/peer"
|
||||
p2pproto "github.com/libp2p/go-libp2p-core/protocol"
|
||||
"github.com/multiformats/go-multiaddr"
|
||||
"github.com/status-im/go-waku/waku/v2/node"
|
||||
"github.com/status-im/go-waku/waku/v2/protocol"
|
||||
"github.com/status-im/go-waku/waku/v2/protocol/pb"
|
||||
"github.com/status-im/go-waku/waku/v2/protocol/relay"
|
||||
)
|
||||
|
||||
var nodes map[int]*node.WakuNode = make(map[int]*node.WakuNode)
|
||||
var subscriptions map[string]*relay.Subscription = make(map[string]*relay.Subscription)
|
||||
var mutex sync.Mutex
|
||||
var wakuNode *node.WakuNode
|
||||
|
||||
var ErrWakuNodeNotReady = errors.New("go-waku not initialized")
|
||||
|
||||
|
@ -111,7 +96,7 @@ func getConfig(configJSON *C.char) (WakuConfig, error) {
|
|||
return config, nil
|
||||
}
|
||||
|
||||
//export gowaku_new
|
||||
//export waku_new
|
||||
// Initialize a waku node. Receives a JSON string containing the configuration
|
||||
// for the node. It can be NULL. Example configuration:
|
||||
// ```
|
||||
|
@ -126,7 +111,11 @@ func getConfig(configJSON *C.char) (WakuConfig, error) {
|
|||
// - relay: Enable WakuRelay. Default `true`
|
||||
// This function will return a nodeID which should be used in all calls from this API that require
|
||||
// interacting with the node.
|
||||
func gowaku_new(configJSON *C.char) *C.char {
|
||||
func waku_new(configJSON *C.char) *C.char {
|
||||
if wakuNode != nil {
|
||||
return makeJSONResponse(errors.New("go-waku already initialized. stop it first"))
|
||||
}
|
||||
|
||||
config, err := getConfig(configJSON)
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
|
@ -165,28 +154,21 @@ func gowaku_new(configJSON *C.char) *C.char {
|
|||
}
|
||||
|
||||
ctx := context.Background()
|
||||
wakuNode, err := node.New(ctx, opts...)
|
||||
w, err := node.New(ctx, opts...)
|
||||
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
}
|
||||
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
wakuNode = w
|
||||
|
||||
id := len(nodes) + 1
|
||||
nodes[id] = wakuNode
|
||||
|
||||
return prepareJSONResponse(id, nil)
|
||||
return makeJSONResponse(nil)
|
||||
}
|
||||
|
||||
//export gowaku_start
|
||||
//export waku_start
|
||||
// Starts the waku node
|
||||
func gowaku_start(nodeID C.int) *C.char {
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
wakuNode, ok := nodes[int(nodeID)]
|
||||
if !ok || wakuNode == nil {
|
||||
func waku_start() *C.char {
|
||||
if wakuNode == nil {
|
||||
return makeJSONResponse(ErrWakuNodeNotReady)
|
||||
}
|
||||
|
||||
|
@ -197,56 +179,48 @@ func gowaku_start(nodeID C.int) *C.char {
|
|||
return makeJSONResponse(nil)
|
||||
}
|
||||
|
||||
//export gowaku_stop
|
||||
//export waku_stop
|
||||
// Stops a waku node
|
||||
func gowaku_stop(nodeID C.int) *C.char {
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
wakuNode, ok := nodes[int(nodeID)]
|
||||
if !ok || wakuNode == nil {
|
||||
func waku_stop() *C.char {
|
||||
if wakuNode == nil {
|
||||
return makeJSONResponse(ErrWakuNodeNotReady)
|
||||
}
|
||||
|
||||
wakuNode.Stop()
|
||||
nodes[int(nodeID)] = nil
|
||||
wakuNode = nil
|
||||
|
||||
return makeJSONResponse(nil)
|
||||
}
|
||||
|
||||
//export gowaku_peerid
|
||||
//export waku_peerid
|
||||
// Obtain the peer ID of the waku node
|
||||
func gowaku_peerid(nodeID C.int) *C.char {
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
wakuNode, ok := nodes[int(nodeID)]
|
||||
if !ok || wakuNode == nil {
|
||||
func waku_peerid() *C.char {
|
||||
if wakuNode == nil {
|
||||
return makeJSONResponse(ErrWakuNodeNotReady)
|
||||
}
|
||||
|
||||
return prepareJSONResponse(wakuNode.ID(), nil)
|
||||
}
|
||||
|
||||
//export gowaku_listen_addresses
|
||||
//export waku_listen_addresses
|
||||
// Obtain the multiaddresses the wakunode is listening to
|
||||
func gowaku_listen_addresses(nodeID C.int) *C.char {
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
wakuNode, ok := nodes[int(nodeID)]
|
||||
if !ok || wakuNode == nil {
|
||||
func waku_listen_addresses() *C.char {
|
||||
if wakuNode == nil {
|
||||
return makeJSONResponse(ErrWakuNodeNotReady)
|
||||
}
|
||||
|
||||
addrs, err := json.Marshal(wakuNode.ListenAddresses())
|
||||
return prepareJSONResponse(addrs, err)
|
||||
var addresses []string
|
||||
for _, addr := range wakuNode.ListenAddresses() {
|
||||
addresses = append(addresses, addr.String())
|
||||
}
|
||||
|
||||
return prepareJSONResponse(addresses, nil)
|
||||
}
|
||||
|
||||
//export gowaku_add_peer
|
||||
//export waku_add_peer
|
||||
// Add node multiaddress and protocol to the wakunode peerstore
|
||||
func gowaku_add_peer(nodeID C.int, address *C.char, protocolID *C.char) *C.char {
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
wakuNode, ok := nodes[int(nodeID)]
|
||||
if !ok || wakuNode == nil {
|
||||
func waku_add_peer(address *C.char, protocolID *C.char) *C.char {
|
||||
if wakuNode == nil {
|
||||
return makeJSONResponse(ErrWakuNodeNotReady)
|
||||
}
|
||||
|
||||
|
@ -259,13 +233,10 @@ func gowaku_add_peer(nodeID C.int, address *C.char, protocolID *C.char) *C.char
|
|||
return prepareJSONResponse(peerID, err)
|
||||
}
|
||||
|
||||
//export gowaku_dial_peer
|
||||
// Dial peer at multiaddress. if ms > 0, cancel the function execution if it takes longer than N milliseconds
|
||||
func gowaku_dial_peer(nodeID C.int, address *C.char, ms C.int) *C.char {
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
wakuNode, ok := nodes[int(nodeID)]
|
||||
if !ok || wakuNode == nil {
|
||||
//export waku_connect
|
||||
// Connect to peer at multiaddress. if ms > 0, cancel the function execution if it takes longer than N milliseconds
|
||||
func waku_connect(address *C.char, ms C.int) *C.char {
|
||||
if wakuNode == nil {
|
||||
return makeJSONResponse(ErrWakuNodeNotReady)
|
||||
}
|
||||
|
||||
|
@ -283,13 +254,10 @@ func gowaku_dial_peer(nodeID C.int, address *C.char, ms C.int) *C.char {
|
|||
return makeJSONResponse(err)
|
||||
}
|
||||
|
||||
//export gowaku_dial_peerid
|
||||
// Dial known peer by peerID. if ms > 0, cancel the function execution if it takes longer than N milliseconds
|
||||
func gowaku_dial_peerid(nodeID C.int, peerID *C.char, ms C.int) *C.char {
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
wakuNode, ok := nodes[int(nodeID)]
|
||||
if !ok || wakuNode == nil {
|
||||
//export waku_connect_peerid
|
||||
// Connect to known peer by peerID. if ms > 0, cancel the function execution if it takes longer than N milliseconds
|
||||
func waku_connect_peerid(peerID *C.char, ms C.int) *C.char {
|
||||
if wakuNode == nil {
|
||||
return makeJSONResponse(ErrWakuNodeNotReady)
|
||||
}
|
||||
|
||||
|
@ -312,27 +280,10 @@ func gowaku_dial_peerid(nodeID C.int, peerID *C.char, ms C.int) *C.char {
|
|||
return makeJSONResponse(err)
|
||||
}
|
||||
|
||||
//export gowaku_close_peer
|
||||
// Close connection to peer at multiaddress
|
||||
func gowaku_close_peer(nodeID C.int, address *C.char) *C.char {
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
wakuNode, ok := nodes[int(nodeID)]
|
||||
if !ok || wakuNode == nil {
|
||||
return makeJSONResponse(ErrWakuNodeNotReady)
|
||||
}
|
||||
|
||||
err := wakuNode.ClosePeerByAddress(C.GoString(address))
|
||||
return makeJSONResponse(err)
|
||||
}
|
||||
|
||||
//export gowaku_close_peerid
|
||||
//export waku_disconnect
|
||||
// Close connection to a known peer by peerID
|
||||
func gowaku_close_peerid(nodeID C.int, peerID *C.char) *C.char {
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
wakuNode, ok := nodes[int(nodeID)]
|
||||
if !ok || wakuNode == nil {
|
||||
func waku_disconnect(peerID *C.char) *C.char {
|
||||
if wakuNode == nil {
|
||||
return makeJSONResponse(ErrWakuNodeNotReady)
|
||||
}
|
||||
|
||||
|
@ -345,212 +296,70 @@ func gowaku_close_peerid(nodeID C.int, peerID *C.char) *C.char {
|
|||
return makeJSONResponse(err)
|
||||
}
|
||||
|
||||
//export gowaku_peer_cnt
|
||||
//export waku_peer_cnt
|
||||
// Get number of connected peers
|
||||
func gowaku_peer_cnt(nodeID C.int) *C.char {
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
wakuNode, ok := nodes[int(nodeID)]
|
||||
if !ok || wakuNode == nil {
|
||||
func waku_peer_cnt() *C.char {
|
||||
if wakuNode == nil {
|
||||
return makeJSONResponse(ErrWakuNodeNotReady)
|
||||
}
|
||||
|
||||
return prepareJSONResponse(wakuNode.PeerCount(), nil)
|
||||
}
|
||||
|
||||
//export gowaku_content_topic
|
||||
//export waku_content_topic
|
||||
// Create a content topic string according to RFC 23
|
||||
func gowaku_content_topic(applicationName *C.char, applicationVersion C.uint, contentTopicName *C.char, encoding *C.char) *C.char {
|
||||
func waku_content_topic(applicationName *C.char, applicationVersion C.uint, contentTopicName *C.char, encoding *C.char) *C.char {
|
||||
return C.CString(protocol.NewContentTopic(C.GoString(applicationName), uint(applicationVersion), C.GoString(contentTopicName), C.GoString(encoding)).String())
|
||||
}
|
||||
|
||||
//export gowaku_pubsub_topic
|
||||
//export waku_pubsub_topic
|
||||
// Create a pubsub topic string according to RFC 23
|
||||
func gowaku_pubsub_topic(name *C.char, encoding *C.char) *C.char {
|
||||
func waku_pubsub_topic(name *C.char, encoding *C.char) *C.char {
|
||||
return prepareJSONResponse(protocol.NewPubsubTopic(C.GoString(name), C.GoString(encoding)).String(), nil)
|
||||
}
|
||||
|
||||
//export gowaku_default_pubsub_topic
|
||||
//export waku_default_pubsub_topic
|
||||
// Get the default pubsub topic used in waku2: /waku/2/default-waku/proto
|
||||
func gowaku_default_pubsub_topic() *C.char {
|
||||
func waku_default_pubsub_topic() *C.char {
|
||||
return C.CString(protocol.DefaultPubsubTopic().String())
|
||||
}
|
||||
|
||||
func publish(nodeID int, message string, pubsubTopic string, ms int) (string, error) {
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
wakuNode, ok := nodes[nodeID]
|
||||
if !ok || wakuNode == nil {
|
||||
return "", ErrWakuNodeNotReady
|
||||
}
|
||||
|
||||
var msg pb.WakuMessage
|
||||
err := json.Unmarshal([]byte(message), &msg)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var ctx context.Context
|
||||
var cancel context.CancelFunc
|
||||
|
||||
if ms > 0 {
|
||||
ctx, cancel = context.WithTimeout(context.Background(), time.Duration(int(ms))*time.Millisecond)
|
||||
defer cancel()
|
||||
} else {
|
||||
ctx = context.Background()
|
||||
}
|
||||
|
||||
hash, err := wakuNode.Relay().PublishToTopic(ctx, &msg, pubsubTopic)
|
||||
return hexutil.Encode(hash), err
|
||||
}
|
||||
|
||||
//export gowaku_relay_publish
|
||||
// Publish a message using waku relay. Use NULL for topic to use the default pubsub topic
|
||||
// If ms is greater than 0, the broadcast of the message must happen before the timeout
|
||||
// (in milliseconds) is reached, or an error will be returned
|
||||
func gowaku_relay_publish(nodeID C.int, messageJSON *C.char, topic *C.char, ms C.int) *C.char {
|
||||
topicToPublish := ""
|
||||
func getTopic(topic *C.char) string {
|
||||
result := ""
|
||||
if topic != nil {
|
||||
topicToPublish = C.GoString(topic)
|
||||
result = C.GoString(topic)
|
||||
} else {
|
||||
topicToPublish = protocol.DefaultPubsubTopic().String()
|
||||
result = protocol.DefaultPubsubTopic().String()
|
||||
}
|
||||
|
||||
hash, err := publish(int(nodeID), C.GoString(messageJSON), topicToPublish, int(ms))
|
||||
return prepareJSONResponse(hash, err)
|
||||
return result
|
||||
}
|
||||
|
||||
//export gowaku_enough_peers
|
||||
// Determine if there are enough peers to publish a message on a topic. Use NULL
|
||||
// to verify the number of peers in the default pubsub topic
|
||||
func gowaku_enough_peers(nodeID C.int, topic *C.char) *C.char {
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
wakuNode, ok := nodes[int(nodeID)]
|
||||
if !ok || wakuNode == nil {
|
||||
return makeJSONResponse(ErrWakuNodeNotReady)
|
||||
}
|
||||
|
||||
topicToCheck := protocol.DefaultPubsubTopic().String()
|
||||
if topic != nil {
|
||||
topicToCheck = C.GoString(topic)
|
||||
}
|
||||
|
||||
return prepareJSONResponse(wakuNode.Relay().EnoughPeersToPublishToTopic(topicToCheck), nil)
|
||||
}
|
||||
|
||||
//export gowaku_set_event_callback
|
||||
//export waku_set_event_callback
|
||||
// Register callback to act as signal handler and receive application signal
|
||||
// (in JSON) which are used o react to asyncronous events in waku. The function
|
||||
// signature for the callback should be `void myCallback(char* signalJSON)`
|
||||
func gowaku_set_event_callback(cb unsafe.Pointer) {
|
||||
func waku_set_event_callback(cb unsafe.Pointer) {
|
||||
setEventCallback(cb)
|
||||
}
|
||||
|
||||
type SubscriptionMsg struct {
|
||||
MessageID string `json:"messageID"`
|
||||
SubscriptionID string `json:"subscriptionID"`
|
||||
PubsubTopic string `json:"pubsubTopic"`
|
||||
Message *pb.WakuMessage `json:"wakuMessage"`
|
||||
MessageID string `json:"messageID"`
|
||||
PubsubTopic string `json:"pubsubTopic"`
|
||||
Message *pb.WakuMessage `json:"wakuMessage"`
|
||||
}
|
||||
|
||||
func toSubscriptionMessage(subsID string, msg *protocol.Envelope) *SubscriptionMsg {
|
||||
func toSubscriptionMessage(msg *protocol.Envelope) *SubscriptionMsg {
|
||||
return &SubscriptionMsg{
|
||||
SubscriptionID: subsID,
|
||||
MessageID: hexutil.Encode(msg.Hash()),
|
||||
PubsubTopic: msg.PubsubTopic(),
|
||||
Message: msg.Message(),
|
||||
MessageID: hexutil.Encode(msg.Hash()),
|
||||
PubsubTopic: msg.PubsubTopic(),
|
||||
Message: msg.Message(),
|
||||
}
|
||||
}
|
||||
|
||||
//export gowaku_relay_subscribe
|
||||
// Subscribe to a WakuRelay topic. Set the topic to NULL to subscribe
|
||||
// to the default topic. Returns a json response containing the subscription ID
|
||||
// or an error message. When a message is received, a "message" is emitted containing
|
||||
// the message, pubsub topic, and nodeID in which the message was received
|
||||
func gowaku_relay_subscribe(nodeID C.int, topic *C.char) *C.char {
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
wakuNode, ok := nodes[int(nodeID)]
|
||||
if !ok || wakuNode == nil {
|
||||
return makeJSONResponse(ErrWakuNodeNotReady)
|
||||
}
|
||||
|
||||
topicToSubscribe := protocol.DefaultPubsubTopic().String()
|
||||
if topic != nil {
|
||||
topicToSubscribe = C.GoString(topic)
|
||||
}
|
||||
|
||||
subscription, err := wakuNode.Relay().SubscribeToTopic(context.Background(), topicToSubscribe)
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
}
|
||||
|
||||
subsID := uuid.New().String()
|
||||
subscriptions[subsID] = subscription
|
||||
|
||||
go func() {
|
||||
for envelope := range subscription.C {
|
||||
send(int(nodeID), "message", toSubscriptionMessage(subsID, envelope))
|
||||
}
|
||||
}()
|
||||
|
||||
return prepareJSONResponse(subsID, nil)
|
||||
}
|
||||
|
||||
//export gowaku_relay_unsubscribe_from_topic
|
||||
// Closes the pubsub subscription to a pubsub topic. Existing subscriptions
|
||||
// will not be closed, but they will stop receiving messages
|
||||
func gowaku_relay_unsubscribe_from_topic(nodeID C.int, topic *C.char) *C.char {
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
wakuNode, ok := nodes[int(nodeID)]
|
||||
if !ok || wakuNode == nil {
|
||||
return makeJSONResponse(ErrWakuNodeNotReady)
|
||||
}
|
||||
|
||||
topicToUnsubscribe := protocol.DefaultPubsubTopic().String()
|
||||
if topic != nil {
|
||||
topicToUnsubscribe = C.GoString(topic)
|
||||
}
|
||||
|
||||
err := wakuNode.Relay().Unsubscribe(context.Background(), topicToUnsubscribe)
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
}
|
||||
|
||||
return makeJSONResponse(nil)
|
||||
}
|
||||
|
||||
//export gowaku_relay_close_subscription
|
||||
// Closes a waku relay subscription
|
||||
func gowaku_relay_close_subscription(nodeID C.int, subsID *C.char) *C.char {
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
wakuNode, ok := nodes[int(nodeID)]
|
||||
if !ok || wakuNode == nil {
|
||||
return makeJSONResponse(ErrWakuNodeNotReady)
|
||||
}
|
||||
|
||||
subscription, ok := subscriptions[C.GoString(subsID)]
|
||||
if !ok {
|
||||
return makeJSONResponse(errors.New("Subscription does not exist"))
|
||||
}
|
||||
|
||||
subscription.Unsubscribe()
|
||||
|
||||
delete(subscriptions, C.GoString(subsID))
|
||||
|
||||
return makeJSONResponse(nil)
|
||||
}
|
||||
|
||||
//export gowaku_peers
|
||||
//export waku_peers
|
||||
// Retrieve the list of peers known by the waku node
|
||||
func gowaku_peers(nodeID C.int) *C.char {
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
wakuNode, ok := nodes[int(nodeID)]
|
||||
if !ok || wakuNode == nil {
|
||||
func waku_peers() *C.char {
|
||||
if wakuNode == nil {
|
||||
return makeJSONResponse(ErrWakuNodeNotReady)
|
||||
}
|
||||
|
||||
|
@ -558,114 +367,38 @@ func gowaku_peers(nodeID C.int) *C.char {
|
|||
return prepareJSONResponse(peers, err)
|
||||
}
|
||||
|
||||
func unmarshalPubkey(pub []byte) (*ecdsa.PublicKey, error) {
|
||||
func unmarshalPubkey(pub []byte) (ecdsa.PublicKey, error) {
|
||||
x, y := elliptic.Unmarshal(secp256k1.S256(), pub)
|
||||
if x == nil {
|
||||
return nil, errors.New("invalid public key")
|
||||
return ecdsa.PublicKey{}, errors.New("invalid public key")
|
||||
}
|
||||
return &ecdsa.PublicKey{Curve: secp256k1.S256(), X: x, Y: y}, nil
|
||||
return ecdsa.PublicKey{Curve: secp256k1.S256(), X: x, Y: y}, nil
|
||||
}
|
||||
|
||||
//export gowaku_encode_data
|
||||
// Encode a byte array. `keyType` defines the type of key to use: `NONE`,
|
||||
// `ASYMMETRIC` and `SYMMETRIC`. `version` is used to define the type of
|
||||
// payload encryption:
|
||||
// When `version` is 0
|
||||
// - No encryption is used
|
||||
// When `version` is 1
|
||||
// - If using `ASYMMETRIC` encoding, `key` must contain a secp256k1 public key
|
||||
// to encrypt the data with,
|
||||
// - If using `SYMMETRIC` encoding, `key` must contain a 32 bytes symmetric key.
|
||||
// The `signingKey` can contain an optional secp256k1 private key to sign the
|
||||
// encoded message, otherwise NULL can be used.
|
||||
func gowaku_encode_data(data *C.char, keyType *C.char, key *C.char, signingKey *C.char, version C.int) *C.char {
|
||||
keyInfo := &node.KeyInfo{
|
||||
Kind: node.KeyKind(C.GoString(keyType)),
|
||||
}
|
||||
|
||||
keyBytes, err := hexutil.Decode(C.GoString(key))
|
||||
//export waku_decode_symmetric
|
||||
// Decode a waku message using a 32 bytes symmetric key. The key must be a hex encoded string with "0x" prefix
|
||||
func waku_decode_symmetric(messageJSON *C.char, symmetricKey *C.char) *C.char {
|
||||
var msg pb.WakuMessage
|
||||
err := json.Unmarshal([]byte(C.GoString(messageJSON)), &msg)
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
}
|
||||
|
||||
if signingKey != nil {
|
||||
signingKeyBytes, err := hexutil.Decode(C.GoString(signingKey))
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
}
|
||||
|
||||
privK, err := crypto.ToECDSA(signingKeyBytes)
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
}
|
||||
keyInfo.PrivKey = privK
|
||||
}
|
||||
|
||||
switch keyInfo.Kind {
|
||||
case node.Symmetric:
|
||||
keyInfo.SymKey = keyBytes
|
||||
case node.Asymmetric:
|
||||
pubK, err := unmarshalPubkey(keyBytes)
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
}
|
||||
keyInfo.PubKey = *pubK
|
||||
}
|
||||
|
||||
b, err := base64.StdEncoding.DecodeString(C.GoString(data))
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
}
|
||||
|
||||
payload := node.Payload{
|
||||
Data: b,
|
||||
Key: keyInfo,
|
||||
}
|
||||
|
||||
response, err := payload.Encode(uint32(version))
|
||||
return prepareJSONResponse(response, err)
|
||||
}
|
||||
|
||||
//export gowaku_decode_data
|
||||
// Decode a byte array. `keyType` defines the type of key used: `NONE`,
|
||||
// `ASYMMETRIC` and `SYMMETRIC`. `version` is used to define the type of
|
||||
// encryption that was used in the payload:
|
||||
// When `version` is 0
|
||||
// - No encryption was used. It will return the original message payload
|
||||
// When `version` is 1
|
||||
// - If using `ASYMMETRIC` encoding, `key` must contain a secp256k1 public key
|
||||
// to decrypt the data with,
|
||||
// - If using `SYMMETRIC` encoding, `key` must contain a 32 bytes symmetric key.
|
||||
func gowaku_decode_data(data *C.char, keyType *C.char, key *C.char, version C.int) *C.char {
|
||||
b, err := base64.StdEncoding.DecodeString(C.GoString(data))
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
if msg.Version == 0 {
|
||||
return prepareJSONResponse(msg.Payload, nil)
|
||||
} else if msg.Version > 1 {
|
||||
return makeJSONResponse(errors.New("unsupported wakumessage version"))
|
||||
}
|
||||
|
||||
keyInfo := &node.KeyInfo{
|
||||
Kind: node.KeyKind(C.GoString(keyType)),
|
||||
Kind: node.Symmetric,
|
||||
}
|
||||
|
||||
keyBytes, err := hexutil.Decode(C.GoString(key))
|
||||
keyInfo.SymKey, err = hexutil.Decode(C.GoString(symmetricKey))
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
}
|
||||
|
||||
switch keyInfo.Kind {
|
||||
case node.Symmetric:
|
||||
keyInfo.SymKey = keyBytes
|
||||
case node.Asymmetric:
|
||||
privK, err := crypto.ToECDSA(keyBytes)
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
}
|
||||
keyInfo.PrivKey = privK
|
||||
}
|
||||
|
||||
msg := pb.WakuMessage{
|
||||
Payload: b,
|
||||
Version: uint32(version),
|
||||
}
|
||||
payload, err := node.DecodePayload(&msg, keyInfo)
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
|
@ -686,9 +419,58 @@ func gowaku_decode_data(data *C.char, keyType *C.char, key *C.char, version C.in
|
|||
return prepareJSONResponse(response, err)
|
||||
}
|
||||
|
||||
//export gowaku_utils_base64_decode
|
||||
//export waku_decode_asymmetric
|
||||
// Decode a waku message using a secp256k1 private key. The key must be a hex encoded string with "0x" prefix
|
||||
func waku_decode_asymmetric(messageJSON *C.char, privateKey *C.char) *C.char {
|
||||
var msg pb.WakuMessage
|
||||
err := json.Unmarshal([]byte(C.GoString(messageJSON)), &msg)
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
}
|
||||
|
||||
if msg.Version == 0 {
|
||||
return prepareJSONResponse(msg.Payload, nil)
|
||||
} else if msg.Version > 1 {
|
||||
return makeJSONResponse(errors.New("unsupported wakumessage version"))
|
||||
}
|
||||
|
||||
keyInfo := &node.KeyInfo{
|
||||
Kind: node.Asymmetric,
|
||||
}
|
||||
|
||||
keyBytes, err := hexutil.Decode(C.GoString(privateKey))
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
}
|
||||
|
||||
keyInfo.PrivKey, err = crypto.ToECDSA(keyBytes)
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
}
|
||||
|
||||
payload, err := node.DecodePayload(&msg, keyInfo)
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
}
|
||||
|
||||
response := struct {
|
||||
PubKey string `json:"pubkey"`
|
||||
Signature string `json:"signature"`
|
||||
Data []byte `json:"data"`
|
||||
Padding []byte `json:"padding"`
|
||||
}{
|
||||
PubKey: hexutil.Encode(crypto.FromECDSAPub(payload.PubKey)),
|
||||
Signature: hexutil.Encode(payload.Signature),
|
||||
Data: payload.Data,
|
||||
Padding: payload.Padding,
|
||||
}
|
||||
|
||||
return prepareJSONResponse(response, err)
|
||||
}
|
||||
|
||||
//export waku_utils_base64_decode
|
||||
// Decode a base64 string (useful for reading the payload from waku messages)
|
||||
func gowaku_utils_base64_decode(data *C.char) *C.char {
|
||||
func waku_utils_base64_decode(data *C.char) *C.char {
|
||||
b, err := base64.StdEncoding.DecodeString(C.GoString(data))
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
|
@ -697,21 +479,20 @@ func gowaku_utils_base64_decode(data *C.char) *C.char {
|
|||
return prepareJSONResponse(string(b), nil)
|
||||
}
|
||||
|
||||
//export gowaku_utils_base64_encode
|
||||
//export waku_utils_base64_encode
|
||||
// Encode data to base64 (useful for creating the payload of a waku message in the
|
||||
// format understood by gowaku_relay_publish)
|
||||
func gowaku_utils_base64_encode(data *C.char) *C.char {
|
||||
// format understood by waku_relay_publish)
|
||||
func waku_utils_base64_encode(data *C.char) *C.char {
|
||||
str := base64.StdEncoding.EncodeToString([]byte(C.GoString(data)))
|
||||
return C.CString(string(str))
|
||||
|
||||
}
|
||||
|
||||
//export waku_utils_free
|
||||
// Frees a char* since all strings returned by gowaku are allocated in the C heap using malloc.
|
||||
func waku_utils_free(data *C.char) {
|
||||
C.free(unsafe.Pointer(data))
|
||||
}
|
||||
|
||||
// TODO:
|
||||
// connected/disconnected
|
||||
// dns discovery
|
||||
// func gowaku_relay_publish_msg(msg C.WakuMessage, pubsubTopic *C.char, ms C.int) *C.char
|
||||
// getFastestPeer(protocol)
|
||||
// getRandomPeer(protocol)
|
||||
// func (wakuLP *WakuLightPush) PublishToTopic(ctx context.Context, message *pb.WakuMessage, topic string, peer, requestId nil) ([]byte, error) {
|
||||
// func (wakuLP *WakuLightPush) Publish(ctx context.Context, message *pb.WakuMessage, peer, requestId nil) ([]byte, error) {
|
||||
// func (query)
|
||||
|
|
|
@ -0,0 +1,96 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"C"
|
||||
|
||||
"github.com/status-im/go-waku/waku/v2/protocol/pb"
|
||||
)
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/ethereum/go-ethereum/common/hexutil"
|
||||
"github.com/libp2p/go-libp2p-core/peer"
|
||||
"github.com/status-im/go-waku/waku/v2/protocol/lightpush"
|
||||
)
|
||||
|
||||
func lightpushPublish(msg pb.WakuMessage, pubsubTopic string, peerID string, ms int) (string, error) {
|
||||
if wakuNode == nil {
|
||||
return "", ErrWakuNodeNotReady
|
||||
}
|
||||
|
||||
var ctx context.Context
|
||||
var cancel context.CancelFunc
|
||||
|
||||
if ms > 0 {
|
||||
ctx, cancel = context.WithTimeout(context.Background(), time.Duration(int(ms))*time.Millisecond)
|
||||
defer cancel()
|
||||
} else {
|
||||
ctx = context.Background()
|
||||
}
|
||||
|
||||
var lpOptions []lightpush.LightPushOption
|
||||
if peerID != "" {
|
||||
p, err := peer.Decode(peerID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
lpOptions = append(lpOptions, lightpush.WithPeer(p))
|
||||
} else {
|
||||
lpOptions = append(lpOptions, lightpush.WithAutomaticPeerSelection(wakuNode.Host()))
|
||||
}
|
||||
|
||||
hash, err := wakuNode.Lightpush().PublishToTopic(ctx, &msg, pubsubTopic, lpOptions...)
|
||||
return hexutil.Encode(hash), err
|
||||
}
|
||||
|
||||
//export waku_lightpush_publish
|
||||
// Publish a message using waku lightpush. Use NULL for topic to use the default pubsub topic..
|
||||
// peerID should contain the ID of a peer supporting the lightpush protocol. Use NULL to automatically select a node
|
||||
// If ms is greater than 0, the broadcast of the message must happen before the timeout
|
||||
// (in milliseconds) is reached, or an error will be returned
|
||||
func waku_lightpush_publish(messageJSON *C.char, topic *C.char, peerID *C.char, ms C.int) *C.char {
|
||||
msg, err := wakuMessage(C.GoString(messageJSON))
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
}
|
||||
|
||||
hash, err := lightpushPublish(msg, getTopic(topic), C.GoString(peerID), int(ms))
|
||||
return prepareJSONResponse(hash, err)
|
||||
}
|
||||
|
||||
//export waku_lightpush_publish_enc_asymmetric
|
||||
// Publish a message encrypted with a secp256k1 public key using waku lightpush. Use NULL for topic to use the default pubsub topic.
|
||||
// peerID should contain the ID of a peer supporting the lightpush protocol. Use NULL to automatically select a node
|
||||
// publicKey must be a hex string prefixed with "0x" containing a valid secp256k1 public key.
|
||||
// optionalSigningKey is an optional hex string prefixed with "0x" containing a valid secp256k1 private key for signing the message. Use NULL otherwise
|
||||
// If ms is greater than 0, the broadcast of the message must happen before the timeout
|
||||
// (in milliseconds) is reached, or an error will be returned.
|
||||
func waku_lightpush_publish_enc_asymmetric(messageJSON *C.char, topic *C.char, peerID *C.char, publicKey *C.char, optionalSigningKey *C.char, ms C.int) *C.char {
|
||||
msg, err := wakuMessageAsymmetricEncoding(C.GoString(messageJSON), C.GoString(publicKey), C.GoString(optionalSigningKey))
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
}
|
||||
|
||||
hash, err := lightpushPublish(msg, getTopic(topic), C.GoString(peerID), int(ms))
|
||||
|
||||
return prepareJSONResponse(hash, err)
|
||||
}
|
||||
|
||||
//export waku_lightpush_publish_enc_symmetric
|
||||
// Publish a message encrypted with a 32 bytes symmetric key using waku relay. Use NULL for topic to use the default pubsub topic.
|
||||
// peerID should contain the ID of a peer supporting the lightpush protocol. Use NULL to automatically select a node
|
||||
// publicKey must be a hex string prefixed with "0x" containing a 32 bytes symmetric key
|
||||
// optionalSigningKey is an optional hex string prefixed with "0x" containing a valid secp256k1 private key for signing the message. Use NULL otherwise
|
||||
// If ms is greater than 0, the broadcast of the message must happen before the timeout
|
||||
// (in milliseconds) is reached, or an error will be returned.
|
||||
func waku_lightpush_publish_enc_symmetric(messageJSON *C.char, topic *C.char, peerID *C.char, symmetricKey *C.char, optionalSigningKey *C.char, ms C.int) *C.char {
|
||||
msg, err := wakuMessageSymmetricEncoding(C.GoString(messageJSON), C.GoString(symmetricKey), C.GoString(optionalSigningKey))
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
}
|
||||
|
||||
hash, err := lightpushPublish(msg, getTopic(topic), C.GoString(peerID), int(ms))
|
||||
|
||||
return prepareJSONResponse(hash, err)
|
||||
}
|
|
@ -0,0 +1,174 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"C"
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/ethereum/go-ethereum/common/hexutil"
|
||||
"github.com/status-im/go-waku/waku/v2/protocol"
|
||||
"github.com/status-im/go-waku/waku/v2/protocol/pb"
|
||||
)
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/status-im/go-waku/waku/v2/protocol/relay"
|
||||
)
|
||||
|
||||
var subscriptions map[string]*relay.Subscription = make(map[string]*relay.Subscription)
|
||||
var mutex sync.Mutex
|
||||
|
||||
//export waku_relay_enough_peers
|
||||
// Determine if there are enough peers to publish a message on a topic. Use NULL
|
||||
// to verify the number of peers in the default pubsub topic
|
||||
func waku_relay_enough_peers(topic *C.char) *C.char {
|
||||
if wakuNode == nil {
|
||||
return makeJSONResponse(ErrWakuNodeNotReady)
|
||||
}
|
||||
|
||||
topicToCheck := protocol.DefaultPubsubTopic().String()
|
||||
if topic != nil {
|
||||
topicToCheck = C.GoString(topic)
|
||||
}
|
||||
|
||||
return prepareJSONResponse(wakuNode.Relay().EnoughPeersToPublishToTopic(topicToCheck), nil)
|
||||
}
|
||||
|
||||
func relayPublish(msg pb.WakuMessage, pubsubTopic string, ms int) (string, error) {
|
||||
if wakuNode == nil {
|
||||
return "", ErrWakuNodeNotReady
|
||||
}
|
||||
|
||||
var ctx context.Context
|
||||
var cancel context.CancelFunc
|
||||
|
||||
if ms > 0 {
|
||||
ctx, cancel = context.WithTimeout(context.Background(), time.Duration(int(ms))*time.Millisecond)
|
||||
defer cancel()
|
||||
} else {
|
||||
ctx = context.Background()
|
||||
}
|
||||
|
||||
hash, err := wakuNode.Relay().PublishToTopic(ctx, &msg, pubsubTopic)
|
||||
return hexutil.Encode(hash), err
|
||||
}
|
||||
|
||||
//export waku_relay_publish
|
||||
// Publish a message using waku relay. Use NULL for topic to use the default pubsub topic
|
||||
// If ms is greater than 0, the broadcast of the message must happen before the timeout
|
||||
// (in milliseconds) is reached, or an error will be returned
|
||||
func waku_relay_publish(messageJSON *C.char, topic *C.char, ms C.int) *C.char {
|
||||
msg, err := wakuMessage(C.GoString(messageJSON))
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
}
|
||||
|
||||
hash, err := relayPublish(msg, getTopic(topic), int(ms))
|
||||
return prepareJSONResponse(hash, err)
|
||||
}
|
||||
|
||||
//export waku_relay_publish_enc_asymmetric
|
||||
// Publish a message encrypted with a secp256k1 public key using waku relay. Use NULL for topic to use the default pubsub topic.
|
||||
// publicKey must be a hex string prefixed with "0x" containing a valid secp256k1 public key.
|
||||
// optionalSigningKey is an optional hex string prefixed with "0x" containing a valid secp256k1 private key for signing the message. Use NULL otherwise
|
||||
// If ms is greater than 0, the broadcast of the message must happen before the timeout
|
||||
// (in milliseconds) is reached, or an error will be returned.
|
||||
func waku_relay_publish_enc_asymmetric(messageJSON *C.char, topic *C.char, publicKey *C.char, optionalSigningKey *C.char, ms C.int) *C.char {
|
||||
msg, err := wakuMessageAsymmetricEncoding(C.GoString(messageJSON), C.GoString(publicKey), C.GoString(optionalSigningKey))
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
}
|
||||
|
||||
hash, err := relayPublish(msg, getTopic(topic), int(ms))
|
||||
|
||||
return prepareJSONResponse(hash, err)
|
||||
}
|
||||
|
||||
//export waku_relay_publish_enc_symmetric
|
||||
// Publish a message encrypted with a 32 bytes symmetric key using waku relay. Use NULL for topic to use the default pubsub topic.
|
||||
// publicKey must be a hex string prefixed with "0x" containing a 32 bytes symmetric key
|
||||
// optionalSigningKey is an optional hex string prefixed with "0x" containing a valid secp256k1 private key for signing the message. Use NULL otherwise
|
||||
// If ms is greater than 0, the broadcast of the message must happen before the timeout
|
||||
// (in milliseconds) is reached, or an error will be returned.
|
||||
func waku_relay_publish_enc_symmetric(messageJSON *C.char, topic *C.char, symmetricKey *C.char, optionalSigningKey *C.char, ms C.int) *C.char {
|
||||
msg, err := wakuMessageSymmetricEncoding(C.GoString(messageJSON), C.GoString(symmetricKey), C.GoString(optionalSigningKey))
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
}
|
||||
|
||||
hash, err := relayPublish(msg, getTopic(topic), int(ms))
|
||||
|
||||
return prepareJSONResponse(hash, err)
|
||||
}
|
||||
|
||||
//export waku_relay_subscribe
|
||||
// Subscribe to a WakuRelay topic. Set the topic to NULL to subscribe
|
||||
// to the default topic. Returns a json response containing the subscription ID
|
||||
// or an error message. When a message is received, a "message" is emitted containing
|
||||
// the message, pubsub topic, and nodeID in which the message was received
|
||||
func waku_relay_subscribe(topic *C.char) *C.char {
|
||||
if wakuNode == nil {
|
||||
return makeJSONResponse(ErrWakuNodeNotReady)
|
||||
}
|
||||
|
||||
topicToSubscribe := protocol.DefaultPubsubTopic().String()
|
||||
if topic != nil {
|
||||
topicToSubscribe = C.GoString(topic)
|
||||
}
|
||||
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
|
||||
subscription, ok := subscriptions[topicToSubscribe]
|
||||
if ok {
|
||||
return makeJSONResponse(nil)
|
||||
}
|
||||
|
||||
subscription, err := wakuNode.Relay().SubscribeToTopic(context.Background(), topicToSubscribe)
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
}
|
||||
|
||||
subscriptions[topicToSubscribe] = subscription
|
||||
|
||||
go func() {
|
||||
for envelope := range subscription.C {
|
||||
send("message", toSubscriptionMessage(envelope))
|
||||
}
|
||||
}()
|
||||
|
||||
return makeJSONResponse(nil)
|
||||
}
|
||||
|
||||
//export waku_relay_unsubscribe
|
||||
// Closes the pubsub subscription to a pubsub topic. Existing subscriptions
|
||||
// will not be closed, but they will stop receiving messages
|
||||
func waku_relay_unsubscribe(topic *C.char) *C.char {
|
||||
if wakuNode == nil {
|
||||
return makeJSONResponse(ErrWakuNodeNotReady)
|
||||
}
|
||||
|
||||
topicToUnsubscribe := protocol.DefaultPubsubTopic().String()
|
||||
if topic != nil {
|
||||
topicToUnsubscribe = C.GoString(topic)
|
||||
}
|
||||
|
||||
mutex.Lock()
|
||||
defer mutex.Unlock()
|
||||
|
||||
subscription, ok := subscriptions[topicToUnsubscribe]
|
||||
if ok {
|
||||
return makeJSONResponse(nil)
|
||||
}
|
||||
|
||||
subscription.Unsubscribe()
|
||||
|
||||
delete(subscriptions, topicToUnsubscribe)
|
||||
|
||||
err := wakuNode.Relay().Unsubscribe(context.Background(), topicToUnsubscribe)
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
}
|
||||
|
||||
return makeJSONResponse(nil)
|
||||
}
|
|
@ -0,0 +1,126 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"C"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/status-im/go-waku/waku/v2/protocol/pb"
|
||||
"github.com/status-im/go-waku/waku/v2/protocol/store"
|
||||
)
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/libp2p/go-libp2p-core/peer"
|
||||
)
|
||||
|
||||
type StorePagingOptions struct {
|
||||
PageSize uint64 `json:"pageSize,omitempty"`
|
||||
Cursor *pb.Index `json:"cursor,omitempty"`
|
||||
Forward bool `json:"forward,omitempty"`
|
||||
}
|
||||
|
||||
type StoreMessagesArgs struct {
|
||||
Topic string `json:"pubsubTopic,omitempty"`
|
||||
ContentFilters []string `json:"contentFilters,omitempty"`
|
||||
StartTime int64 `json:"startTime,omitempty"`
|
||||
EndTime int64 `json:"endTime,omitempty"`
|
||||
PagingOptions StorePagingOptions `json:"pagingOptions,omitempty"`
|
||||
}
|
||||
|
||||
type StoreMessagesReply struct {
|
||||
Messages []*pb.WakuMessage `json:"messages,omitempty"`
|
||||
PagingInfo StorePagingOptions `json:"pagingInfo,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
//export waku_store_query
|
||||
// Query historic messages using waku store protocol.
|
||||
// queryJSON must contain a valid json string with the following format:
|
||||
// {
|
||||
// "pubsubTopic": "...", // optional string
|
||||
// "startTime": 1234, // optional, unix epoch time in nanoseconds
|
||||
// "endTime": 1234, // optional, unix epoch time in nanoseconds
|
||||
// "contentFilters": [ // optional
|
||||
// {
|
||||
// "contentTopic": "..."
|
||||
// }, ...
|
||||
// ],
|
||||
// "pagingOptions": {// optional pagination information
|
||||
// "pageSize": 40, // number
|
||||
// "cursor": { // optional
|
||||
// "digest": ...,
|
||||
// "receiverTime": ...,
|
||||
// "senderTime": ...,
|
||||
// "pubsubTopic" ...,
|
||||
// }
|
||||
// "forward": true, // sort order
|
||||
// }
|
||||
// }
|
||||
// peerID should contain the ID of a peer supporting the lightpush protocol. Use NULL to automatically select a node
|
||||
// If ms is greater than 0, the broadcast of the message must happen before the timeout
|
||||
// (in milliseconds) is reached, or an error will be returned
|
||||
func waku_store_query(queryJSON *C.char, peerID *C.char, ms C.int) *C.char {
|
||||
if wakuNode == nil {
|
||||
return makeJSONResponse(ErrWakuNodeNotReady)
|
||||
}
|
||||
|
||||
var args StoreMessagesArgs
|
||||
err := json.Unmarshal([]byte(C.GoString(queryJSON)), &args)
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
}
|
||||
|
||||
options := []store.HistoryRequestOption{
|
||||
store.WithAutomaticRequestId(),
|
||||
store.WithPaging(args.PagingOptions.Forward, args.PagingOptions.PageSize),
|
||||
store.WithCursor(args.PagingOptions.Cursor),
|
||||
}
|
||||
|
||||
pid := C.GoString(peerID)
|
||||
if pid != "" {
|
||||
p, err := peer.Decode(pid)
|
||||
if err != nil {
|
||||
return makeJSONResponse(err)
|
||||
}
|
||||
options = append(options, store.WithPeer(p))
|
||||
} else {
|
||||
options = append(options, store.WithAutomaticPeerSelection())
|
||||
}
|
||||
|
||||
reply := StoreMessagesReply{}
|
||||
|
||||
var ctx context.Context
|
||||
var cancel context.CancelFunc
|
||||
|
||||
if ms > 0 {
|
||||
ctx, cancel = context.WithTimeout(context.Background(), time.Duration(int(ms))*time.Millisecond)
|
||||
defer cancel()
|
||||
} else {
|
||||
ctx = context.Background()
|
||||
}
|
||||
|
||||
res, err := wakuNode.Store().Query(
|
||||
ctx,
|
||||
store.Query{
|
||||
Topic: args.Topic,
|
||||
ContentTopics: args.ContentFilters,
|
||||
StartTime: args.StartTime,
|
||||
EndTime: args.EndTime,
|
||||
},
|
||||
options...,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
reply.Error = err.Error()
|
||||
return prepareJSONResponse(reply, nil)
|
||||
}
|
||||
reply.Messages = res.Messages
|
||||
reply.PagingInfo = StorePagingOptions{
|
||||
PageSize: args.PagingOptions.PageSize,
|
||||
Cursor: res.Cursor(),
|
||||
Forward: args.PagingOptions.Forward,
|
||||
}
|
||||
|
||||
return prepareJSONResponse(reply, nil)
|
||||
}
|
|
@ -0,0 +1,99 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/ethereum/go-ethereum/common/hexutil"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
"github.com/status-im/go-waku/waku/v2/node"
|
||||
"github.com/status-im/go-waku/waku/v2/protocol/pb"
|
||||
)
|
||||
|
||||
func wakuMessage(messageJSON string) (pb.WakuMessage, error) {
|
||||
var msg pb.WakuMessage
|
||||
err := json.Unmarshal([]byte(messageJSON), &msg)
|
||||
msg.Version = 0
|
||||
return msg, err
|
||||
}
|
||||
|
||||
func wakuMessageSymmetricEncoding(messageJSON string, publicKey string, optionalSigningKey string) (pb.WakuMessage, error) {
|
||||
msg, err := wakuMessage(messageJSON)
|
||||
if err != nil {
|
||||
return msg, err
|
||||
}
|
||||
|
||||
payload := node.Payload{
|
||||
Data: msg.Payload,
|
||||
Key: &node.KeyInfo{
|
||||
Kind: node.Asymmetric,
|
||||
},
|
||||
}
|
||||
|
||||
keyBytes, err := hexutil.Decode(publicKey)
|
||||
if err != nil {
|
||||
return msg, err
|
||||
}
|
||||
|
||||
payload.Key.PubKey, err = unmarshalPubkey(keyBytes)
|
||||
if err != nil {
|
||||
return msg, err
|
||||
}
|
||||
|
||||
if optionalSigningKey != "" {
|
||||
signingKeyBytes, err := hexutil.Decode(optionalSigningKey)
|
||||
if err != nil {
|
||||
return msg, err
|
||||
}
|
||||
|
||||
payload.Key.PrivKey, err = crypto.ToECDSA(signingKeyBytes)
|
||||
if err != nil {
|
||||
return msg, err
|
||||
}
|
||||
}
|
||||
|
||||
msg.Version = 1
|
||||
msg.Payload, err = payload.Encode(1)
|
||||
|
||||
return msg, err
|
||||
}
|
||||
|
||||
func wakuMessageAsymmetricEncoding(messageJSON string, publicKey string, optionalSigningKey string) (pb.WakuMessage, error) {
|
||||
msg, err := wakuMessage(messageJSON)
|
||||
if err != nil {
|
||||
return msg, err
|
||||
}
|
||||
|
||||
payload := node.Payload{
|
||||
Data: msg.Payload,
|
||||
Key: &node.KeyInfo{
|
||||
Kind: node.Asymmetric,
|
||||
},
|
||||
}
|
||||
|
||||
keyBytes, err := hexutil.Decode(publicKey)
|
||||
if err != nil {
|
||||
return msg, err
|
||||
}
|
||||
|
||||
payload.Key.PubKey, err = unmarshalPubkey(keyBytes)
|
||||
if err != nil {
|
||||
return msg, err
|
||||
}
|
||||
|
||||
if optionalSigningKey != "" {
|
||||
signingKeyBytes, err := hexutil.Decode(optionalSigningKey)
|
||||
if err != nil {
|
||||
return msg, err
|
||||
}
|
||||
|
||||
payload.Key.PrivKey, err = crypto.ToECDSA(signingKeyBytes)
|
||||
if err != nil {
|
||||
return msg, err
|
||||
}
|
||||
}
|
||||
|
||||
msg.Version = 1
|
||||
msg.Payload, err = payload.Encode(1)
|
||||
|
||||
return msg, err
|
||||
}
|
|
@ -29,23 +29,21 @@ var mobileSignalHandler MobileSignalHandler
|
|||
|
||||
// SignalEnvelope is a general signal sent upward from node to app
|
||||
type SignalEnvelope struct {
|
||||
NodeID int `json:"nodeId"`
|
||||
Type string `json:"type"`
|
||||
Event interface{} `json:"event"`
|
||||
Type string `json:"type"`
|
||||
Event interface{} `json:"event"`
|
||||
}
|
||||
|
||||
// NewEnvelope creates new envlope of given type and event payload.
|
||||
func NewEnvelope(nodeId int, typ string, event interface{}) *SignalEnvelope {
|
||||
func NewEnvelope(signalType string, event interface{}) *SignalEnvelope {
|
||||
return &SignalEnvelope{
|
||||
NodeID: nodeId,
|
||||
Type: typ,
|
||||
Event: event,
|
||||
Type: signalType,
|
||||
Event: event,
|
||||
}
|
||||
}
|
||||
|
||||
// send sends application signal (in JSON) upwards to application (via default notification handler)
|
||||
func send(node int, typ string, event interface{}) {
|
||||
signal := NewEnvelope(node, typ, event)
|
||||
func send(signalType string, event interface{}) {
|
||||
signal := NewEnvelope(signalType, event)
|
||||
data, err := json.Marshal(&signal)
|
||||
if err != nil {
|
||||
fmt.Println("marshal signal error", err)
|
||||
|
|
Loading…
Reference in New Issue