-
-
Save REPTILEHAUS/fd6c826824b82b7b310e8f5c6c07b52f to your computer and use it in GitHub Desktop.
whisper chat demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var chat = { | |
username: "<not set>", | |
topic: "0xfeedbabe", | |
key: "", | |
identity: "", | |
pollInterval: null, | |
filter: null, | |
setUsername: function(name) { | |
this.username = name; | |
return true; | |
}, | |
join: function(password) { | |
// create key from shared secret | |
this.key = shh.generateSymKeyFromPassword(password); | |
// create pub/priv key for identity | |
this.identity = shh.newKeyPair(); | |
pubKey = shh.getPublicKey(this.identity); | |
console.log("identity", pubKey.substr(2, 8)); | |
// create message filter (console doesn't support subscriptions) | |
me = this; | |
this.filter = shh.newMessageFilter({ | |
symKeyID: this.key, | |
topics: [this.topic], | |
}, function(err, message) { | |
if (err) { | |
console.error(err); | |
} else { | |
printMessage(message, me.username); | |
} | |
}); | |
this.say("joined"); | |
return true; | |
}, | |
pollMessages: function() { | |
messages = shh.getFilterMessages(this.filter); | |
for (i = 0; i < messages.length; i++) { | |
printMessage(messages[i], this.username); | |
} | |
} | |
say: function(text) { | |
message = { | |
symKeyId: this.key, | |
topic: this.topic, | |
payload: web3.toHex(this.username + ": " + text), | |
powTime: 5, | |
powTarget: shh.info().minPow, | |
sig: this.identity | |
}; | |
return shh.post(message); | |
} | |
leave: function() { | |
shh.deleteMessageFilter(this.filter); | |
clearInterval(this.pollInterval); | |
this.say("left...") | |
console.log("chat room left"); | |
return true; | |
}, | |
} | |
// start helper functions | |
function time(message) { | |
date = new Date(message.timestamp * 1000); | |
hours = date.getHours(); | |
minutes = "0" + date.getMinutes(); | |
seconds = "0" + date.getSeconds(); | |
return hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2); | |
} | |
function sender(message) { | |
return message.sig.substr(2, 8) | |
} | |
function printMessage(message, myUsername) { | |
line = web3.toAscii(message.payload); | |
parts = line.split(":"); | |
name = parts[0] | |
if (name !== myUsername) { | |
console.log("[" + time(message) + " " + name + "/" + sender(message) + "]" + parts.slice(1).join(":")); | |
} | |
} | |
// end helper functions | |
console.log("Supported functions:"); | |
console.log("* chat.setUsername(<name:string>)"); | |
console.log("* chat.join(<password:string>)"); | |
console.log("* chat.leave()"); | |
console.log("* chat.say(<message:string>)"); | |
console.log(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment