lib.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. (function(web3){
  2. web3.Lib = {};
  3. var _toRVS = function(data){
  4. var res = {};
  5. var signed = data.signature;
  6. res.r = web3.Utils.toBuffer(signed.slice(0,66));
  7. res.s = web3.Utils.toBuffer("0x"+signed.slice(66,130));
  8. res.v = web3.Utils.bufferToInt(web3.Utils.toBuffer("0x"+signed.slice(130,132)));
  9. res.m = web3.Utils.toBuffer(web3.sha3("\x19Ethereum Signed Message:\n" + data.data.length + data.data));
  10. return res;
  11. }
  12. web3.Lib.signData = function(acc, data){
  13. var hash = web3.sha3(JSON.stringify(data));
  14. var signed = web3.eth.sign(acc, web3.toHex(JSON.stringify(data)));
  15. console.log("Requested sign by account : " + acc);
  16. return {
  17. data : JSON.stringify(data),
  18. dataHash : hash,
  19. signature: signed
  20. };
  21. }
  22. web3.Lib.verifySignature = function(acc, data){
  23. var data = _toRVS(data);
  24. var pubKey = web3.Utils.ecrecover(data.m, data.v, data.r, data.s);
  25. var addrBuf = web3.Utils.pubToAddress(pubKey);
  26. var addr = web3.Utils.bufferToHex(addrBuf);
  27. return acc == addr;
  28. }
  29. web3.db.getString = function(a,k){
  30. return localStorage[a+k];
  31. }
  32. web3.db.putString = function(a,k,v){
  33. localStorage.setItem(a+k,v);
  34. }
  35. web3.Lib.DB = {
  36. _dbname : "defaultDBName",
  37. setJSON : function(k,d){
  38. web3.db.putString(this._dbname, k, JSON.stringify(d));
  39. },
  40. getSON : function(d){
  41. return JSON.parse(web3.db.getString(this._dbname,d));
  42. },
  43. set : function(k,d){
  44. web3.db.putString(this._dbname, k, d);
  45. },
  46. get : function(d){
  47. return web3.db.getString(this._dbname,d);
  48. },
  49. setDB : function(name){
  50. this._dbname = name;
  51. }
  52. };
  53. web3.Lib.initWhisper = function(channel, fn) {
  54. if(typeof channel == undefined)
  55. channel = web3.sha3("[]Custom Lobby").substr(2);
  56. function _setFunction(fn){
  57. EmbarkJS.Messages.listenTo({topic: [channel]}).then(fn);
  58. };
  59. function send(msg){
  60. EmbarkJS.Messages.sendMessage({topic: channel, data: msg});
  61. };
  62. console.log("Whisper version : " + web3.version.whisper);
  63. return new Promise(function(resolve, reject){
  64. web3.version.getWhisper(function(err, res) {
  65. if (err) {
  66. console.log("[!] --> No Whisper - no communication");
  67. reject(err);
  68. } else {
  69. if(fn){
  70. _setFunction(fn);
  71. }
  72. var r = {
  73. func : fn,
  74. channel : channel,
  75. setFunction : _setFunction,
  76. send : send
  77. };
  78. resolve(r);
  79. }
  80. });
  81. });
  82. }
  83. })(web3);