├── lib ├── crypto │ ├── index.js │ ├── hash.js │ ├── tools.js │ └── key.js ├── protocol │ ├── address.js │ ├── pb │ │ ├── payloads.proto │ │ ├── payloads_pb.js │ │ ├── sigchain_pb.js │ │ └── messages_pb.js │ ├── serialize.js │ ├── encryption.js │ └── index.js ├── const.js ├── rpc.js ├── nkn.js └── client.js ├── .circleci └── config.yml ├── Gruntfile.js ├── .gitignore ├── package.json ├── examples └── node_example.js ├── README.md ├── docs └── README-ru.md └── LICENSE /lib/crypto/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Key = require('./key'); 4 | const tools = require('./tools'); 5 | const hash = require('./hash'); 6 | 7 | module.exports = { 8 | Key, 9 | tools, 10 | hash, 11 | } 12 | -------------------------------------------------------------------------------- /lib/protocol/address.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const tools = require('../crypto/tools'); 4 | 5 | module.exports.getPubkey = function (addr) { 6 | // TODO: get dest pk if dest is name rather than pk 7 | let s = addr.split('.'); 8 | return tools.hexToBytes(s[s.length-1]); 9 | } 10 | -------------------------------------------------------------------------------- /lib/const.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = { 4 | errCodes: { 5 | success: 0, 6 | wrongNode: 48001, 7 | }, 8 | defaultOptions: { 9 | reconnectIntervalMin: 1000, 10 | reconnectIntervalMax: 64000, 11 | responseTimeout: 5, 12 | msgHoldingSeconds: 3600, 13 | encrypt: true, 14 | seedRpcServerAddr: 'https://mainnet-rpc-node-0001.nkn.org/mainnet/api/wallet', 15 | }, 16 | }; 17 | -------------------------------------------------------------------------------- /lib/protocol/pb/payloads.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | enum PayloadType { 4 | BINARY = 0; 5 | TEXT = 1; 6 | ACK = 2; 7 | } 8 | 9 | message Message { 10 | bytes payload = 1; 11 | bool encrypted = 2; 12 | bytes nonce = 3; 13 | bytes encrypted_key = 4; 14 | } 15 | 16 | message Payload { 17 | PayloadType type = 1; 18 | bytes pid = 2; 19 | bytes data = 3; 20 | bytes reply_to_pid = 4; 21 | bool no_ack = 5; 22 | } 23 | 24 | message TextData { 25 | string text = 1; 26 | } 27 | -------------------------------------------------------------------------------- /lib/rpc.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | require('es6-promise/auto'); 4 | require('cross-fetch/polyfill'); 5 | 6 | module.exports = rpcCall; 7 | 8 | async function rpcCall(addr, method, params = {}) { 9 | let response = await fetch(addr, { 10 | method: 'POST', 11 | body: JSON.stringify({ 12 | jsonrpc: "2.0", 13 | method: method, 14 | params: params, 15 | }), 16 | }) 17 | 18 | let data = await response.json(); 19 | 20 | if (data.error) { 21 | throw data.error; 22 | } 23 | 24 | return data.result; 25 | } 26 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | jobs: 3 | build: 4 | docker: 5 | - image: circleci/node:7.10 6 | 7 | working_directory: ~/repo 8 | 9 | steps: 10 | - checkout 11 | 12 | - restore_cache: 13 | keys: 14 | - v1-dependencies-{{ checksum "package.json" }} 15 | - v1-dependencies- 16 | 17 | - run: yarn install 18 | 19 | - save_cache: 20 | paths: 21 | - node_modules 22 | key: v1-dependencies-{{ checksum "package.json" }} 23 | 24 | - run: yarn test 25 | -------------------------------------------------------------------------------- /lib/nkn.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Client = require('./client'); 4 | const consts = require('./const'); 5 | const crypto = require('./crypto'); 6 | const protocol = require('./protocol'); 7 | 8 | function nkn(options = {}) { 9 | let key = crypto.Key({ 10 | seed: options.seed, 11 | }); 12 | 13 | Object.keys(options).forEach(key => options[key] === undefined && delete options[key]); 14 | 15 | options = Object.assign({}, consts.defaultOptions, options); 16 | 17 | return Client(key, options.identifier, options); 18 | } 19 | 20 | module.exports = nkn; 21 | module.exports.PayloadType = protocol.payloads.PayloadType; 22 | -------------------------------------------------------------------------------- /Gruntfile.js: -------------------------------------------------------------------------------- 1 | module.exports = function(grunt) { 2 | grunt.initConfig({ 3 | browserify: { 4 | dist: { 5 | files: { 6 | 'dist/nkn.js': [ 'lib/nkn.js' ] 7 | }, 8 | options: { 9 | exclude: ['crypto'], 10 | browserifyOptions: { 11 | standalone: 'nkn' 12 | } 13 | } 14 | } 15 | }, 16 | uglify: { 17 | dist: { 18 | files: { 19 | 'dist/nkn.min.js' : [ 'dist/nkn.js' ] 20 | } 21 | } 22 | } 23 | }); 24 | 25 | grunt.loadNpmTasks('grunt-browserify'); 26 | grunt.loadNpmTasks('grunt-contrib-uglify-es'); 27 | 28 | grunt.registerTask('dist', ['browserify', 'uglify']); 29 | }; 30 | -------------------------------------------------------------------------------- /lib/crypto/hash.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const CryptoJS = require('crypto-js'); 4 | 5 | function cryptoHexStringParse(hexString) { 6 | return CryptoJS.enc.Hex.parse(hexString) 7 | } 8 | 9 | function sha256(str) { 10 | return CryptoJS.SHA256(str).toString(); 11 | } 12 | 13 | function sha256Hex(hexStr) { 14 | return sha256(cryptoHexStringParse(hexStr)); 15 | } 16 | 17 | function doubleSha256(str) { 18 | return CryptoJS.SHA256(CryptoJS.SHA256(str)).toString(); 19 | } 20 | 21 | function doubleSha256Hex(hexStr) { 22 | return CryptoJS.SHA256(CryptoJS.SHA256(cryptoHexStringParse(hexStr))).toString(); 23 | } 24 | 25 | function ripemd160(str) { 26 | return CryptoJS.RIPEMD160(str).toString(); 27 | } 28 | 29 | function ripemd160Hex(hexStr) { 30 | return CryptoJS.RIPEMD160(cryptoHexStringParse(hexStr)).toString(); 31 | } 32 | 33 | module.exports = { 34 | sha256, 35 | sha256Hex, 36 | doubleSha256, 37 | doubleSha256Hex, 38 | ripemd160, 39 | ripemd160Hex, 40 | cryptoHexStringParse, 41 | } 42 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # next.js build output 61 | .next 62 | 63 | # jetbrains 64 | .idea/ 65 | 66 | # others 67 | .DS_Store 68 | -------------------------------------------------------------------------------- /lib/crypto/tools.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const CryptoJS = require('crypto-js'); 4 | const nacl = require('tweetnacl'); 5 | 6 | function hexToBytes(hex) { 7 | for (var bytes = [], c = 0; c < hex.length; c += 2) { 8 | bytes.push(parseInt(hex.substr(c, 2), 16)); 9 | } 10 | return new Uint8Array(bytes); 11 | } 12 | 13 | function bytesToHex(bytes) { 14 | return Array.from(bytes, function(byte) { 15 | return ('0' + (byte & 0xFF).toString(16)).slice(-2) 16 | }).join(''); 17 | } 18 | 19 | var randomBytes; 20 | if (typeof navigator != 'undefined' && navigator.product === "ReactNative") { 21 | randomBytes = require('crypto').randomBytes; 22 | } else { 23 | randomBytes = nacl.randomBytes; 24 | } 25 | 26 | function randomInt32() { 27 | let b = randomBytes(4); 28 | b[0] &= 127 29 | return (b[0]<<24) + (b[1]<<16) + (b[2]<<8) + b[3]; 30 | } 31 | 32 | function paddingSignature(data, len) { 33 | for(let i = 0; i < len - data.length; i++){ 34 | data = '0' + data 35 | } 36 | return data 37 | } 38 | 39 | function mergeBytes(a, b) { 40 | let merged = new Uint8Array(a.length + b.length); 41 | merged.set(a); 42 | merged.set(b, a.length); 43 | return merged; 44 | } 45 | 46 | module.exports = { 47 | hexToBytes, 48 | bytesToHex, 49 | randomBytes, 50 | randomInt32, 51 | paddingSignature, 52 | mergeBytes, 53 | } 54 | -------------------------------------------------------------------------------- /lib/protocol/serialize.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | function encodeUint8(value) { 4 | let buf = Buffer.alloc(1, 0); 5 | buf.writeUInt8(value); 6 | return buf.toString('hex'); 7 | } 8 | 9 | function encodeUint16(value) { 10 | let buf = Buffer.alloc(2, 0); 11 | buf.writeUInt16LE(value); 12 | return buf.toString('hex'); 13 | } 14 | 15 | function encodeUint32(value) { 16 | let buf = Buffer.alloc(4, 0); 17 | buf.writeUInt32LE(value); 18 | return buf.toString('hex'); 19 | } 20 | 21 | function encodeUint64(value) { 22 | if (value >= 0xffffffffffff) { 23 | throw 'Value out of range. 48+ bit integer is not supported in JavaScript' 24 | } 25 | let buf = Buffer.alloc(8, 0); 26 | buf.writeUIntLE(value, 0, 6); 27 | return buf.toString('hex'); 28 | } 29 | 30 | function encodeUint(value) { 31 | if (value < 0xfd) { 32 | return encodeUint8(value); 33 | } else if (value <= 0xffff) { 34 | return 'fd' + encodeUint16(value); 35 | } else if (value <= 0xffffffff) { 36 | return 'fe' + encodeUint32(value); 37 | } else { 38 | return 'ff' + encodeUint64(value); 39 | } 40 | } 41 | 42 | function encodeBytes(value) { 43 | let buf = Buffer.from(value); 44 | return encodeUint(buf.length) + buf.toString('hex'); 45 | } 46 | 47 | function encodeString(value) { 48 | let buf = Buffer.from(value, 'utf8'); 49 | return encodeUint(buf.length) + buf.toString('hex'); 50 | } 51 | 52 | function encodeBool(value) { 53 | return encodeUint8(value ? 1 : 0); 54 | } 55 | 56 | module.exports = { 57 | encodeUint8, 58 | encodeUint16, 59 | encodeUint32, 60 | encodeUint64, 61 | encodeUint, 62 | encodeBytes, 63 | encodeString, 64 | encodeBool, 65 | } 66 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nkn-client", 3 | "version": "0.7.3", 4 | "description": "NKN Client", 5 | "main": "lib/nkn.js", 6 | "directories": { 7 | "lib": "lib" 8 | }, 9 | "scripts": { 10 | "pb": "protoc --js_out=import_style=commonjs,binary:. lib/protocol/pb/*.proto", 11 | "test": "echo \"Error: no test specified\"" 12 | }, 13 | "browserify": { 14 | "transform": [ 15 | [ 16 | "browserify-replace", 17 | { 18 | "replace": [ 19 | { 20 | "from": "var global = Function\\('return this'\\)\\(\\);", 21 | "to": "var global = (function(){ return this }).call(null);" 22 | } 23 | ] 24 | } 25 | ] 26 | ] 27 | }, 28 | "repository": { 29 | "type": "git", 30 | "url": "git+https://github.com/nknorg/nkn-client-js.git" 31 | }, 32 | "keywords": [ 33 | "NKN", 34 | "blockchain", 35 | "distributed system" 36 | ], 37 | "author": "NKN", 38 | "license": "Apache-2.0", 39 | "bugs": { 40 | "url": "https://github.com/nknorg/nkn-client-js/issues" 41 | }, 42 | "homepage": "https://nkn.org", 43 | "dependencies": { 44 | "buffer": "^5.2.1", 45 | "cross-fetch": "^2.2.2", 46 | "crypto-js": "^3.1.9-1", 47 | "ed2curve": "^0.2.1", 48 | "es6-promise": "^4.2.4", 49 | "google-protobuf": "^3.6.1", 50 | "is": "^3.2.1", 51 | "isomorphic-ws": "^4.0.1", 52 | "pako": "^1.0.10", 53 | "tweetnacl": "^1.0.1", 54 | "ws": "^5.2.0" 55 | }, 56 | "devDependencies": { 57 | "browserify-replace": "^1.0.0", 58 | "grunt": "^1.0.2", 59 | "grunt-browserify": "^5.3.0", 60 | "grunt-contrib-uglify-es": "^3.3.0" 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /lib/crypto/key.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const nacl = require('tweetnacl'); 4 | const ed2curve = require('ed2curve'); 5 | const tools = require('./tools'); 6 | 7 | module.exports = Key; 8 | 9 | function Key(options = {}) { 10 | if (!(this instanceof Key)) { 11 | return new Key(options); 12 | } 13 | 14 | let key, seed; 15 | 16 | if (options.seed) { 17 | seed = tools.hexToBytes(options.seed); 18 | } else { 19 | seed = tools.randomBytes(nacl.sign.seedLength); 20 | } 21 | 22 | key = nacl.sign.keyPair.fromSeed(seed); 23 | 24 | this.key = key; 25 | this.publicKey = tools.bytesToHex(key.publicKey); 26 | this.privateKey = tools.bytesToHex(key.secretKey); 27 | this.seed = tools.bytesToHex(seed); 28 | this.curveSecretKey = ed2curve.convertSecretKey(key.secretKey); 29 | this.sharedKeyCache = {}; 30 | } 31 | 32 | Key.prototype.getOrComputeSharedKey = function (otherPubkey) { 33 | if (!this.sharedKeyCache[otherPubkey]) { 34 | let otherCurvePubkey = ed2curve.convertPublicKey(otherPubkey); 35 | this.sharedKeyCache[otherPubkey] = nacl.box.before(otherCurvePubkey, this.curveSecretKey); 36 | } 37 | return this.sharedKeyCache[otherPubkey]; 38 | } 39 | 40 | Key.prototype.encrypt = function (message, destPubkey, options = {}) { 41 | let sharedKey = this.getOrComputeSharedKey(destPubkey); 42 | let nonce = options.nonce || tools.randomBytes(nacl.box.nonceLength); 43 | return { 44 | message: nacl.box.after(message, nonce, sharedKey), 45 | nonce: nonce, 46 | }; 47 | } 48 | 49 | Key.prototype.decrypt = function (encryptedMessage, nonce, srcPubkey, options = {}) { 50 | let sharedKey = this.getOrComputeSharedKey(srcPubkey); 51 | return nacl.box.open.after(encryptedMessage, nonce, sharedKey); 52 | } 53 | 54 | Key.prototype.sign = async function (message) { 55 | let sig = nacl.sign.detached(message, this.key.secretKey); 56 | return tools.paddingSignature(tools.bytesToHex(sig), nacl.sign.signatureLength); 57 | } 58 | -------------------------------------------------------------------------------- /lib/protocol/encryption.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const nacl = require('tweetnacl'); 4 | 5 | const tools = require('../crypto/tools'); 6 | const address = require('./address'); 7 | const protocol = require('.'); 8 | 9 | module.exports.encryptPayload = function (payload, dest) { 10 | if (Array.isArray(dest)) { 11 | let nonce = tools.randomBytes(nacl.secretbox.nonceLength); 12 | let key = tools.randomBytes(nacl.secretbox.keyLength); 13 | let encryptedPayload = nacl.secretbox(payload, nonce, key); 14 | 15 | let msgs = []; 16 | for (var i = 0; i < dest.length; i++) { 17 | let encryptedKey = this.key.encrypt(key, address.getPubkey(dest[i])); 18 | let mergedNonce = tools.mergeBytes(encryptedKey.nonce, nonce); 19 | let msg = protocol.newMessage(encryptedPayload, true, mergedNonce, encryptedKey.message); 20 | msgs.push(msg); 21 | } 22 | return msgs; 23 | } else { 24 | let encrypted = this.key.encrypt(payload, address.getPubkey(dest)); 25 | return protocol.newMessage(encrypted.message, true, encrypted.nonce); 26 | } 27 | } 28 | 29 | module.exports.decryptPayload = function (msg, srcAddr) { 30 | let rawPayload = msg.getPayload(); 31 | let srcPubkey = address.getPubkey(srcAddr) 32 | let nonce = msg.getNonce(); 33 | let encryptedKey = msg.getEncryptedKey(); 34 | let decryptedPayload; 35 | if (encryptedKey && encryptedKey.length > 0) { 36 | if (nonce.length != nacl.box.nonceLength + nacl.secretbox.nonceLength) { 37 | throw "Invalid nonce length." 38 | } 39 | let sharedKey = this.key.decrypt(encryptedKey, nonce.slice(0, nacl.box.nonceLength), srcPubkey); 40 | if (sharedKey === null) { 41 | throw "Decrypt shared key failed." 42 | } 43 | decryptedPayload = nacl.secretbox.open(rawPayload, nonce.slice(nacl.box.nonceLength), sharedKey) 44 | if (decryptedPayload === null) { 45 | throw "Decrypt message failed." 46 | } 47 | } else { 48 | if (nonce.length != nacl.box.nonceLength) { 49 | throw "Invalid nonce length." 50 | } 51 | decryptedPayload = this.key.decrypt(rawPayload, nonce, srcPubkey); 52 | if (decryptedPayload === null) { 53 | throw "Decrypt message failed." 54 | } 55 | } 56 | return decryptedPayload; 57 | } 58 | -------------------------------------------------------------------------------- /examples/node_example.js: -------------------------------------------------------------------------------- 1 | // Example of nkn-client-js for Node.js 2 | // Usage: node node_example.js seedRpcServerAddr timeoutInMilliSeconds 3 | 4 | const crypto = require('crypto'); 5 | const nkn = require('../lib/nkn'); 6 | 7 | // Never put private key in version control system like here! 8 | const seed = '2bc5501d131696429264eb7286c44a29dd44dd66834d9471bd8b0eb875a1edb0'; 9 | const seedRpcServerAddr = process.argv[2]; 10 | const timeout = parseInt(process.argv[3]) || 5000; 11 | const logPrefix = process.argv[4] ? ('[' + process.argv[4] + '] ') : ''; 12 | var timeSent, timeReceived; 13 | 14 | function generateMessage() { 15 | let fromClient = nkn({ 16 | // neither of these are required, as shown in toClient below 17 | identifier: crypto.randomBytes(8).toString('hex'), 18 | seed: seed, 19 | seedRpcServerAddr: seedRpcServerAddr, 20 | }); 21 | 22 | fromClient.on('connect', () => { 23 | try { 24 | let toClient = nkn({ 25 | identifier: crypto.randomBytes(8).toString('hex'), 26 | seedRpcServerAddr: seedRpcServerAddr, 27 | }); 28 | toClient.on('connect', () => { 29 | try { 30 | fromClient.send( 31 | toClient.addr, 32 | 'Hello world!', 33 | // For byte array: 34 | // Uint8Array.from([1,2,3,4,5]), 35 | ).then((data) => { 36 | timeReceived = new Date(); 37 | console.log(logPrefix + 'Receive', '"' + data + '"', 'from', toClient.addr, 'after', timeReceived - timeSent, 'ms'); 38 | }).catch((e) => { 39 | console.log(logPrefix + 'Catch: ', e); 40 | }); 41 | timeSent = new Date(); 42 | console.log(logPrefix + 'Send message from', fromClient.addr, 'to', toClient.addr); 43 | setTimeout(function () { 44 | try { 45 | toClient.close(); 46 | if (timeReceived === undefined) { 47 | console.log(logPrefix + 'Message from', fromClient.nodeAddr, 'to', toClient.nodeAddr, 'timeout'); 48 | } 49 | } catch (e) { 50 | console.error(logPrefix + e); 51 | } 52 | }, timeout); 53 | } catch (e) { 54 | console.error(logPrefix + e); 55 | } 56 | }); 57 | // can also be async (src, payload, payloadType) => {} 58 | toClient.on('message', (src, payload, payloadType, encrypt) => { 59 | timeReceived = new Date(); 60 | var type; 61 | if (payloadType === nkn.PayloadType.TEXT) { 62 | type = 'text'; 63 | } else if (payloadType === nkn.PayloadType.BINARY) { 64 | type = 'binary'; 65 | } 66 | console.log(logPrefix + 'Receive', encrypt ? 'encrypted' : 'unencrypted', type, 'message', '"' + payload + '"','from', src, 'after', timeReceived - timeSent, 'ms'); 67 | // Send a text response 68 | return 'Well received!'; 69 | // For byte array response: 70 | // return Uint8Array.from([1,2,3,4,5]) 71 | }); 72 | setTimeout(function () { 73 | try { 74 | fromClient.close(); 75 | } catch (e) { 76 | console.error(logPrefix + e); 77 | } 78 | }, timeout); 79 | } catch (e) { 80 | console.error(logPrefix + e); 81 | } 82 | }); 83 | } 84 | 85 | generateMessage(); 86 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | **Note: This repo is deprecated in favor of [nkn-sdk-js](https://github.com/nknorg/nkn-sdk-js).** 2 | 3 | [![CircleCI Status](https://circleci.com/gh/nknorg/nkn-client-js.svg?style=shield&circle-token=:circle-token)](https://circleci.com/gh/nknorg/nkn-client-js) 4 | 5 | # nkn-client-js 6 | 7 | [English](/README.md) • 8 | [Русский](/docs/README-ru.md) 9 | 10 | JavaScript implementation of NKN client. 11 | 12 | Send and receive data between any NKN clients without setting up a server. 13 | 14 | Note: This is a **client** version of the NKN protocol, which can send and 15 | receive data but **not** relay data (mining). For **node** implementation which 16 | can mine NKN token by relaying data, please refer to 17 | [nkn](https://github.com/nknorg/nkn/). 18 | 19 | ## Usage 20 | 21 | For npm: 22 | 23 | ```shell 24 | npm install nkn-client 25 | ``` 26 | 27 | And then in your code: 28 | 29 | ```javascript 30 | const nkn = require('nkn-client'); 31 | ``` 32 | 33 | For browser, use `dist/nkn.js` or `dist/nkn.min.js`. 34 | 35 | Create a client with a generated key pair: 36 | 37 | ```javascript 38 | const client = nkn(); 39 | ``` 40 | 41 | Or with an identifier (used to distinguish different clients sharing the same 42 | key pair): 43 | 44 | ```javascript 45 | const client = nkn({ 46 | identifier: 'any string', 47 | }); 48 | ``` 49 | 50 | Get client key pair: 51 | 52 | ```javascript 53 | console.log(client.key.seed, client.key.privateKey, client.key.publicKey); 54 | ``` 55 | 56 | Create a client using an existing secret seed: 57 | 58 | ```javascript 59 | const client = nkn({ 60 | identifier: 'any string', 61 | seed: '2bc5501d131696429264eb7286c44a29dd44dd66834d9471bd8b0eb875a1edb0', 62 | }); 63 | ``` 64 | 65 | Secret seed should be kept **SECRET**! Never put it in version control system 66 | like here. 67 | 68 | By default the client will use bootstrap RPC server (for getting node address) 69 | provided by NKN. Any NKN full node can serve as a bootstrap RPC server. To 70 | create a client using customized bootstrap RPC server: 71 | 72 | ```javascript 73 | const client = nkn({ 74 | identifier: 'any string', 75 | seedRpcServerAddr: 'https://ip:port', 76 | }); 77 | ``` 78 | 79 | Get client identifier: 80 | 81 | ```javascript 82 | console.log(client.identifier); 83 | ``` 84 | 85 | And client NKN address, which is used to receive data from other clients: 86 | 87 | ```javascript 88 | console.log(client.addr); 89 | ``` 90 | 91 | Listen for connection established: 92 | 93 | ```javascript 94 | client.on('connect', () => { 95 | console.log('Connection opened.'); 96 | }); 97 | ``` 98 | 99 | Send text message to other clients: 100 | 101 | ```javascript 102 | client.send( 103 | 'another client address', 104 | 'hello world!', 105 | ); 106 | ``` 107 | 108 | You can also send byte array directly: 109 | 110 | ```javascript 111 | client.send( 112 | 'another client address', 113 | Uint8Array.from([1,2,3,4,5]), 114 | ); 115 | ``` 116 | 117 | Or publish text message to a topic (subscribe is done through [nkn-wallet-js](https://github.com/nknorg/nkn-wallet-js)): 118 | 119 | ```javascript 120 | client.publish( 121 | 'topic', 122 | 'hello world!', 123 | ); 124 | ``` 125 | Receive data from other clients: 126 | 127 | ```javascript 128 | // can also be async (src, payload, payloadType, encrypt) => {} 129 | client.on('message', (src, payload, payloadType, encrypt) => { 130 | if (payloadType === nkn.PayloadType.TEXT) { 131 | console.log('Receive text message:', src, payload); 132 | } else if (payloadType === nkn.PayloadType.BINARY) { 133 | console.log('Receive binary message:', src, payload); 134 | } 135 | console.log('Message is', encrypt ? 'encrypted' : 'unencrypted'); 136 | }); 137 | ``` 138 | 139 | If a valid data (string or Uint8Array) is returned at the end of the handler, 140 | the data will be sent back to sender as response: 141 | 142 | ```javascript 143 | client.on('message', (src, payload, payloadType, encrypt) => { 144 | return 'Well received!'; 145 | // You can also return a byte array: 146 | // return Uint8Array.from([1,2,3,4,5]); 147 | }); 148 | ``` 149 | 150 | Note that if multiple onmessage handlers are added, the result returned by the 151 | first handler (in the order of being added) will be sent as response. 152 | 153 | The `send` method will return a Promise that will be resolved when sender 154 | receives a response, or rejected if not receiving acknowledgement within timeout 155 | period. Similar to message, response can be either string or byte array: 156 | 157 | ```javascript 158 | client.send( 159 | 'another client address', 160 | 'hello world!', 161 | ).then((response) => { 162 | // The response here can be either string or Uint8Array 163 | console.log('Receive response:', response); 164 | }).catch((e) => { 165 | // This will most likely to be timeout 166 | console.log('Catch:', e); 167 | }); 168 | ``` 169 | 170 | Client receiving data will automatically send an acknowledgement back to sender 171 | if no response is returned by any handler so that sender will be able to know if 172 | the packet has been delivered. From the sender's perspective, it's almost the 173 | same as receiving a response, except that the Promise is resolved without a 174 | value: 175 | 176 | ```javascript 177 | client.send( 178 | 'another client address', 179 | 'hello world!', 180 | ).then(() => { 181 | console.log('Receive ACK'); 182 | }).catch((e) => { 183 | // This will most likely to be timeout 184 | console.log('Catch:', e); 185 | }); 186 | ``` 187 | 188 | Timeout for receiving response or acknowledgement can be set when initializing 189 | client: 190 | 191 | ```javascript 192 | const client = nkn({ 193 | responseTimeout: 5, // in seconds 194 | }); 195 | ``` 196 | 197 | or when sending a packet: 198 | 199 | ```javascript 200 | client.send( 201 | 'another client address', 202 | 'Hello world!', 203 | { 204 | responseTimeout: 5, // in seconds 205 | }, 206 | ) 207 | ``` 208 | 209 | Check [examples](examples) for full examples. 210 | 211 | ## Contributing 212 | 213 | **Can I submit a bug, suggestion or feature request?** 214 | 215 | Yes. Please open an issue for that. 216 | 217 | **Can I contribute patches?** 218 | 219 | Yes, we appreciate your help! To make contributions, please fork the repo, push 220 | your changes to the forked repo with signed-off commits, and open a pull request 221 | here. 222 | 223 | Please sign off your commit. This means adding a line "Signed-off-by: Name 224 | " at the end of each commit, indicating that you wrote the code and have 225 | the right to pass it on as an open source patch. This can be done automatically 226 | by adding -s when committing: 227 | 228 | ```shell 229 | git commit -s 230 | ``` 231 | 232 | ## Community 233 | 234 | * [Discord](https://discord.gg/c7mTynX) 235 | * [Telegram](https://t.me/nknorg) 236 | * [Reddit](https://www.reddit.com/r/nknblockchain/) 237 | * [Twitter](https://twitter.com/NKN_ORG) 238 | -------------------------------------------------------------------------------- /docs/README-ru.md: -------------------------------------------------------------------------------- 1 | [![CircleCI Status](https://circleci.com/gh/nknorg/nkn-client-js.svg?style=shield&circle-token=:circle-token)](https://circleci.com/gh/nknorg/nkn-client-js) 2 | 3 | # nkn-client-js 4 | 5 | [English](/README.md) • 6 | [Русский](/docs/README-ru.md) 7 | 8 | JavaScript реализация NKN клиента. 9 | 10 | Отправляйте и принимайте данные от любых NKN клиентов, без поднятии сервера. 11 | 12 | Примечание: Это **клиентская** версия NKN протокола, которая может отправлять 13 | и принимать данные, но **не** транслировать данные (майнинг). Для создания **узла**, 14 | которая может майнить NKN токен через транслирование данных, пожалуйста, перейдите в 15 | [nkn](https://github.com/nknorg/nkn/). 16 | 17 | **Примечание: Этот репозиторий находится на ранней стадии разработки и могут 18 | отсутствовать функции работающие должным образом. Он должен использоваться только 19 | для тестирования** 20 | 21 | ## Применение 22 | 23 | Установите через `npm`: 24 | 25 | ```shell 26 | npm install nkn-client 27 | ``` 28 | 29 | И запустите свой код: 30 | 31 | ```javascript 32 | const nkn = require('nkn-client'); 33 | ``` 34 | 35 | Для браузеров используйте `dist/nkn.js` или `dist/nkn.min.js`. 36 | 37 | Создайте клиент с помощью сгенерированных пар ключей: 38 | 39 | ```javascript 40 | const client = nkn(); 41 | ``` 42 | 43 | Или через идентификатор (используется, чтобы отличить разных клиентов с 44 | одинаковыми парами ключей): 45 | 46 | ```javascript 47 | const client = nkn({ 48 | identifier: 'any string', 49 | }); 50 | ``` 51 | 52 | Получить пару ключей: 53 | 54 | ```javascript 55 | console.log(client.key.seed, client.key.privateKey, client.key.publicKey); 56 | ``` 57 | 58 | Создайте клиент, используя существующий приватный ключ: 59 | 60 | ```javascript 61 | const client = nkn({ 62 | identifier: 'any string', 63 | seed: '2bc5501d131696429264eb7286c44a29dd44dd66834d9471bd8b0eb875a1edb0', 64 | }); 65 | ``` 66 | 67 | По умолчанию, клиент использует загрузочный RPC сервер (чтобы получить адреса узлов) 68 | предоставляемый нами. Любой полный узел NKN может быть использован, в качестве 69 | загрузочного сервера. Чтобы создать клиент используя свой загрузочный RPC сервер, 70 | используйте: 71 | 72 | ```javascript 73 | const client = nkn({ 74 | identifier: 'any string', 75 | seedRpcServerAddr: 'https://ip:port', 76 | }); 77 | ``` 78 | 79 | Приватный ключ должен хранится в **СЕКРЕТЕ**! Никогда не добавляйте его в систему 80 | контроля версии, как здесь. 81 | 82 | Получить идентификатор клиента: 83 | 84 | ```javascript 85 | console.log(client.identifier); 86 | ``` 87 | 88 | И адрес NKN клиента, которая используется для получения данных с других клиентов: 89 | 90 | ```javascript 91 | console.log(client.addr); 92 | ``` 93 | 94 | Событие при установке соединения: 95 | 96 | ```javascript 97 | client.on('connect', () => { 98 | console.log('Connection opened.'); 99 | }); 100 | ``` 101 | 102 | Отправить текстовое сообщение другим клиентам: 103 | 104 | ```javascript 105 | client.send( 106 | 'another client address', 107 | 'hello world!', 108 | ); 109 | ``` 110 | 111 | Также, вы можете напрямую отправить массив байтов: 112 | 113 | ```javascript 114 | client.send( 115 | 'another client address', 116 | Uint8Array.from([1,2,3,4,5]), 117 | ); 118 | ``` 119 | 120 | Получить данные с других клиентов: 121 | 122 | ```javascript 123 | // Также, можно запустить асинхронно 124 | // async (src, payload, payloadType) => {} 125 | client.on('message', (src, payload, payloadType) => { 126 | if (payloadType === nkn.PayloadType.TEXT) { 127 | console.log('Receive text message:', src, payload); 128 | } else if (payloadType === nkn.PayloadType.BINARY) { 129 | console.log('Receive binary message:', src, payload); 130 | } 131 | }); 132 | ``` 133 | 134 | Если в конце обработчик получил валидные данные (string или Uint8Array), 135 | эти данные будут переданы обратно отправителю, в качестве ответа: 136 | 137 | ```javascript 138 | client.on('message', (src, payload, payloadType) => { 139 | return 'Well received!'; 140 | // Также, вы можете вернуть массив байтов 141 | // return Uint8Array.from([1,2,3,4,5]); 142 | }); 143 | ``` 144 | 145 | Обратите внимание, что если в onmessage переданы несколько обработчиков, результат 146 | от первого завершенного обработчика (в добавленном порядке) будет отправлен, 147 | в качестве ответа. 148 | 149 | Метод `send` вернет Promise, который будет выполнен, когда отправитель получит 150 | ответ, или если отправитель отклонил ответ, или не ответил в течение заданного таймаута. 151 | Подобно сообщению, ответ может быть строкой или массивом байтов. 152 | 153 | ```javascript 154 | client.send( 155 | 'another client address', 156 | 'hello world!', 157 | ).then((response) => { 158 | // Здесь ответом может быть string или Uint8Array 159 | console.log('Receive response:', response); 160 | }).catch((e) => { 161 | // Скорее всего, здесь будет таймаут 162 | console.log('Catch:', e); 163 | }); 164 | ``` 165 | 166 | Если ни один обработчик не вернет результат, клиент автоматический 167 | отправит подтверждение отправителю, так отправитель сможет узнать, если 168 | данные были доставлены. Для отправителя это будет точно также, как если бы 169 | он получил ответ, за исключением, что Promise завершится успешно 170 | без каких-либо значении: 171 | 172 | ```javascript 173 | client.send( 174 | 'another client address', 175 | 'hello world!', 176 | ).then(() => { 177 | console.log('Receive ACK'); 178 | }).catch((e) => { 179 | // Скорее всего, здесь будет таймаут 180 | console.log('Catch:', e); 181 | }); 182 | ``` 183 | 184 | Таймаут ожидания ответа или подтверждения может быть установлен, при 185 | инициализации клиента: 186 | 187 | ```javascript 188 | const client = nkn({ 189 | responseTimeout: 5, // в секундах 190 | }); 191 | ``` 192 | 193 | или при отправке данных: 194 | 195 | ```javascript 196 | client.send( 197 | 'another client address', 198 | 'Hello world!', 199 | { 200 | responseTimeout: 5, // в секундах 201 | }, 202 | ) 203 | ``` 204 | 205 | Посмотрите [примеры](examples) для полного понимания. 206 | 207 | ## Внести вклад 208 | 209 | **Могу ли я уведомить, об ошибке или предложить улучшения?** 210 | 211 | Да. Для этого откройте `issue`, пожалуйста! 212 | 213 | **Могу ли я внести исправления?** 214 | 215 | Да, мы ценим вашу помощь! Чтобы внести свой вклад, пожалуйста, 216 | форкните репозиторий, запушьте изменения в форкнутый репозиторий с 217 | подписанными коммитами и откройте `pull request` здесь. 218 | 219 | Пожалуйста, подписывайте свой коммит. Это значит, добавлять строку, в виде 220 | "Signed-off-by: Name ", в конце каждого коммита подтверждая, 221 | что код написан вами и у вас есть права передать его, как исправления с открытым 222 | исходным кодом. Это можно добавлять автоматический добавив `-s`, при коммите: 223 | 224 | ```shell 225 | git commit -s 226 | ``` 227 | 228 | ## Сообщество 229 | 230 | * [Discord](https://discord.gg/c7mTynX) 231 | * [Telegram](https://t.me/nknorg) 232 | * [Reddit](https://www.reddit.com/r/nknblockchain/) 233 | * [Twitter](https://twitter.com/NKN_ORG) 234 | -------------------------------------------------------------------------------- /lib/protocol/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const pako = require('pako'); 4 | const nacl = require('tweetnacl'); 5 | 6 | const hash = require('../crypto/hash'); 7 | const tools = require('../crypto/tools'); 8 | const messages = require('./pb/messages_pb'); 9 | const payloads = require('./pb/payloads_pb'); 10 | const sigchain = require('./pb/sigchain_pb'); 11 | const serialize = require('./serialize'); 12 | const encryption = require('./encryption'); 13 | 14 | const pidSize = 8; // in bytes 15 | const maxClientMessageSize = 4000000; // in bytes. Node is using 4*1024*1024 as limit, we give some additional space for serialization overhead. 16 | const signatureLength = nacl.sign.signatureLength; 17 | 18 | function newPayload(type, replyToPid, data, msgPid) { 19 | let payload = new payloads.Payload(); 20 | payload.setType(type); 21 | if (replyToPid) { 22 | payload.setReplyToPid(replyToPid); 23 | } else if (msgPid) { 24 | payload.setPid(msgPid); 25 | } else { 26 | payload.setPid(tools.randomBytes(pidSize)); 27 | } 28 | payload.setData(data); 29 | return payload; 30 | } 31 | 32 | module.exports.newBinaryPayload = function (data, replyToPid, msgPid) { 33 | return newPayload(payloads.PayloadType.BINARY, replyToPid, data, msgPid); 34 | } 35 | 36 | module.exports.newTextPayload = function (text, replyToPid, msgPid) { 37 | let data = new payloads.TextData(); 38 | data.setText(text); 39 | return newPayload(payloads.PayloadType.TEXT, replyToPid, data.serializeBinary(), msgPid); 40 | } 41 | 42 | module.exports.newAckPayload = function (replyToPid, msgPid) { 43 | return newPayload(payloads.PayloadType.ACK, replyToPid, null, msgPid); 44 | } 45 | 46 | module.exports.newMessage = function (payload, encrypted, nonce, encryptedKey) { 47 | let msg = new payloads.Message(); 48 | msg.setPayload(payload); 49 | msg.setEncrypted(encrypted); 50 | if (nonce) { 51 | msg.setNonce(nonce); 52 | } 53 | if (encryptedKey) { 54 | msg.setEncryptedKey(encryptedKey); 55 | } 56 | return msg; 57 | } 58 | 59 | function newClientMessage(messageType, message, compressionType) { 60 | let msg = new messages.ClientMessage(); 61 | msg.setMessageType(messageType); 62 | msg.setCompressionType(compressionType); 63 | switch (compressionType) { 64 | case messages.CompressionType.COMPRESSION_NONE: 65 | break; 66 | case messages.CompressionType.COMPRESSION_ZLIB: 67 | message = pako.deflate(message); 68 | break; 69 | default: 70 | throw "unknown compression type " + compressionType; 71 | } 72 | msg.setMessage(message); 73 | return msg; 74 | } 75 | 76 | module.exports.newOutboundMessage = async function (dest, payload, maxHoldingSeconds) { 77 | if (!Array.isArray(dest)) { 78 | dest = [dest]; 79 | } 80 | if (dest.length === 0) { 81 | throw "no destination"; 82 | } 83 | 84 | if (!Array.isArray(payload)) { 85 | payload = [payload]; 86 | } 87 | if (payload.length === 0) { 88 | throw "no payloads"; 89 | } 90 | 91 | if (payload.length > 1 && payload.length !== dest.length) { 92 | throw "invalid payload count"; 93 | } 94 | 95 | let sigChainElem = new sigchain.SigChainElem(); 96 | sigChainElem.setNextPubkey(tools.hexToBytes(this.node.pubkey)); 97 | let sigChainElemSerialized = serializeSigChainElem(sigChainElem); 98 | 99 | let sigChain = new sigchain.SigChain(); 100 | sigChain.setNonce(tools.randomInt32()); 101 | if (this.sigChainBlockHash) { 102 | sigChain.setBlockHash(tools.hexToBytes(this.sigChainBlockHash)); 103 | } 104 | sigChain.setSrcId(tools.hexToBytes(addr2Id(this.addr))); 105 | sigChain.setSrcPubkey(tools.hexToBytes(this.key.publicKey)); 106 | 107 | let signatures = []; 108 | let hex, digest, signature; 109 | for (var i = 0; i < dest.length; i++) { 110 | // TODO: handle name service 111 | sigChain.setDestId(tools.hexToBytes(addr2Id(dest[i]))); 112 | sigChain.setDestPubkey(tools.hexToBytes(addr2Pubkey(dest[i]))); 113 | if (payload.length > 1) { 114 | sigChain.setDataSize(payload[i].length); 115 | } else { 116 | sigChain.setDataSize(payload[0].length); 117 | } 118 | hex = serializeSigChainMetadata(sigChain); 119 | digest = hash.sha256Hex(hex); 120 | digest = hash.sha256Hex(digest + sigChainElemSerialized); 121 | signature = await this.key.sign(Buffer.from(digest, 'hex')); 122 | signatures.push(tools.hexToBytes(signature)); 123 | } 124 | 125 | let msg = new messages.OutboundMessage(); 126 | msg.setDestsList(dest); 127 | msg.setPayloadsList(payload); 128 | msg.setMaxHoldingSeconds(maxHoldingSeconds); 129 | msg.setNonce(sigChain.getNonce()); 130 | msg.setBlockHash(sigChain.getBlockHash()); 131 | msg.setSignaturesList(signatures); 132 | 133 | let compressionType; 134 | if (payload.length > 1) { 135 | compressionType = messages.CompressionType.COMPRESSION_ZLIB; 136 | } else { 137 | compressionType = messages.CompressionType.COMPRESSION_NONE; 138 | } 139 | 140 | return newClientMessage(messages.ClientMessageType.OUTBOUND_MESSAGE, msg.serializeBinary(), compressionType); 141 | } 142 | 143 | module.exports.newReceipt = async function (prevSignature) { 144 | let sigChainElem = new sigchain.SigChainElem(); 145 | let sigChainElemSerialized = serializeSigChainElem(sigChainElem); 146 | let digest = hash.sha256Hex(prevSignature); 147 | digest = hash.sha256Hex(digest + sigChainElemSerialized); 148 | let signature = await this.key.sign(Buffer.from(digest, 'hex')); 149 | let msg = new messages.Receipt(); 150 | msg.setPrevSignature(tools.hexToBytes(prevSignature)); 151 | msg.setSignature(tools.hexToBytes(signature)); 152 | return newClientMessage(messages.ClientMessageType.RECEIPT, msg.serializeBinary(), messages.CompressionType.COMPRESSION_NONE); 153 | } 154 | 155 | function serializeSigChainMetadata(sigChain) { 156 | let hex = ''; 157 | hex += serialize.encodeUint32(sigChain.getNonce()); 158 | hex += serialize.encodeUint32(sigChain.getDataSize()); 159 | hex += serialize.encodeBytes(sigChain.getBlockHash()); 160 | hex += serialize.encodeBytes(sigChain.getSrcId()); 161 | hex += serialize.encodeBytes(sigChain.getSrcPubkey()); 162 | hex += serialize.encodeBytes(sigChain.getDestId()); 163 | hex += serialize.encodeBytes(sigChain.getDestPubkey()); 164 | return hex; 165 | } 166 | 167 | function serializeSigChainElem(sigChainElem) { 168 | let hex = ''; 169 | hex += serialize.encodeBytes(sigChainElem.getId()); 170 | hex += serialize.encodeBytes(sigChainElem.getNextPubkey()); 171 | hex += serialize.encodeBool(sigChainElem.getMining()); 172 | return hex; 173 | } 174 | 175 | function addr2Id(addr) { 176 | return hash.sha256(addr) 177 | } 178 | 179 | function addr2Pubkey(addr) { 180 | let s = addr.split('.'); 181 | return s[s.length - 1]; 182 | } 183 | 184 | module.exports.messages = messages; 185 | module.exports.payloads = payloads; 186 | module.exports.pidSize = pidSize; 187 | module.exports.serialize = serialize; 188 | module.exports.encryption = encryption; 189 | module.exports.maxClientMessageSize = maxClientMessageSize; 190 | module.exports.signatureLength = signatureLength; 191 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /lib/client.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | require('es6-promise/auto'); 4 | 5 | const WebSocket = require('isomorphic-ws'); 6 | const Is = require('is'); 7 | 8 | const protocol = require('./protocol'); 9 | const rpcCall = require('./rpc'); 10 | const consts = require('./const'); 11 | const tools = require('./crypto/tools'); 12 | 13 | const TIMEOUT_CHECK_INTERVAL = 250; 14 | 15 | function ResponseProcessor(pid, timeout) { 16 | if (pid instanceof Uint8Array) { 17 | pid = tools.bytesToHex(pid); 18 | } 19 | 20 | let responseHandler = null 21 | let timeoutHandler = null 22 | 23 | let now = Date.now() 24 | let deadline = now + timeout * 1000 25 | 26 | this.checkTimeout = function (now) { 27 | return now > deadline 28 | } 29 | 30 | this.pid = pid 31 | 32 | this.onResponse = function (handler) { 33 | responseHandler = handler 34 | return this 35 | } 36 | 37 | this.onTimeout = function (handler) { 38 | timeoutHandler = handler 39 | return this 40 | } 41 | 42 | this.handleResponse = function (data) { 43 | if(Is.function(responseHandler)) { 44 | responseHandler(data) 45 | } 46 | } 47 | 48 | this.handleTimeout = function () { 49 | if(Is.function(timeoutHandler)) { 50 | timeoutHandler(this.pid) 51 | } 52 | } 53 | } 54 | 55 | function ResponseManager() { 56 | let responseProcessorList = {}; 57 | let timer = null; 58 | 59 | this.setProcessor = function (proceccor) { 60 | responseProcessorList[proceccor.pid] = proceccor 61 | } 62 | 63 | this.clearProcessor = function () { 64 | for(let pid in responseProcessorList) { 65 | responseProcessorList[pid].handleTimeout() 66 | } 67 | responseProcessorList = {} 68 | } 69 | 70 | this.stopProcessor = function () { 71 | clearTimeout(timer); 72 | this.clearProcessor(); 73 | } 74 | 75 | this.callResponseHandler = function (pid, data) { 76 | if (pid instanceof Uint8Array) { 77 | pid = tools.bytesToHex(pid); 78 | } 79 | 80 | if(Is.instanceof(responseProcessorList[pid], ResponseProcessor)) { 81 | responseProcessorList[pid].handleResponse(data) 82 | delete responseProcessorList[pid] 83 | } 84 | } 85 | 86 | function timeoutCheck() { 87 | let timeoutProcessor = [] 88 | let now = Date.now() 89 | for(let pid in responseProcessorList) { 90 | if(responseProcessorList[pid].checkTimeout(now)) { 91 | timeoutProcessor.push(responseProcessorList[pid]) 92 | } 93 | } 94 | 95 | timeoutProcessor.forEach(p => { 96 | p.handleTimeout() 97 | delete responseProcessorList[p.pid] 98 | }) 99 | 100 | timer = setTimeout(timeoutCheck, TIMEOUT_CHECK_INTERVAL) 101 | } 102 | 103 | timeoutCheck() 104 | } 105 | 106 | function messageFromPayload(payload, encrypt, dest) { 107 | if (encrypt) { 108 | return protocol.encryption.encryptPayload.call(this, payload.serializeBinary(), dest); 109 | } 110 | return protocol.newMessage(payload.serializeBinary(), false); 111 | } 112 | 113 | async function sendMsg(dest, data, encrypt, maxHoldingSeconds, replyToPid, msgPid) { 114 | if (Array.isArray(dest)) { 115 | if (dest.length === 0) { 116 | return null; 117 | } 118 | if (dest.length === 1) { 119 | return await sendMsg.call(this, dest[0], data, encrypt, maxHoldingSeconds, replyToPid, msgPid); 120 | } 121 | } 122 | 123 | let payload; 124 | if (Is.string(data)) { 125 | payload = protocol.newTextPayload(data, replyToPid, msgPid); 126 | } else { 127 | payload = protocol.newBinaryPayload(data, replyToPid, msgPid); 128 | } 129 | 130 | let pldMsg = messageFromPayload.call(this, payload, encrypt, dest); 131 | if (Array.isArray(pldMsg)) { 132 | pldMsg = pldMsg.map(pld => pld.serializeBinary()); 133 | } else { 134 | pldMsg = pldMsg.serializeBinary(); 135 | } 136 | 137 | let msgs = []; 138 | if (Array.isArray(pldMsg)) { 139 | let destList = [], pldList = [], totalSize = 0, size = 0; 140 | for (var i = 0; i < pldMsg.length; i++) { 141 | size = pldMsg[i].length + dest[i].length + protocol.signatureLength; 142 | if (size > protocol.maxClientMessageSize) { 143 | throw "message size is greater than " + protocol.maxClientMessageSize + " bytes"; 144 | } 145 | if (totalSize + size > protocol.maxClientMessageSize) { 146 | msgs.push(await protocol.newOutboundMessage.call(this, destList, pldList, maxHoldingSeconds)); 147 | destList = []; 148 | pldList = []; 149 | totalSize = 0; 150 | } 151 | destList.push(dest[i]); 152 | pldList.push(pldMsg[i]); 153 | totalSize += size; 154 | } 155 | msgs.push(await protocol.newOutboundMessage.call(this, destList, pldList, maxHoldingSeconds)); 156 | } else { 157 | if (pldMsg.length + dest.length + protocol.signatureLength > protocol.maxClientMessageSize) { 158 | throw "message size is greater than " + protocol.maxClientMessageSize + " bytes"; 159 | } 160 | msgs.push(await protocol.newOutboundMessage.call(this, dest, pldMsg, maxHoldingSeconds)); 161 | } 162 | 163 | if (msgs.length > 1) { 164 | console.log(`Client message size is greater than ${protocol.maxClientMessageSize} bytes, split into ${msgs.length} batches.`); 165 | } 166 | 167 | msgs.forEach((msg) => { 168 | this.ws.send(msg.serializeBinary()); 169 | }); 170 | 171 | return payload.getPid(); 172 | } 173 | 174 | async function handleInboundMsg(rawMsg) { 175 | let msg = protocol.messages.InboundMessage.deserializeBinary(rawMsg); 176 | 177 | let prevSignature = msg.getPrevSignature(); 178 | if (prevSignature.length > 0) { 179 | prevSignature = tools.bytesToHex(prevSignature); 180 | let receipt = await protocol.newReceipt.call(this, prevSignature); 181 | this.ws.send(receipt.serializeBinary()); 182 | } 183 | 184 | let pldMsg = protocol.payloads.Message.deserializeBinary(msg.getPayload()); 185 | let pldBytes; 186 | if (pldMsg.getEncrypted()) { 187 | pldBytes = protocol.encryption.decryptPayload.call(this, pldMsg, msg.getSrc()); 188 | } else { 189 | pldBytes = pldMsg.getPayload(); 190 | } 191 | let payload = protocol.payloads.Payload.deserializeBinary(pldBytes); 192 | let data = payload.getData(); 193 | 194 | // process data 195 | switch (payload.getType()) { 196 | case protocol.payloads.PayloadType.TEXT: 197 | let textData = protocol.payloads.TextData.deserializeBinary(data); 198 | data = textData.getText(); 199 | break; 200 | case protocol.payloads.PayloadType.ACK: 201 | data = undefined; 202 | break; 203 | } 204 | 205 | // handle response if applicable 206 | if (payload.getReplyToPid().length) { 207 | this.responseManager.callResponseHandler(payload.getReplyToPid(), data, payload.getType()); 208 | return true; 209 | } 210 | 211 | // handle msg 212 | switch (payload.getType()) { 213 | case protocol.payloads.PayloadType.TEXT: 214 | case protocol.payloads.PayloadType.BINARY: 215 | let responses = []; 216 | if (this.eventListeners.message) { 217 | responses = await Promise.all(this.eventListeners.message.map(f => { 218 | try { 219 | return Promise.resolve(f(msg.getSrc(), data, payload.getType(), pldMsg.getEncrypted(), payload.getPid())); 220 | } catch (e) { 221 | console.log(e); 222 | return Promise.resolve(null); 223 | } 224 | })); 225 | } 226 | let responded = false; 227 | for (let response of responses) { 228 | if (response === false) { 229 | return true; 230 | } else if (response !== undefined && response !== null) { 231 | this.send(msg.getSrc(), response, { 232 | encrypt: pldMsg.getEncrypted(), 233 | msgHoldingSeconds: 0, 234 | replyToPid: payload.getPid(), 235 | noReply: true, 236 | }); 237 | responded = true; 238 | break; 239 | } 240 | } 241 | if (!responded) { 242 | await this.sendACK(msg.getSrc(), payload.getPid(), pldMsg.getEncrypted()); 243 | } 244 | return true; 245 | } 246 | 247 | return false; 248 | } 249 | 250 | async function handleMsg(rawMsg) { 251 | let msg = protocol.messages.ClientMessage.deserializeBinary(rawMsg); 252 | switch (msg.getMessageType()) { 253 | case protocol.messages.ClientMessageType.INBOUND_MESSAGE: 254 | return await handleInboundMsg.call(this, msg.getMessage()); 255 | default: 256 | return false 257 | } 258 | } 259 | 260 | function Client(key, identifier, options = {}) { 261 | if (!(this instanceof Client)) { 262 | return new Client(key, identifier, options); 263 | } 264 | 265 | if (typeof identifier === 'object') { 266 | options = identifier; 267 | identifier = undefined; 268 | } 269 | 270 | if (identifier === undefined || identifier === null) { 271 | identifier = ''; 272 | } 273 | 274 | const pubkey = key.publicKey; 275 | const addr = (identifier ? identifier + '.' : '') + pubkey; 276 | 277 | this.key = key; 278 | this.identifier = identifier; 279 | this.options = options; 280 | this.addr = addr; 281 | this.eventListeners = {}; 282 | this.sigChainBlockHash = null; 283 | this.shouldReconnect = false; 284 | this.reconnectInterval = options.reconnectIntervalMin; 285 | this.responseManager = new ResponseManager(); 286 | this.ws = null; 287 | this.node = null; 288 | this.ready = false; 289 | 290 | this.connect(); 291 | }; 292 | 293 | function isTls() { 294 | if (this.options && Is.bool(this.options.tls)) { 295 | return this.options.tls; 296 | } 297 | if (typeof window === 'undefined') { 298 | return false; 299 | } 300 | if (window.location && window.location.protocol === "https:") { 301 | return true; 302 | } 303 | return false; 304 | } 305 | 306 | function newWsAddr(nodeInfo) { 307 | if (!nodeInfo.addr) { 308 | console.log('No address in node info', nodeInfo); 309 | if (this.shouldReconnect) { 310 | this.reconnect(); 311 | } 312 | return; 313 | } 314 | 315 | var ws; 316 | try { 317 | ws = new WebSocket((isTls.call(this) ? 'wss://' : 'ws://') + nodeInfo.addr); 318 | ws.binaryType = "arraybuffer"; 319 | } catch (e) { 320 | console.log('Create WebSocket failed,', e); 321 | if (this.shouldReconnect) { 322 | this.reconnect(); 323 | } 324 | return; 325 | } 326 | 327 | if (this.ws) { 328 | this.ws.onclose = () => {}; 329 | this.ws.close(); 330 | } 331 | 332 | this.ws = ws; 333 | this.node = nodeInfo; 334 | 335 | ws.onopen = () => { 336 | ws.send(JSON.stringify({ 337 | Action: 'setClient', 338 | Addr: this.addr, 339 | })); 340 | this.shouldReconnect = true; 341 | this.reconnectInterval = this.options.reconnectIntervalMin; 342 | }; 343 | 344 | ws.onmessage = async (event) => { 345 | if (event.data instanceof ArrayBuffer) { 346 | try { 347 | let handled = await handleMsg.bind(this)(event.data); 348 | if(!handled) { 349 | console.warn('Unhandled msg.'); 350 | } 351 | } catch (e) { 352 | console.log(e); 353 | } 354 | return; 355 | } 356 | 357 | let msg = JSON.parse(event.data); 358 | if (msg.Error !== undefined && msg.Error !== consts.errCodes.success) { 359 | console.log(msg); 360 | if (msg.Error === consts.errCodes.wrongNode) { 361 | newWsAddr.call(this, msg.Result); 362 | } else if (msg.Action === 'setClient') { 363 | this.ws.close(); 364 | } 365 | return; 366 | } 367 | switch (msg.Action) { 368 | case 'setClient': 369 | this.sigChainBlockHash = msg.Result.sigChainBlockHash; 370 | this.ready = true; 371 | if (this.eventListeners.connect) { 372 | this.eventListeners.connect.forEach(f => f()); 373 | } 374 | break; 375 | case 'updateSigChainBlockHash': 376 | this.sigChainBlockHash = msg.Result; 377 | break; 378 | case 'sendRawBlock': 379 | if (this.eventListeners.block) { 380 | this.eventListeners.block.forEach(f => f(msg.Result)); 381 | } 382 | break; 383 | default: 384 | console.warn('Unknown msg type:', msg.Action); 385 | } 386 | }; 387 | 388 | ws.onclose = () => { 389 | if (this.shouldReconnect) { 390 | console.warn('WebSocket unexpectedly closed.'); 391 | this.reconnect(); 392 | } 393 | }; 394 | 395 | ws.onerror = (err) => { 396 | console.log(err.message); 397 | } 398 | } 399 | 400 | Client.prototype.connect = async function () { 401 | try { 402 | let res = await rpcCall( 403 | this.options.seedRpcServerAddr, 404 | isTls.call(this) ? 'getwssaddr' : 'getwsaddr', 405 | { address: this.addr }, 406 | ); 407 | newWsAddr.call(this, res); 408 | } catch (err) { 409 | console.log('RPC call failed,', err); 410 | if (this.shouldReconnect) { 411 | this.reconnect(); 412 | } 413 | } 414 | }; 415 | 416 | Client.prototype.reconnect = function () { 417 | console.log('Reconnecting in ' + this.reconnectInterval/1000 + 's...'); 418 | setTimeout(() => this.connect(), this.reconnectInterval); 419 | this.reconnectInterval *= 2; 420 | if (this.reconnectInterval > this.options.reconnectIntervalMax) { 421 | this.reconnectInterval = this.options.reconnectIntervalMax; 422 | } 423 | }; 424 | 425 | Client.prototype.on = function (event, func) { 426 | if (this.eventListeners[event]) { 427 | this.eventListeners[event].push(func); 428 | } else { 429 | this.eventListeners[event] = [func]; 430 | } 431 | }; 432 | 433 | function getOrDefault(value, defaultValue) { 434 | if (value === undefined) { 435 | return defaultValue; 436 | } 437 | return value; 438 | } 439 | 440 | Client.prototype.send = async function (dest, data, options = {}) { 441 | let msgHoldingSeconds = getOrDefault(options.msgHoldingSeconds, this.options.msgHoldingSeconds); 442 | let encrypt = getOrDefault(options.encrypt, this.options.encrypt); 443 | 444 | let pid = await sendMsg.call(this, dest, data, encrypt, msgHoldingSeconds, options.replyToPid, options.pid); 445 | if (pid === null || options.noReply) { 446 | return null; 447 | } 448 | 449 | let responseProcessor = new ResponseProcessor(pid, options.responseTimeout || this.options.responseTimeout) 450 | this.responseManager.setProcessor(responseProcessor) 451 | 452 | return await new Promise(function(resolve, reject) { 453 | responseProcessor.onResponse(resolve); 454 | responseProcessor.onTimeout(() => reject('Message timeout.')); 455 | }); 456 | }; 457 | 458 | Client.prototype.sendACK = async function (dest, pid, encrypt) { 459 | if (Array.isArray(dest)) { 460 | if (dest.length === 0) { 461 | return; 462 | } 463 | if (dest.length === 1) { 464 | return await this.sendACK(dest[0], pid, encrypt); 465 | } 466 | if (dest.length > 1 && encrypt) { 467 | console.warn("Encrypted ACK with multicast is not supported, fallback to unicast.") 468 | for (var i = 0; i < dest.length; i++) { 469 | await this.sendACK(dest[i], pid, encrypt); 470 | } 471 | return; 472 | } 473 | } 474 | 475 | let payload = protocol.newAckPayload(pid); 476 | let pldMsg = messageFromPayload.call(this, payload, encrypt, dest); 477 | let msg = protocol.newOutboundMessage.call(this, dest, pldMsg.serializeBinary(), 0); 478 | this.ws.send(msg.serializeBinary()); 479 | }; 480 | 481 | Client.prototype.getSubscribers = function (topic, options = {}) { 482 | options = Object.assign({}, {offset: 0, limit: 1000, meta: false, txPool: false}, options ); 483 | return rpcCall( 484 | this.options.seedRpcServerAddr, 485 | 'getsubscribers', 486 | { topic: topic, offset: options.offset, limit: options.limit, meta: options.meta, txPool: options.txPool }, 487 | ); 488 | } 489 | 490 | Client.prototype.getSubscribersCount = function (topic) { 491 | return rpcCall( 492 | this.options.seedRpcServerAddr, 493 | 'getsubscriberscount', 494 | { topic: topic }, 495 | ); 496 | } 497 | 498 | Client.prototype.getSubscription = function (topic, subscriber) { 499 | return rpcCall( 500 | this.options.seedRpcServerAddr, 501 | 'getsubscription', 502 | { topic: topic, subscriber: subscriber }, 503 | ); 504 | } 505 | 506 | Client.prototype.publish = async function (topic, data, options = {}) { 507 | let offset = 0; 508 | let limit = 1000; 509 | let res = await this.getSubscribers(topic, { offset, limit, txPool: options.txPool || false }); 510 | let subscribers = res.subscribers; 511 | let subscribersInTxPool = res.subscribersInTxPool; 512 | while (res.subscribers && res.subscribers.length >= limit) { 513 | offset += limit; 514 | res = await this.getSubscribers(topic, { offset, limit }); 515 | subscribers = subscribers.concat(res.subscribers); 516 | } 517 | if (options.txPool) { 518 | subscribers = subscribers.concat(subscribersInTxPool); 519 | } 520 | options = Object.assign({}, options, { noReply: true }); 521 | return this.send(subscribers, data, options); 522 | } 523 | 524 | Client.prototype.close = function () { 525 | this.shouldReconnect = false; 526 | this.ws.close(); 527 | this.responseManager.stopProcessor() 528 | }; 529 | 530 | module.exports = Client; 531 | -------------------------------------------------------------------------------- /lib/protocol/pb/payloads_pb.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileoverview 3 | * @enhanceable 4 | * @suppress {messageConventions} JS Compiler reports an error if a variable or 5 | * field starts with 'MSG_' and isn't a translatable message. 6 | * @public 7 | */ 8 | // GENERATED CODE -- DO NOT EDIT! 9 | 10 | var jspb = require('google-protobuf'); 11 | var goog = jspb; 12 | var global = Function('return this')(); 13 | 14 | goog.exportSymbol('proto.Message', null, global); 15 | goog.exportSymbol('proto.Payload', null, global); 16 | goog.exportSymbol('proto.PayloadType', null, global); 17 | goog.exportSymbol('proto.TextData', null, global); 18 | /** 19 | * Generated by JsPbCodeGenerator. 20 | * @param {Array=} opt_data Optional initial data array, typically from a 21 | * server response, or constructed directly in Javascript. The array is used 22 | * in place and becomes part of the constructed object. It is not cloned. 23 | * If no data is provided, the constructed object will be empty, but still 24 | * valid. 25 | * @extends {jspb.Message} 26 | * @constructor 27 | */ 28 | proto.Message = function(opt_data) { 29 | jspb.Message.initialize(this, opt_data, 0, -1, null, null); 30 | }; 31 | goog.inherits(proto.Message, jspb.Message); 32 | if (goog.DEBUG && !COMPILED) { 33 | /** 34 | * @public 35 | * @override 36 | */ 37 | proto.Message.displayName = 'proto.Message'; 38 | } 39 | /** 40 | * Generated by JsPbCodeGenerator. 41 | * @param {Array=} opt_data Optional initial data array, typically from a 42 | * server response, or constructed directly in Javascript. The array is used 43 | * in place and becomes part of the constructed object. It is not cloned. 44 | * If no data is provided, the constructed object will be empty, but still 45 | * valid. 46 | * @extends {jspb.Message} 47 | * @constructor 48 | */ 49 | proto.Payload = function(opt_data) { 50 | jspb.Message.initialize(this, opt_data, 0, -1, null, null); 51 | }; 52 | goog.inherits(proto.Payload, jspb.Message); 53 | if (goog.DEBUG && !COMPILED) { 54 | /** 55 | * @public 56 | * @override 57 | */ 58 | proto.Payload.displayName = 'proto.Payload'; 59 | } 60 | /** 61 | * Generated by JsPbCodeGenerator. 62 | * @param {Array=} opt_data Optional initial data array, typically from a 63 | * server response, or constructed directly in Javascript. The array is used 64 | * in place and becomes part of the constructed object. It is not cloned. 65 | * If no data is provided, the constructed object will be empty, but still 66 | * valid. 67 | * @extends {jspb.Message} 68 | * @constructor 69 | */ 70 | proto.TextData = function(opt_data) { 71 | jspb.Message.initialize(this, opt_data, 0, -1, null, null); 72 | }; 73 | goog.inherits(proto.TextData, jspb.Message); 74 | if (goog.DEBUG && !COMPILED) { 75 | /** 76 | * @public 77 | * @override 78 | */ 79 | proto.TextData.displayName = 'proto.TextData'; 80 | } 81 | 82 | 83 | 84 | if (jspb.Message.GENERATE_TO_OBJECT) { 85 | /** 86 | * Creates an object representation of this proto suitable for use in Soy templates. 87 | * Field names that are reserved in JavaScript and will be renamed to pb_name. 88 | * To access a reserved field use, foo.pb_, eg, foo.pb_default. 89 | * For the list of reserved names please see: 90 | * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. 91 | * @param {boolean=} opt_includeInstance Whether to include the JSPB instance 92 | * for transitional soy proto support: http://goto/soy-param-migration 93 | * @return {!Object} 94 | */ 95 | proto.Message.prototype.toObject = function(opt_includeInstance) { 96 | return proto.Message.toObject(opt_includeInstance, this); 97 | }; 98 | 99 | 100 | /** 101 | * Static version of the {@see toObject} method. 102 | * @param {boolean|undefined} includeInstance Whether to include the JSPB 103 | * instance for transitional soy proto support: 104 | * http://goto/soy-param-migration 105 | * @param {!proto.Message} msg The msg instance to transform. 106 | * @return {!Object} 107 | * @suppress {unusedLocalVariables} f is only used for nested messages 108 | */ 109 | proto.Message.toObject = function(includeInstance, msg) { 110 | var f, obj = { 111 | payload: msg.getPayload_asB64(), 112 | encrypted: jspb.Message.getFieldWithDefault(msg, 2, false), 113 | nonce: msg.getNonce_asB64(), 114 | encryptedKey: msg.getEncryptedKey_asB64() 115 | }; 116 | 117 | if (includeInstance) { 118 | obj.$jspbMessageInstance = msg; 119 | } 120 | return obj; 121 | }; 122 | } 123 | 124 | 125 | /** 126 | * Deserializes binary data (in protobuf wire format). 127 | * @param {jspb.ByteSource} bytes The bytes to deserialize. 128 | * @return {!proto.Message} 129 | */ 130 | proto.Message.deserializeBinary = function(bytes) { 131 | var reader = new jspb.BinaryReader(bytes); 132 | var msg = new proto.Message; 133 | return proto.Message.deserializeBinaryFromReader(msg, reader); 134 | }; 135 | 136 | 137 | /** 138 | * Deserializes binary data (in protobuf wire format) from the 139 | * given reader into the given message object. 140 | * @param {!proto.Message} msg The message object to deserialize into. 141 | * @param {!jspb.BinaryReader} reader The BinaryReader to use. 142 | * @return {!proto.Message} 143 | */ 144 | proto.Message.deserializeBinaryFromReader = function(msg, reader) { 145 | while (reader.nextField()) { 146 | if (reader.isEndGroup()) { 147 | break; 148 | } 149 | var field = reader.getFieldNumber(); 150 | switch (field) { 151 | case 1: 152 | var value = /** @type {!Uint8Array} */ (reader.readBytes()); 153 | msg.setPayload(value); 154 | break; 155 | case 2: 156 | var value = /** @type {boolean} */ (reader.readBool()); 157 | msg.setEncrypted(value); 158 | break; 159 | case 3: 160 | var value = /** @type {!Uint8Array} */ (reader.readBytes()); 161 | msg.setNonce(value); 162 | break; 163 | case 4: 164 | var value = /** @type {!Uint8Array} */ (reader.readBytes()); 165 | msg.setEncryptedKey(value); 166 | break; 167 | default: 168 | reader.skipField(); 169 | break; 170 | } 171 | } 172 | return msg; 173 | }; 174 | 175 | 176 | /** 177 | * Serializes the message to binary data (in protobuf wire format). 178 | * @return {!Uint8Array} 179 | */ 180 | proto.Message.prototype.serializeBinary = function() { 181 | var writer = new jspb.BinaryWriter(); 182 | proto.Message.serializeBinaryToWriter(this, writer); 183 | return writer.getResultBuffer(); 184 | }; 185 | 186 | 187 | /** 188 | * Serializes the given message to binary data (in protobuf wire 189 | * format), writing to the given BinaryWriter. 190 | * @param {!proto.Message} message 191 | * @param {!jspb.BinaryWriter} writer 192 | * @suppress {unusedLocalVariables} f is only used for nested messages 193 | */ 194 | proto.Message.serializeBinaryToWriter = function(message, writer) { 195 | var f = undefined; 196 | f = message.getPayload_asU8(); 197 | if (f.length > 0) { 198 | writer.writeBytes( 199 | 1, 200 | f 201 | ); 202 | } 203 | f = message.getEncrypted(); 204 | if (f) { 205 | writer.writeBool( 206 | 2, 207 | f 208 | ); 209 | } 210 | f = message.getNonce_asU8(); 211 | if (f.length > 0) { 212 | writer.writeBytes( 213 | 3, 214 | f 215 | ); 216 | } 217 | f = message.getEncryptedKey_asU8(); 218 | if (f.length > 0) { 219 | writer.writeBytes( 220 | 4, 221 | f 222 | ); 223 | } 224 | }; 225 | 226 | 227 | /** 228 | * optional bytes payload = 1; 229 | * @return {!(string|Uint8Array)} 230 | */ 231 | proto.Message.prototype.getPayload = function() { 232 | return /** @type {!(string|Uint8Array)} */ (jspb.Message.getFieldWithDefault(this, 1, "")); 233 | }; 234 | 235 | 236 | /** 237 | * optional bytes payload = 1; 238 | * This is a type-conversion wrapper around `getPayload()` 239 | * @return {string} 240 | */ 241 | proto.Message.prototype.getPayload_asB64 = function() { 242 | return /** @type {string} */ (jspb.Message.bytesAsB64( 243 | this.getPayload())); 244 | }; 245 | 246 | 247 | /** 248 | * optional bytes payload = 1; 249 | * Note that Uint8Array is not supported on all browsers. 250 | * @see http://caniuse.com/Uint8Array 251 | * This is a type-conversion wrapper around `getPayload()` 252 | * @return {!Uint8Array} 253 | */ 254 | proto.Message.prototype.getPayload_asU8 = function() { 255 | return /** @type {!Uint8Array} */ (jspb.Message.bytesAsU8( 256 | this.getPayload())); 257 | }; 258 | 259 | 260 | /** @param {!(string|Uint8Array)} value */ 261 | proto.Message.prototype.setPayload = function(value) { 262 | jspb.Message.setProto3BytesField(this, 1, value); 263 | }; 264 | 265 | 266 | /** 267 | * optional bool encrypted = 2; 268 | * Note that Boolean fields may be set to 0/1 when serialized from a Java server. 269 | * You should avoid comparisons like {@code val === true/false} in those cases. 270 | * @return {boolean} 271 | */ 272 | proto.Message.prototype.getEncrypted = function() { 273 | return /** @type {boolean} */ (jspb.Message.getFieldWithDefault(this, 2, false)); 274 | }; 275 | 276 | 277 | /** @param {boolean} value */ 278 | proto.Message.prototype.setEncrypted = function(value) { 279 | jspb.Message.setProto3BooleanField(this, 2, value); 280 | }; 281 | 282 | 283 | /** 284 | * optional bytes nonce = 3; 285 | * @return {!(string|Uint8Array)} 286 | */ 287 | proto.Message.prototype.getNonce = function() { 288 | return /** @type {!(string|Uint8Array)} */ (jspb.Message.getFieldWithDefault(this, 3, "")); 289 | }; 290 | 291 | 292 | /** 293 | * optional bytes nonce = 3; 294 | * This is a type-conversion wrapper around `getNonce()` 295 | * @return {string} 296 | */ 297 | proto.Message.prototype.getNonce_asB64 = function() { 298 | return /** @type {string} */ (jspb.Message.bytesAsB64( 299 | this.getNonce())); 300 | }; 301 | 302 | 303 | /** 304 | * optional bytes nonce = 3; 305 | * Note that Uint8Array is not supported on all browsers. 306 | * @see http://caniuse.com/Uint8Array 307 | * This is a type-conversion wrapper around `getNonce()` 308 | * @return {!Uint8Array} 309 | */ 310 | proto.Message.prototype.getNonce_asU8 = function() { 311 | return /** @type {!Uint8Array} */ (jspb.Message.bytesAsU8( 312 | this.getNonce())); 313 | }; 314 | 315 | 316 | /** @param {!(string|Uint8Array)} value */ 317 | proto.Message.prototype.setNonce = function(value) { 318 | jspb.Message.setProto3BytesField(this, 3, value); 319 | }; 320 | 321 | 322 | /** 323 | * optional bytes encrypted_key = 4; 324 | * @return {!(string|Uint8Array)} 325 | */ 326 | proto.Message.prototype.getEncryptedKey = function() { 327 | return /** @type {!(string|Uint8Array)} */ (jspb.Message.getFieldWithDefault(this, 4, "")); 328 | }; 329 | 330 | 331 | /** 332 | * optional bytes encrypted_key = 4; 333 | * This is a type-conversion wrapper around `getEncryptedKey()` 334 | * @return {string} 335 | */ 336 | proto.Message.prototype.getEncryptedKey_asB64 = function() { 337 | return /** @type {string} */ (jspb.Message.bytesAsB64( 338 | this.getEncryptedKey())); 339 | }; 340 | 341 | 342 | /** 343 | * optional bytes encrypted_key = 4; 344 | * Note that Uint8Array is not supported on all browsers. 345 | * @see http://caniuse.com/Uint8Array 346 | * This is a type-conversion wrapper around `getEncryptedKey()` 347 | * @return {!Uint8Array} 348 | */ 349 | proto.Message.prototype.getEncryptedKey_asU8 = function() { 350 | return /** @type {!Uint8Array} */ (jspb.Message.bytesAsU8( 351 | this.getEncryptedKey())); 352 | }; 353 | 354 | 355 | /** @param {!(string|Uint8Array)} value */ 356 | proto.Message.prototype.setEncryptedKey = function(value) { 357 | jspb.Message.setProto3BytesField(this, 4, value); 358 | }; 359 | 360 | 361 | 362 | 363 | 364 | if (jspb.Message.GENERATE_TO_OBJECT) { 365 | /** 366 | * Creates an object representation of this proto suitable for use in Soy templates. 367 | * Field names that are reserved in JavaScript and will be renamed to pb_name. 368 | * To access a reserved field use, foo.pb_, eg, foo.pb_default. 369 | * For the list of reserved names please see: 370 | * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. 371 | * @param {boolean=} opt_includeInstance Whether to include the JSPB instance 372 | * for transitional soy proto support: http://goto/soy-param-migration 373 | * @return {!Object} 374 | */ 375 | proto.Payload.prototype.toObject = function(opt_includeInstance) { 376 | return proto.Payload.toObject(opt_includeInstance, this); 377 | }; 378 | 379 | 380 | /** 381 | * Static version of the {@see toObject} method. 382 | * @param {boolean|undefined} includeInstance Whether to include the JSPB 383 | * instance for transitional soy proto support: 384 | * http://goto/soy-param-migration 385 | * @param {!proto.Payload} msg The msg instance to transform. 386 | * @return {!Object} 387 | * @suppress {unusedLocalVariables} f is only used for nested messages 388 | */ 389 | proto.Payload.toObject = function(includeInstance, msg) { 390 | var f, obj = { 391 | type: jspb.Message.getFieldWithDefault(msg, 1, 0), 392 | pid: msg.getPid_asB64(), 393 | data: msg.getData_asB64(), 394 | replyToPid: msg.getReplyToPid_asB64(), 395 | noAck: jspb.Message.getFieldWithDefault(msg, 5, false) 396 | }; 397 | 398 | if (includeInstance) { 399 | obj.$jspbMessageInstance = msg; 400 | } 401 | return obj; 402 | }; 403 | } 404 | 405 | 406 | /** 407 | * Deserializes binary data (in protobuf wire format). 408 | * @param {jspb.ByteSource} bytes The bytes to deserialize. 409 | * @return {!proto.Payload} 410 | */ 411 | proto.Payload.deserializeBinary = function(bytes) { 412 | var reader = new jspb.BinaryReader(bytes); 413 | var msg = new proto.Payload; 414 | return proto.Payload.deserializeBinaryFromReader(msg, reader); 415 | }; 416 | 417 | 418 | /** 419 | * Deserializes binary data (in protobuf wire format) from the 420 | * given reader into the given message object. 421 | * @param {!proto.Payload} msg The message object to deserialize into. 422 | * @param {!jspb.BinaryReader} reader The BinaryReader to use. 423 | * @return {!proto.Payload} 424 | */ 425 | proto.Payload.deserializeBinaryFromReader = function(msg, reader) { 426 | while (reader.nextField()) { 427 | if (reader.isEndGroup()) { 428 | break; 429 | } 430 | var field = reader.getFieldNumber(); 431 | switch (field) { 432 | case 1: 433 | var value = /** @type {!proto.PayloadType} */ (reader.readEnum()); 434 | msg.setType(value); 435 | break; 436 | case 2: 437 | var value = /** @type {!Uint8Array} */ (reader.readBytes()); 438 | msg.setPid(value); 439 | break; 440 | case 3: 441 | var value = /** @type {!Uint8Array} */ (reader.readBytes()); 442 | msg.setData(value); 443 | break; 444 | case 4: 445 | var value = /** @type {!Uint8Array} */ (reader.readBytes()); 446 | msg.setReplyToPid(value); 447 | break; 448 | case 5: 449 | var value = /** @type {boolean} */ (reader.readBool()); 450 | msg.setNoAck(value); 451 | break; 452 | default: 453 | reader.skipField(); 454 | break; 455 | } 456 | } 457 | return msg; 458 | }; 459 | 460 | 461 | /** 462 | * Serializes the message to binary data (in protobuf wire format). 463 | * @return {!Uint8Array} 464 | */ 465 | proto.Payload.prototype.serializeBinary = function() { 466 | var writer = new jspb.BinaryWriter(); 467 | proto.Payload.serializeBinaryToWriter(this, writer); 468 | return writer.getResultBuffer(); 469 | }; 470 | 471 | 472 | /** 473 | * Serializes the given message to binary data (in protobuf wire 474 | * format), writing to the given BinaryWriter. 475 | * @param {!proto.Payload} message 476 | * @param {!jspb.BinaryWriter} writer 477 | * @suppress {unusedLocalVariables} f is only used for nested messages 478 | */ 479 | proto.Payload.serializeBinaryToWriter = function(message, writer) { 480 | var f = undefined; 481 | f = message.getType(); 482 | if (f !== 0.0) { 483 | writer.writeEnum( 484 | 1, 485 | f 486 | ); 487 | } 488 | f = message.getPid_asU8(); 489 | if (f.length > 0) { 490 | writer.writeBytes( 491 | 2, 492 | f 493 | ); 494 | } 495 | f = message.getData_asU8(); 496 | if (f.length > 0) { 497 | writer.writeBytes( 498 | 3, 499 | f 500 | ); 501 | } 502 | f = message.getReplyToPid_asU8(); 503 | if (f.length > 0) { 504 | writer.writeBytes( 505 | 4, 506 | f 507 | ); 508 | } 509 | f = message.getNoAck(); 510 | if (f) { 511 | writer.writeBool( 512 | 5, 513 | f 514 | ); 515 | } 516 | }; 517 | 518 | 519 | /** 520 | * optional PayloadType type = 1; 521 | * @return {!proto.PayloadType} 522 | */ 523 | proto.Payload.prototype.getType = function() { 524 | return /** @type {!proto.PayloadType} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); 525 | }; 526 | 527 | 528 | /** @param {!proto.PayloadType} value */ 529 | proto.Payload.prototype.setType = function(value) { 530 | jspb.Message.setProto3EnumField(this, 1, value); 531 | }; 532 | 533 | 534 | /** 535 | * optional bytes pid = 2; 536 | * @return {!(string|Uint8Array)} 537 | */ 538 | proto.Payload.prototype.getPid = function() { 539 | return /** @type {!(string|Uint8Array)} */ (jspb.Message.getFieldWithDefault(this, 2, "")); 540 | }; 541 | 542 | 543 | /** 544 | * optional bytes pid = 2; 545 | * This is a type-conversion wrapper around `getPid()` 546 | * @return {string} 547 | */ 548 | proto.Payload.prototype.getPid_asB64 = function() { 549 | return /** @type {string} */ (jspb.Message.bytesAsB64( 550 | this.getPid())); 551 | }; 552 | 553 | 554 | /** 555 | * optional bytes pid = 2; 556 | * Note that Uint8Array is not supported on all browsers. 557 | * @see http://caniuse.com/Uint8Array 558 | * This is a type-conversion wrapper around `getPid()` 559 | * @return {!Uint8Array} 560 | */ 561 | proto.Payload.prototype.getPid_asU8 = function() { 562 | return /** @type {!Uint8Array} */ (jspb.Message.bytesAsU8( 563 | this.getPid())); 564 | }; 565 | 566 | 567 | /** @param {!(string|Uint8Array)} value */ 568 | proto.Payload.prototype.setPid = function(value) { 569 | jspb.Message.setProto3BytesField(this, 2, value); 570 | }; 571 | 572 | 573 | /** 574 | * optional bytes data = 3; 575 | * @return {!(string|Uint8Array)} 576 | */ 577 | proto.Payload.prototype.getData = function() { 578 | return /** @type {!(string|Uint8Array)} */ (jspb.Message.getFieldWithDefault(this, 3, "")); 579 | }; 580 | 581 | 582 | /** 583 | * optional bytes data = 3; 584 | * This is a type-conversion wrapper around `getData()` 585 | * @return {string} 586 | */ 587 | proto.Payload.prototype.getData_asB64 = function() { 588 | return /** @type {string} */ (jspb.Message.bytesAsB64( 589 | this.getData())); 590 | }; 591 | 592 | 593 | /** 594 | * optional bytes data = 3; 595 | * Note that Uint8Array is not supported on all browsers. 596 | * @see http://caniuse.com/Uint8Array 597 | * This is a type-conversion wrapper around `getData()` 598 | * @return {!Uint8Array} 599 | */ 600 | proto.Payload.prototype.getData_asU8 = function() { 601 | return /** @type {!Uint8Array} */ (jspb.Message.bytesAsU8( 602 | this.getData())); 603 | }; 604 | 605 | 606 | /** @param {!(string|Uint8Array)} value */ 607 | proto.Payload.prototype.setData = function(value) { 608 | jspb.Message.setProto3BytesField(this, 3, value); 609 | }; 610 | 611 | 612 | /** 613 | * optional bytes reply_to_pid = 4; 614 | * @return {!(string|Uint8Array)} 615 | */ 616 | proto.Payload.prototype.getReplyToPid = function() { 617 | return /** @type {!(string|Uint8Array)} */ (jspb.Message.getFieldWithDefault(this, 4, "")); 618 | }; 619 | 620 | 621 | /** 622 | * optional bytes reply_to_pid = 4; 623 | * This is a type-conversion wrapper around `getReplyToPid()` 624 | * @return {string} 625 | */ 626 | proto.Payload.prototype.getReplyToPid_asB64 = function() { 627 | return /** @type {string} */ (jspb.Message.bytesAsB64( 628 | this.getReplyToPid())); 629 | }; 630 | 631 | 632 | /** 633 | * optional bytes reply_to_pid = 4; 634 | * Note that Uint8Array is not supported on all browsers. 635 | * @see http://caniuse.com/Uint8Array 636 | * This is a type-conversion wrapper around `getReplyToPid()` 637 | * @return {!Uint8Array} 638 | */ 639 | proto.Payload.prototype.getReplyToPid_asU8 = function() { 640 | return /** @type {!Uint8Array} */ (jspb.Message.bytesAsU8( 641 | this.getReplyToPid())); 642 | }; 643 | 644 | 645 | /** @param {!(string|Uint8Array)} value */ 646 | proto.Payload.prototype.setReplyToPid = function(value) { 647 | jspb.Message.setProto3BytesField(this, 4, value); 648 | }; 649 | 650 | 651 | /** 652 | * optional bool no_ack = 5; 653 | * Note that Boolean fields may be set to 0/1 when serialized from a Java server. 654 | * You should avoid comparisons like {@code val === true/false} in those cases. 655 | * @return {boolean} 656 | */ 657 | proto.Payload.prototype.getNoAck = function() { 658 | return /** @type {boolean} */ (jspb.Message.getFieldWithDefault(this, 5, false)); 659 | }; 660 | 661 | 662 | /** @param {boolean} value */ 663 | proto.Payload.prototype.setNoAck = function(value) { 664 | jspb.Message.setProto3BooleanField(this, 5, value); 665 | }; 666 | 667 | 668 | 669 | 670 | 671 | if (jspb.Message.GENERATE_TO_OBJECT) { 672 | /** 673 | * Creates an object representation of this proto suitable for use in Soy templates. 674 | * Field names that are reserved in JavaScript and will be renamed to pb_name. 675 | * To access a reserved field use, foo.pb_, eg, foo.pb_default. 676 | * For the list of reserved names please see: 677 | * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. 678 | * @param {boolean=} opt_includeInstance Whether to include the JSPB instance 679 | * for transitional soy proto support: http://goto/soy-param-migration 680 | * @return {!Object} 681 | */ 682 | proto.TextData.prototype.toObject = function(opt_includeInstance) { 683 | return proto.TextData.toObject(opt_includeInstance, this); 684 | }; 685 | 686 | 687 | /** 688 | * Static version of the {@see toObject} method. 689 | * @param {boolean|undefined} includeInstance Whether to include the JSPB 690 | * instance for transitional soy proto support: 691 | * http://goto/soy-param-migration 692 | * @param {!proto.TextData} msg The msg instance to transform. 693 | * @return {!Object} 694 | * @suppress {unusedLocalVariables} f is only used for nested messages 695 | */ 696 | proto.TextData.toObject = function(includeInstance, msg) { 697 | var f, obj = { 698 | text: jspb.Message.getFieldWithDefault(msg, 1, "") 699 | }; 700 | 701 | if (includeInstance) { 702 | obj.$jspbMessageInstance = msg; 703 | } 704 | return obj; 705 | }; 706 | } 707 | 708 | 709 | /** 710 | * Deserializes binary data (in protobuf wire format). 711 | * @param {jspb.ByteSource} bytes The bytes to deserialize. 712 | * @return {!proto.TextData} 713 | */ 714 | proto.TextData.deserializeBinary = function(bytes) { 715 | var reader = new jspb.BinaryReader(bytes); 716 | var msg = new proto.TextData; 717 | return proto.TextData.deserializeBinaryFromReader(msg, reader); 718 | }; 719 | 720 | 721 | /** 722 | * Deserializes binary data (in protobuf wire format) from the 723 | * given reader into the given message object. 724 | * @param {!proto.TextData} msg The message object to deserialize into. 725 | * @param {!jspb.BinaryReader} reader The BinaryReader to use. 726 | * @return {!proto.TextData} 727 | */ 728 | proto.TextData.deserializeBinaryFromReader = function(msg, reader) { 729 | while (reader.nextField()) { 730 | if (reader.isEndGroup()) { 731 | break; 732 | } 733 | var field = reader.getFieldNumber(); 734 | switch (field) { 735 | case 1: 736 | var value = /** @type {string} */ (reader.readString()); 737 | msg.setText(value); 738 | break; 739 | default: 740 | reader.skipField(); 741 | break; 742 | } 743 | } 744 | return msg; 745 | }; 746 | 747 | 748 | /** 749 | * Serializes the message to binary data (in protobuf wire format). 750 | * @return {!Uint8Array} 751 | */ 752 | proto.TextData.prototype.serializeBinary = function() { 753 | var writer = new jspb.BinaryWriter(); 754 | proto.TextData.serializeBinaryToWriter(this, writer); 755 | return writer.getResultBuffer(); 756 | }; 757 | 758 | 759 | /** 760 | * Serializes the given message to binary data (in protobuf wire 761 | * format), writing to the given BinaryWriter. 762 | * @param {!proto.TextData} message 763 | * @param {!jspb.BinaryWriter} writer 764 | * @suppress {unusedLocalVariables} f is only used for nested messages 765 | */ 766 | proto.TextData.serializeBinaryToWriter = function(message, writer) { 767 | var f = undefined; 768 | f = message.getText(); 769 | if (f.length > 0) { 770 | writer.writeString( 771 | 1, 772 | f 773 | ); 774 | } 775 | }; 776 | 777 | 778 | /** 779 | * optional string text = 1; 780 | * @return {string} 781 | */ 782 | proto.TextData.prototype.getText = function() { 783 | return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); 784 | }; 785 | 786 | 787 | /** @param {string} value */ 788 | proto.TextData.prototype.setText = function(value) { 789 | jspb.Message.setProto3StringField(this, 1, value); 790 | }; 791 | 792 | 793 | /** 794 | * @enum {number} 795 | */ 796 | proto.PayloadType = { 797 | BINARY: 0, 798 | TEXT: 1, 799 | ACK: 2 800 | }; 801 | 802 | goog.object.extend(exports, proto); 803 | -------------------------------------------------------------------------------- /lib/protocol/pb/sigchain_pb.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileoverview 3 | * @enhanceable 4 | * @suppress {messageConventions} JS Compiler reports an error if a variable or 5 | * field starts with 'MSG_' and isn't a translatable message. 6 | * @public 7 | */ 8 | // GENERATED CODE -- DO NOT EDIT! 9 | 10 | var jspb = require('google-protobuf'); 11 | var goog = jspb; 12 | var global = Function('return this')(); 13 | 14 | goog.exportSymbol('proto.pb.SigAlgo', null, global); 15 | goog.exportSymbol('proto.pb.SigChain', null, global); 16 | goog.exportSymbol('proto.pb.SigChainElem', null, global); 17 | 18 | /** 19 | * Generated by JsPbCodeGenerator. 20 | * @param {Array=} opt_data Optional initial data array, typically from a 21 | * server response, or constructed directly in Javascript. The array is used 22 | * in place and becomes part of the constructed object. It is not cloned. 23 | * If no data is provided, the constructed object will be empty, but still 24 | * valid. 25 | * @extends {jspb.Message} 26 | * @constructor 27 | */ 28 | proto.pb.SigChainElem = function(opt_data) { 29 | jspb.Message.initialize(this, opt_data, 0, -1, null, null); 30 | }; 31 | goog.inherits(proto.pb.SigChainElem, jspb.Message); 32 | if (goog.DEBUG && !COMPILED) { 33 | proto.pb.SigChainElem.displayName = 'proto.pb.SigChainElem'; 34 | } 35 | 36 | 37 | if (jspb.Message.GENERATE_TO_OBJECT) { 38 | /** 39 | * Creates an object representation of this proto suitable for use in Soy templates. 40 | * Field names that are reserved in JavaScript and will be renamed to pb_name. 41 | * To access a reserved field use, foo.pb_, eg, foo.pb_default. 42 | * For the list of reserved names please see: 43 | * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. 44 | * @param {boolean=} opt_includeInstance Whether to include the JSPB instance 45 | * for transitional soy proto support: http://goto/soy-param-migration 46 | * @return {!Object} 47 | */ 48 | proto.pb.SigChainElem.prototype.toObject = function(opt_includeInstance) { 49 | return proto.pb.SigChainElem.toObject(opt_includeInstance, this); 50 | }; 51 | 52 | 53 | /** 54 | * Static version of the {@see toObject} method. 55 | * @param {boolean|undefined} includeInstance Whether to include the JSPB 56 | * instance for transitional soy proto support: 57 | * http://goto/soy-param-migration 58 | * @param {!proto.pb.SigChainElem} msg The msg instance to transform. 59 | * @return {!Object} 60 | * @suppress {unusedLocalVariables} f is only used for nested messages 61 | */ 62 | proto.pb.SigChainElem.toObject = function(includeInstance, msg) { 63 | var f, obj = { 64 | id: msg.getId_asB64(), 65 | nextPubkey: msg.getNextPubkey_asB64(), 66 | mining: jspb.Message.getFieldWithDefault(msg, 3, false), 67 | signature: msg.getSignature_asB64(), 68 | sigAlgo: jspb.Message.getFieldWithDefault(msg, 5, 0), 69 | vrf: msg.getVrf_asB64(), 70 | proof: msg.getProof_asB64() 71 | }; 72 | 73 | if (includeInstance) { 74 | obj.$jspbMessageInstance = msg; 75 | } 76 | return obj; 77 | }; 78 | } 79 | 80 | 81 | /** 82 | * Deserializes binary data (in protobuf wire format). 83 | * @param {jspb.ByteSource} bytes The bytes to deserialize. 84 | * @return {!proto.pb.SigChainElem} 85 | */ 86 | proto.pb.SigChainElem.deserializeBinary = function(bytes) { 87 | var reader = new jspb.BinaryReader(bytes); 88 | var msg = new proto.pb.SigChainElem; 89 | return proto.pb.SigChainElem.deserializeBinaryFromReader(msg, reader); 90 | }; 91 | 92 | 93 | /** 94 | * Deserializes binary data (in protobuf wire format) from the 95 | * given reader into the given message object. 96 | * @param {!proto.pb.SigChainElem} msg The message object to deserialize into. 97 | * @param {!jspb.BinaryReader} reader The BinaryReader to use. 98 | * @return {!proto.pb.SigChainElem} 99 | */ 100 | proto.pb.SigChainElem.deserializeBinaryFromReader = function(msg, reader) { 101 | while (reader.nextField()) { 102 | if (reader.isEndGroup()) { 103 | break; 104 | } 105 | var field = reader.getFieldNumber(); 106 | switch (field) { 107 | case 1: 108 | var value = /** @type {!Uint8Array} */ (reader.readBytes()); 109 | msg.setId(value); 110 | break; 111 | case 2: 112 | var value = /** @type {!Uint8Array} */ (reader.readBytes()); 113 | msg.setNextPubkey(value); 114 | break; 115 | case 3: 116 | var value = /** @type {boolean} */ (reader.readBool()); 117 | msg.setMining(value); 118 | break; 119 | case 4: 120 | var value = /** @type {!Uint8Array} */ (reader.readBytes()); 121 | msg.setSignature(value); 122 | break; 123 | case 5: 124 | var value = /** @type {!proto.pb.SigAlgo} */ (reader.readEnum()); 125 | msg.setSigAlgo(value); 126 | break; 127 | case 6: 128 | var value = /** @type {!Uint8Array} */ (reader.readBytes()); 129 | msg.setVrf(value); 130 | break; 131 | case 7: 132 | var value = /** @type {!Uint8Array} */ (reader.readBytes()); 133 | msg.setProof(value); 134 | break; 135 | default: 136 | reader.skipField(); 137 | break; 138 | } 139 | } 140 | return msg; 141 | }; 142 | 143 | 144 | /** 145 | * Serializes the message to binary data (in protobuf wire format). 146 | * @return {!Uint8Array} 147 | */ 148 | proto.pb.SigChainElem.prototype.serializeBinary = function() { 149 | var writer = new jspb.BinaryWriter(); 150 | proto.pb.SigChainElem.serializeBinaryToWriter(this, writer); 151 | return writer.getResultBuffer(); 152 | }; 153 | 154 | 155 | /** 156 | * Serializes the given message to binary data (in protobuf wire 157 | * format), writing to the given BinaryWriter. 158 | * @param {!proto.pb.SigChainElem} message 159 | * @param {!jspb.BinaryWriter} writer 160 | * @suppress {unusedLocalVariables} f is only used for nested messages 161 | */ 162 | proto.pb.SigChainElem.serializeBinaryToWriter = function(message, writer) { 163 | var f = undefined; 164 | f = message.getId_asU8(); 165 | if (f.length > 0) { 166 | writer.writeBytes( 167 | 1, 168 | f 169 | ); 170 | } 171 | f = message.getNextPubkey_asU8(); 172 | if (f.length > 0) { 173 | writer.writeBytes( 174 | 2, 175 | f 176 | ); 177 | } 178 | f = message.getMining(); 179 | if (f) { 180 | writer.writeBool( 181 | 3, 182 | f 183 | ); 184 | } 185 | f = message.getSignature_asU8(); 186 | if (f.length > 0) { 187 | writer.writeBytes( 188 | 4, 189 | f 190 | ); 191 | } 192 | f = message.getSigAlgo(); 193 | if (f !== 0.0) { 194 | writer.writeEnum( 195 | 5, 196 | f 197 | ); 198 | } 199 | f = message.getVrf_asU8(); 200 | if (f.length > 0) { 201 | writer.writeBytes( 202 | 6, 203 | f 204 | ); 205 | } 206 | f = message.getProof_asU8(); 207 | if (f.length > 0) { 208 | writer.writeBytes( 209 | 7, 210 | f 211 | ); 212 | } 213 | }; 214 | 215 | 216 | /** 217 | * optional bytes id = 1; 218 | * @return {!(string|Uint8Array)} 219 | */ 220 | proto.pb.SigChainElem.prototype.getId = function() { 221 | return /** @type {!(string|Uint8Array)} */ (jspb.Message.getFieldWithDefault(this, 1, "")); 222 | }; 223 | 224 | 225 | /** 226 | * optional bytes id = 1; 227 | * This is a type-conversion wrapper around `getId()` 228 | * @return {string} 229 | */ 230 | proto.pb.SigChainElem.prototype.getId_asB64 = function() { 231 | return /** @type {string} */ (jspb.Message.bytesAsB64( 232 | this.getId())); 233 | }; 234 | 235 | 236 | /** 237 | * optional bytes id = 1; 238 | * Note that Uint8Array is not supported on all browsers. 239 | * @see http://caniuse.com/Uint8Array 240 | * This is a type-conversion wrapper around `getId()` 241 | * @return {!Uint8Array} 242 | */ 243 | proto.pb.SigChainElem.prototype.getId_asU8 = function() { 244 | return /** @type {!Uint8Array} */ (jspb.Message.bytesAsU8( 245 | this.getId())); 246 | }; 247 | 248 | 249 | /** @param {!(string|Uint8Array)} value */ 250 | proto.pb.SigChainElem.prototype.setId = function(value) { 251 | jspb.Message.setProto3BytesField(this, 1, value); 252 | }; 253 | 254 | 255 | /** 256 | * optional bytes next_pubkey = 2; 257 | * @return {!(string|Uint8Array)} 258 | */ 259 | proto.pb.SigChainElem.prototype.getNextPubkey = function() { 260 | return /** @type {!(string|Uint8Array)} */ (jspb.Message.getFieldWithDefault(this, 2, "")); 261 | }; 262 | 263 | 264 | /** 265 | * optional bytes next_pubkey = 2; 266 | * This is a type-conversion wrapper around `getNextPubkey()` 267 | * @return {string} 268 | */ 269 | proto.pb.SigChainElem.prototype.getNextPubkey_asB64 = function() { 270 | return /** @type {string} */ (jspb.Message.bytesAsB64( 271 | this.getNextPubkey())); 272 | }; 273 | 274 | 275 | /** 276 | * optional bytes next_pubkey = 2; 277 | * Note that Uint8Array is not supported on all browsers. 278 | * @see http://caniuse.com/Uint8Array 279 | * This is a type-conversion wrapper around `getNextPubkey()` 280 | * @return {!Uint8Array} 281 | */ 282 | proto.pb.SigChainElem.prototype.getNextPubkey_asU8 = function() { 283 | return /** @type {!Uint8Array} */ (jspb.Message.bytesAsU8( 284 | this.getNextPubkey())); 285 | }; 286 | 287 | 288 | /** @param {!(string|Uint8Array)} value */ 289 | proto.pb.SigChainElem.prototype.setNextPubkey = function(value) { 290 | jspb.Message.setProto3BytesField(this, 2, value); 291 | }; 292 | 293 | 294 | /** 295 | * optional bool mining = 3; 296 | * Note that Boolean fields may be set to 0/1 when serialized from a Java server. 297 | * You should avoid comparisons like {@code val === true/false} in those cases. 298 | * @return {boolean} 299 | */ 300 | proto.pb.SigChainElem.prototype.getMining = function() { 301 | return /** @type {boolean} */ (jspb.Message.getFieldWithDefault(this, 3, false)); 302 | }; 303 | 304 | 305 | /** @param {boolean} value */ 306 | proto.pb.SigChainElem.prototype.setMining = function(value) { 307 | jspb.Message.setProto3BooleanField(this, 3, value); 308 | }; 309 | 310 | 311 | /** 312 | * optional bytes signature = 4; 313 | * @return {!(string|Uint8Array)} 314 | */ 315 | proto.pb.SigChainElem.prototype.getSignature = function() { 316 | return /** @type {!(string|Uint8Array)} */ (jspb.Message.getFieldWithDefault(this, 4, "")); 317 | }; 318 | 319 | 320 | /** 321 | * optional bytes signature = 4; 322 | * This is a type-conversion wrapper around `getSignature()` 323 | * @return {string} 324 | */ 325 | proto.pb.SigChainElem.prototype.getSignature_asB64 = function() { 326 | return /** @type {string} */ (jspb.Message.bytesAsB64( 327 | this.getSignature())); 328 | }; 329 | 330 | 331 | /** 332 | * optional bytes signature = 4; 333 | * Note that Uint8Array is not supported on all browsers. 334 | * @see http://caniuse.com/Uint8Array 335 | * This is a type-conversion wrapper around `getSignature()` 336 | * @return {!Uint8Array} 337 | */ 338 | proto.pb.SigChainElem.prototype.getSignature_asU8 = function() { 339 | return /** @type {!Uint8Array} */ (jspb.Message.bytesAsU8( 340 | this.getSignature())); 341 | }; 342 | 343 | 344 | /** @param {!(string|Uint8Array)} value */ 345 | proto.pb.SigChainElem.prototype.setSignature = function(value) { 346 | jspb.Message.setProto3BytesField(this, 4, value); 347 | }; 348 | 349 | 350 | /** 351 | * optional SigAlgo sig_algo = 5; 352 | * @return {!proto.pb.SigAlgo} 353 | */ 354 | proto.pb.SigChainElem.prototype.getSigAlgo = function() { 355 | return /** @type {!proto.pb.SigAlgo} */ (jspb.Message.getFieldWithDefault(this, 5, 0)); 356 | }; 357 | 358 | 359 | /** @param {!proto.pb.SigAlgo} value */ 360 | proto.pb.SigChainElem.prototype.setSigAlgo = function(value) { 361 | jspb.Message.setProto3EnumField(this, 5, value); 362 | }; 363 | 364 | 365 | /** 366 | * optional bytes vrf = 6; 367 | * @return {!(string|Uint8Array)} 368 | */ 369 | proto.pb.SigChainElem.prototype.getVrf = function() { 370 | return /** @type {!(string|Uint8Array)} */ (jspb.Message.getFieldWithDefault(this, 6, "")); 371 | }; 372 | 373 | 374 | /** 375 | * optional bytes vrf = 6; 376 | * This is a type-conversion wrapper around `getVrf()` 377 | * @return {string} 378 | */ 379 | proto.pb.SigChainElem.prototype.getVrf_asB64 = function() { 380 | return /** @type {string} */ (jspb.Message.bytesAsB64( 381 | this.getVrf())); 382 | }; 383 | 384 | 385 | /** 386 | * optional bytes vrf = 6; 387 | * Note that Uint8Array is not supported on all browsers. 388 | * @see http://caniuse.com/Uint8Array 389 | * This is a type-conversion wrapper around `getVrf()` 390 | * @return {!Uint8Array} 391 | */ 392 | proto.pb.SigChainElem.prototype.getVrf_asU8 = function() { 393 | return /** @type {!Uint8Array} */ (jspb.Message.bytesAsU8( 394 | this.getVrf())); 395 | }; 396 | 397 | 398 | /** @param {!(string|Uint8Array)} value */ 399 | proto.pb.SigChainElem.prototype.setVrf = function(value) { 400 | jspb.Message.setProto3BytesField(this, 6, value); 401 | }; 402 | 403 | 404 | /** 405 | * optional bytes proof = 7; 406 | * @return {!(string|Uint8Array)} 407 | */ 408 | proto.pb.SigChainElem.prototype.getProof = function() { 409 | return /** @type {!(string|Uint8Array)} */ (jspb.Message.getFieldWithDefault(this, 7, "")); 410 | }; 411 | 412 | 413 | /** 414 | * optional bytes proof = 7; 415 | * This is a type-conversion wrapper around `getProof()` 416 | * @return {string} 417 | */ 418 | proto.pb.SigChainElem.prototype.getProof_asB64 = function() { 419 | return /** @type {string} */ (jspb.Message.bytesAsB64( 420 | this.getProof())); 421 | }; 422 | 423 | 424 | /** 425 | * optional bytes proof = 7; 426 | * Note that Uint8Array is not supported on all browsers. 427 | * @see http://caniuse.com/Uint8Array 428 | * This is a type-conversion wrapper around `getProof()` 429 | * @return {!Uint8Array} 430 | */ 431 | proto.pb.SigChainElem.prototype.getProof_asU8 = function() { 432 | return /** @type {!Uint8Array} */ (jspb.Message.bytesAsU8( 433 | this.getProof())); 434 | }; 435 | 436 | 437 | /** @param {!(string|Uint8Array)} value */ 438 | proto.pb.SigChainElem.prototype.setProof = function(value) { 439 | jspb.Message.setProto3BytesField(this, 7, value); 440 | }; 441 | 442 | 443 | 444 | /** 445 | * Generated by JsPbCodeGenerator. 446 | * @param {Array=} opt_data Optional initial data array, typically from a 447 | * server response, or constructed directly in Javascript. The array is used 448 | * in place and becomes part of the constructed object. It is not cloned. 449 | * If no data is provided, the constructed object will be empty, but still 450 | * valid. 451 | * @extends {jspb.Message} 452 | * @constructor 453 | */ 454 | proto.pb.SigChain = function(opt_data) { 455 | jspb.Message.initialize(this, opt_data, 0, -1, proto.pb.SigChain.repeatedFields_, null); 456 | }; 457 | goog.inherits(proto.pb.SigChain, jspb.Message); 458 | if (goog.DEBUG && !COMPILED) { 459 | proto.pb.SigChain.displayName = 'proto.pb.SigChain'; 460 | } 461 | /** 462 | * List of repeated fields within this message type. 463 | * @private {!Array} 464 | * @const 465 | */ 466 | proto.pb.SigChain.repeatedFields_ = [8]; 467 | 468 | 469 | 470 | if (jspb.Message.GENERATE_TO_OBJECT) { 471 | /** 472 | * Creates an object representation of this proto suitable for use in Soy templates. 473 | * Field names that are reserved in JavaScript and will be renamed to pb_name. 474 | * To access a reserved field use, foo.pb_, eg, foo.pb_default. 475 | * For the list of reserved names please see: 476 | * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. 477 | * @param {boolean=} opt_includeInstance Whether to include the JSPB instance 478 | * for transitional soy proto support: http://goto/soy-param-migration 479 | * @return {!Object} 480 | */ 481 | proto.pb.SigChain.prototype.toObject = function(opt_includeInstance) { 482 | return proto.pb.SigChain.toObject(opt_includeInstance, this); 483 | }; 484 | 485 | 486 | /** 487 | * Static version of the {@see toObject} method. 488 | * @param {boolean|undefined} includeInstance Whether to include the JSPB 489 | * instance for transitional soy proto support: 490 | * http://goto/soy-param-migration 491 | * @param {!proto.pb.SigChain} msg The msg instance to transform. 492 | * @return {!Object} 493 | * @suppress {unusedLocalVariables} f is only used for nested messages 494 | */ 495 | proto.pb.SigChain.toObject = function(includeInstance, msg) { 496 | var f, obj = { 497 | nonce: jspb.Message.getFieldWithDefault(msg, 1, 0), 498 | dataSize: jspb.Message.getFieldWithDefault(msg, 2, 0), 499 | blockHash: msg.getBlockHash_asB64(), 500 | srcId: msg.getSrcId_asB64(), 501 | srcPubkey: msg.getSrcPubkey_asB64(), 502 | destId: msg.getDestId_asB64(), 503 | destPubkey: msg.getDestPubkey_asB64(), 504 | elemsList: jspb.Message.toObjectList(msg.getElemsList(), 505 | proto.pb.SigChainElem.toObject, includeInstance) 506 | }; 507 | 508 | if (includeInstance) { 509 | obj.$jspbMessageInstance = msg; 510 | } 511 | return obj; 512 | }; 513 | } 514 | 515 | 516 | /** 517 | * Deserializes binary data (in protobuf wire format). 518 | * @param {jspb.ByteSource} bytes The bytes to deserialize. 519 | * @return {!proto.pb.SigChain} 520 | */ 521 | proto.pb.SigChain.deserializeBinary = function(bytes) { 522 | var reader = new jspb.BinaryReader(bytes); 523 | var msg = new proto.pb.SigChain; 524 | return proto.pb.SigChain.deserializeBinaryFromReader(msg, reader); 525 | }; 526 | 527 | 528 | /** 529 | * Deserializes binary data (in protobuf wire format) from the 530 | * given reader into the given message object. 531 | * @param {!proto.pb.SigChain} msg The message object to deserialize into. 532 | * @param {!jspb.BinaryReader} reader The BinaryReader to use. 533 | * @return {!proto.pb.SigChain} 534 | */ 535 | proto.pb.SigChain.deserializeBinaryFromReader = function(msg, reader) { 536 | while (reader.nextField()) { 537 | if (reader.isEndGroup()) { 538 | break; 539 | } 540 | var field = reader.getFieldNumber(); 541 | switch (field) { 542 | case 1: 543 | var value = /** @type {number} */ (reader.readUint32()); 544 | msg.setNonce(value); 545 | break; 546 | case 2: 547 | var value = /** @type {number} */ (reader.readUint32()); 548 | msg.setDataSize(value); 549 | break; 550 | case 3: 551 | var value = /** @type {!Uint8Array} */ (reader.readBytes()); 552 | msg.setBlockHash(value); 553 | break; 554 | case 4: 555 | var value = /** @type {!Uint8Array} */ (reader.readBytes()); 556 | msg.setSrcId(value); 557 | break; 558 | case 5: 559 | var value = /** @type {!Uint8Array} */ (reader.readBytes()); 560 | msg.setSrcPubkey(value); 561 | break; 562 | case 6: 563 | var value = /** @type {!Uint8Array} */ (reader.readBytes()); 564 | msg.setDestId(value); 565 | break; 566 | case 7: 567 | var value = /** @type {!Uint8Array} */ (reader.readBytes()); 568 | msg.setDestPubkey(value); 569 | break; 570 | case 8: 571 | var value = new proto.pb.SigChainElem; 572 | reader.readMessage(value,proto.pb.SigChainElem.deserializeBinaryFromReader); 573 | msg.addElems(value); 574 | break; 575 | default: 576 | reader.skipField(); 577 | break; 578 | } 579 | } 580 | return msg; 581 | }; 582 | 583 | 584 | /** 585 | * Serializes the message to binary data (in protobuf wire format). 586 | * @return {!Uint8Array} 587 | */ 588 | proto.pb.SigChain.prototype.serializeBinary = function() { 589 | var writer = new jspb.BinaryWriter(); 590 | proto.pb.SigChain.serializeBinaryToWriter(this, writer); 591 | return writer.getResultBuffer(); 592 | }; 593 | 594 | 595 | /** 596 | * Serializes the given message to binary data (in protobuf wire 597 | * format), writing to the given BinaryWriter. 598 | * @param {!proto.pb.SigChain} message 599 | * @param {!jspb.BinaryWriter} writer 600 | * @suppress {unusedLocalVariables} f is only used for nested messages 601 | */ 602 | proto.pb.SigChain.serializeBinaryToWriter = function(message, writer) { 603 | var f = undefined; 604 | f = message.getNonce(); 605 | if (f !== 0) { 606 | writer.writeUint32( 607 | 1, 608 | f 609 | ); 610 | } 611 | f = message.getDataSize(); 612 | if (f !== 0) { 613 | writer.writeUint32( 614 | 2, 615 | f 616 | ); 617 | } 618 | f = message.getBlockHash_asU8(); 619 | if (f.length > 0) { 620 | writer.writeBytes( 621 | 3, 622 | f 623 | ); 624 | } 625 | f = message.getSrcId_asU8(); 626 | if (f.length > 0) { 627 | writer.writeBytes( 628 | 4, 629 | f 630 | ); 631 | } 632 | f = message.getSrcPubkey_asU8(); 633 | if (f.length > 0) { 634 | writer.writeBytes( 635 | 5, 636 | f 637 | ); 638 | } 639 | f = message.getDestId_asU8(); 640 | if (f.length > 0) { 641 | writer.writeBytes( 642 | 6, 643 | f 644 | ); 645 | } 646 | f = message.getDestPubkey_asU8(); 647 | if (f.length > 0) { 648 | writer.writeBytes( 649 | 7, 650 | f 651 | ); 652 | } 653 | f = message.getElemsList(); 654 | if (f.length > 0) { 655 | writer.writeRepeatedMessage( 656 | 8, 657 | f, 658 | proto.pb.SigChainElem.serializeBinaryToWriter 659 | ); 660 | } 661 | }; 662 | 663 | 664 | /** 665 | * optional uint32 nonce = 1; 666 | * @return {number} 667 | */ 668 | proto.pb.SigChain.prototype.getNonce = function() { 669 | return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); 670 | }; 671 | 672 | 673 | /** @param {number} value */ 674 | proto.pb.SigChain.prototype.setNonce = function(value) { 675 | jspb.Message.setProto3IntField(this, 1, value); 676 | }; 677 | 678 | 679 | /** 680 | * optional uint32 data_size = 2; 681 | * @return {number} 682 | */ 683 | proto.pb.SigChain.prototype.getDataSize = function() { 684 | return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 2, 0)); 685 | }; 686 | 687 | 688 | /** @param {number} value */ 689 | proto.pb.SigChain.prototype.setDataSize = function(value) { 690 | jspb.Message.setProto3IntField(this, 2, value); 691 | }; 692 | 693 | 694 | /** 695 | * optional bytes block_hash = 3; 696 | * @return {!(string|Uint8Array)} 697 | */ 698 | proto.pb.SigChain.prototype.getBlockHash = function() { 699 | return /** @type {!(string|Uint8Array)} */ (jspb.Message.getFieldWithDefault(this, 3, "")); 700 | }; 701 | 702 | 703 | /** 704 | * optional bytes block_hash = 3; 705 | * This is a type-conversion wrapper around `getBlockHash()` 706 | * @return {string} 707 | */ 708 | proto.pb.SigChain.prototype.getBlockHash_asB64 = function() { 709 | return /** @type {string} */ (jspb.Message.bytesAsB64( 710 | this.getBlockHash())); 711 | }; 712 | 713 | 714 | /** 715 | * optional bytes block_hash = 3; 716 | * Note that Uint8Array is not supported on all browsers. 717 | * @see http://caniuse.com/Uint8Array 718 | * This is a type-conversion wrapper around `getBlockHash()` 719 | * @return {!Uint8Array} 720 | */ 721 | proto.pb.SigChain.prototype.getBlockHash_asU8 = function() { 722 | return /** @type {!Uint8Array} */ (jspb.Message.bytesAsU8( 723 | this.getBlockHash())); 724 | }; 725 | 726 | 727 | /** @param {!(string|Uint8Array)} value */ 728 | proto.pb.SigChain.prototype.setBlockHash = function(value) { 729 | jspb.Message.setProto3BytesField(this, 3, value); 730 | }; 731 | 732 | 733 | /** 734 | * optional bytes src_id = 4; 735 | * @return {!(string|Uint8Array)} 736 | */ 737 | proto.pb.SigChain.prototype.getSrcId = function() { 738 | return /** @type {!(string|Uint8Array)} */ (jspb.Message.getFieldWithDefault(this, 4, "")); 739 | }; 740 | 741 | 742 | /** 743 | * optional bytes src_id = 4; 744 | * This is a type-conversion wrapper around `getSrcId()` 745 | * @return {string} 746 | */ 747 | proto.pb.SigChain.prototype.getSrcId_asB64 = function() { 748 | return /** @type {string} */ (jspb.Message.bytesAsB64( 749 | this.getSrcId())); 750 | }; 751 | 752 | 753 | /** 754 | * optional bytes src_id = 4; 755 | * Note that Uint8Array is not supported on all browsers. 756 | * @see http://caniuse.com/Uint8Array 757 | * This is a type-conversion wrapper around `getSrcId()` 758 | * @return {!Uint8Array} 759 | */ 760 | proto.pb.SigChain.prototype.getSrcId_asU8 = function() { 761 | return /** @type {!Uint8Array} */ (jspb.Message.bytesAsU8( 762 | this.getSrcId())); 763 | }; 764 | 765 | 766 | /** @param {!(string|Uint8Array)} value */ 767 | proto.pb.SigChain.prototype.setSrcId = function(value) { 768 | jspb.Message.setProto3BytesField(this, 4, value); 769 | }; 770 | 771 | 772 | /** 773 | * optional bytes src_pubkey = 5; 774 | * @return {!(string|Uint8Array)} 775 | */ 776 | proto.pb.SigChain.prototype.getSrcPubkey = function() { 777 | return /** @type {!(string|Uint8Array)} */ (jspb.Message.getFieldWithDefault(this, 5, "")); 778 | }; 779 | 780 | 781 | /** 782 | * optional bytes src_pubkey = 5; 783 | * This is a type-conversion wrapper around `getSrcPubkey()` 784 | * @return {string} 785 | */ 786 | proto.pb.SigChain.prototype.getSrcPubkey_asB64 = function() { 787 | return /** @type {string} */ (jspb.Message.bytesAsB64( 788 | this.getSrcPubkey())); 789 | }; 790 | 791 | 792 | /** 793 | * optional bytes src_pubkey = 5; 794 | * Note that Uint8Array is not supported on all browsers. 795 | * @see http://caniuse.com/Uint8Array 796 | * This is a type-conversion wrapper around `getSrcPubkey()` 797 | * @return {!Uint8Array} 798 | */ 799 | proto.pb.SigChain.prototype.getSrcPubkey_asU8 = function() { 800 | return /** @type {!Uint8Array} */ (jspb.Message.bytesAsU8( 801 | this.getSrcPubkey())); 802 | }; 803 | 804 | 805 | /** @param {!(string|Uint8Array)} value */ 806 | proto.pb.SigChain.prototype.setSrcPubkey = function(value) { 807 | jspb.Message.setProto3BytesField(this, 5, value); 808 | }; 809 | 810 | 811 | /** 812 | * optional bytes dest_id = 6; 813 | * @return {!(string|Uint8Array)} 814 | */ 815 | proto.pb.SigChain.prototype.getDestId = function() { 816 | return /** @type {!(string|Uint8Array)} */ (jspb.Message.getFieldWithDefault(this, 6, "")); 817 | }; 818 | 819 | 820 | /** 821 | * optional bytes dest_id = 6; 822 | * This is a type-conversion wrapper around `getDestId()` 823 | * @return {string} 824 | */ 825 | proto.pb.SigChain.prototype.getDestId_asB64 = function() { 826 | return /** @type {string} */ (jspb.Message.bytesAsB64( 827 | this.getDestId())); 828 | }; 829 | 830 | 831 | /** 832 | * optional bytes dest_id = 6; 833 | * Note that Uint8Array is not supported on all browsers. 834 | * @see http://caniuse.com/Uint8Array 835 | * This is a type-conversion wrapper around `getDestId()` 836 | * @return {!Uint8Array} 837 | */ 838 | proto.pb.SigChain.prototype.getDestId_asU8 = function() { 839 | return /** @type {!Uint8Array} */ (jspb.Message.bytesAsU8( 840 | this.getDestId())); 841 | }; 842 | 843 | 844 | /** @param {!(string|Uint8Array)} value */ 845 | proto.pb.SigChain.prototype.setDestId = function(value) { 846 | jspb.Message.setProto3BytesField(this, 6, value); 847 | }; 848 | 849 | 850 | /** 851 | * optional bytes dest_pubkey = 7; 852 | * @return {!(string|Uint8Array)} 853 | */ 854 | proto.pb.SigChain.prototype.getDestPubkey = function() { 855 | return /** @type {!(string|Uint8Array)} */ (jspb.Message.getFieldWithDefault(this, 7, "")); 856 | }; 857 | 858 | 859 | /** 860 | * optional bytes dest_pubkey = 7; 861 | * This is a type-conversion wrapper around `getDestPubkey()` 862 | * @return {string} 863 | */ 864 | proto.pb.SigChain.prototype.getDestPubkey_asB64 = function() { 865 | return /** @type {string} */ (jspb.Message.bytesAsB64( 866 | this.getDestPubkey())); 867 | }; 868 | 869 | 870 | /** 871 | * optional bytes dest_pubkey = 7; 872 | * Note that Uint8Array is not supported on all browsers. 873 | * @see http://caniuse.com/Uint8Array 874 | * This is a type-conversion wrapper around `getDestPubkey()` 875 | * @return {!Uint8Array} 876 | */ 877 | proto.pb.SigChain.prototype.getDestPubkey_asU8 = function() { 878 | return /** @type {!Uint8Array} */ (jspb.Message.bytesAsU8( 879 | this.getDestPubkey())); 880 | }; 881 | 882 | 883 | /** @param {!(string|Uint8Array)} value */ 884 | proto.pb.SigChain.prototype.setDestPubkey = function(value) { 885 | jspb.Message.setProto3BytesField(this, 7, value); 886 | }; 887 | 888 | 889 | /** 890 | * repeated SigChainElem elems = 8; 891 | * @return {!Array} 892 | */ 893 | proto.pb.SigChain.prototype.getElemsList = function() { 894 | return /** @type{!Array} */ ( 895 | jspb.Message.getRepeatedWrapperField(this, proto.pb.SigChainElem, 8)); 896 | }; 897 | 898 | 899 | /** @param {!Array} value */ 900 | proto.pb.SigChain.prototype.setElemsList = function(value) { 901 | jspb.Message.setRepeatedWrapperField(this, 8, value); 902 | }; 903 | 904 | 905 | /** 906 | * @param {!proto.pb.SigChainElem=} opt_value 907 | * @param {number=} opt_index 908 | * @return {!proto.pb.SigChainElem} 909 | */ 910 | proto.pb.SigChain.prototype.addElems = function(opt_value, opt_index) { 911 | return jspb.Message.addToRepeatedWrapperField(this, 8, opt_value, proto.pb.SigChainElem, opt_index); 912 | }; 913 | 914 | 915 | proto.pb.SigChain.prototype.clearElemsList = function() { 916 | this.setElemsList([]); 917 | }; 918 | 919 | 920 | /** 921 | * @enum {number} 922 | */ 923 | proto.pb.SigAlgo = { 924 | SIGNATURE: 0, 925 | VRF: 1 926 | }; 927 | 928 | goog.object.extend(exports, proto.pb); 929 | -------------------------------------------------------------------------------- /lib/protocol/pb/messages_pb.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileoverview 3 | * @enhanceable 4 | * @suppress {messageConventions} JS Compiler reports an error if a variable or 5 | * field starts with 'MSG_' and isn't a translatable message. 6 | * @public 7 | */ 8 | // GENERATED CODE -- DO NOT EDIT! 9 | 10 | var jspb = require('google-protobuf'); 11 | var goog = jspb; 12 | var global = Function('return this')(); 13 | 14 | goog.exportSymbol('proto.pb.ClientMessage', null, global); 15 | goog.exportSymbol('proto.pb.ClientMessageType', null, global); 16 | goog.exportSymbol('proto.pb.CompressionType', null, global); 17 | goog.exportSymbol('proto.pb.InboundMessage', null, global); 18 | goog.exportSymbol('proto.pb.OutboundMessage', null, global); 19 | goog.exportSymbol('proto.pb.Receipt', null, global); 20 | /** 21 | * Generated by JsPbCodeGenerator. 22 | * @param {Array=} opt_data Optional initial data array, typically from a 23 | * server response, or constructed directly in Javascript. The array is used 24 | * in place and becomes part of the constructed object. It is not cloned. 25 | * If no data is provided, the constructed object will be empty, but still 26 | * valid. 27 | * @extends {jspb.Message} 28 | * @constructor 29 | */ 30 | proto.pb.ClientMessage = function(opt_data) { 31 | jspb.Message.initialize(this, opt_data, 0, -1, null, null); 32 | }; 33 | goog.inherits(proto.pb.ClientMessage, jspb.Message); 34 | if (goog.DEBUG && !COMPILED) { 35 | /** 36 | * @public 37 | * @override 38 | */ 39 | proto.pb.ClientMessage.displayName = 'proto.pb.ClientMessage'; 40 | } 41 | /** 42 | * Generated by JsPbCodeGenerator. 43 | * @param {Array=} opt_data Optional initial data array, typically from a 44 | * server response, or constructed directly in Javascript. The array is used 45 | * in place and becomes part of the constructed object. It is not cloned. 46 | * If no data is provided, the constructed object will be empty, but still 47 | * valid. 48 | * @extends {jspb.Message} 49 | * @constructor 50 | */ 51 | proto.pb.OutboundMessage = function(opt_data) { 52 | jspb.Message.initialize(this, opt_data, 0, -1, proto.pb.OutboundMessage.repeatedFields_, null); 53 | }; 54 | goog.inherits(proto.pb.OutboundMessage, jspb.Message); 55 | if (goog.DEBUG && !COMPILED) { 56 | /** 57 | * @public 58 | * @override 59 | */ 60 | proto.pb.OutboundMessage.displayName = 'proto.pb.OutboundMessage'; 61 | } 62 | /** 63 | * Generated by JsPbCodeGenerator. 64 | * @param {Array=} opt_data Optional initial data array, typically from a 65 | * server response, or constructed directly in Javascript. The array is used 66 | * in place and becomes part of the constructed object. It is not cloned. 67 | * If no data is provided, the constructed object will be empty, but still 68 | * valid. 69 | * @extends {jspb.Message} 70 | * @constructor 71 | */ 72 | proto.pb.InboundMessage = function(opt_data) { 73 | jspb.Message.initialize(this, opt_data, 0, -1, null, null); 74 | }; 75 | goog.inherits(proto.pb.InboundMessage, jspb.Message); 76 | if (goog.DEBUG && !COMPILED) { 77 | /** 78 | * @public 79 | * @override 80 | */ 81 | proto.pb.InboundMessage.displayName = 'proto.pb.InboundMessage'; 82 | } 83 | /** 84 | * Generated by JsPbCodeGenerator. 85 | * @param {Array=} opt_data Optional initial data array, typically from a 86 | * server response, or constructed directly in Javascript. The array is used 87 | * in place and becomes part of the constructed object. It is not cloned. 88 | * If no data is provided, the constructed object will be empty, but still 89 | * valid. 90 | * @extends {jspb.Message} 91 | * @constructor 92 | */ 93 | proto.pb.Receipt = function(opt_data) { 94 | jspb.Message.initialize(this, opt_data, 0, -1, null, null); 95 | }; 96 | goog.inherits(proto.pb.Receipt, jspb.Message); 97 | if (goog.DEBUG && !COMPILED) { 98 | /** 99 | * @public 100 | * @override 101 | */ 102 | proto.pb.Receipt.displayName = 'proto.pb.Receipt'; 103 | } 104 | 105 | 106 | 107 | if (jspb.Message.GENERATE_TO_OBJECT) { 108 | /** 109 | * Creates an object representation of this proto suitable for use in Soy templates. 110 | * Field names that are reserved in JavaScript and will be renamed to pb_name. 111 | * To access a reserved field use, foo.pb_, eg, foo.pb_default. 112 | * For the list of reserved names please see: 113 | * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. 114 | * @param {boolean=} opt_includeInstance Whether to include the JSPB instance 115 | * for transitional soy proto support: http://goto/soy-param-migration 116 | * @return {!Object} 117 | */ 118 | proto.pb.ClientMessage.prototype.toObject = function(opt_includeInstance) { 119 | return proto.pb.ClientMessage.toObject(opt_includeInstance, this); 120 | }; 121 | 122 | 123 | /** 124 | * Static version of the {@see toObject} method. 125 | * @param {boolean|undefined} includeInstance Whether to include the JSPB 126 | * instance for transitional soy proto support: 127 | * http://goto/soy-param-migration 128 | * @param {!proto.pb.ClientMessage} msg The msg instance to transform. 129 | * @return {!Object} 130 | * @suppress {unusedLocalVariables} f is only used for nested messages 131 | */ 132 | proto.pb.ClientMessage.toObject = function(includeInstance, msg) { 133 | var f, obj = { 134 | messageType: jspb.Message.getFieldWithDefault(msg, 1, 0), 135 | message: msg.getMessage_asB64(), 136 | compressionType: jspb.Message.getFieldWithDefault(msg, 3, 0) 137 | }; 138 | 139 | if (includeInstance) { 140 | obj.$jspbMessageInstance = msg; 141 | } 142 | return obj; 143 | }; 144 | } 145 | 146 | 147 | /** 148 | * Deserializes binary data (in protobuf wire format). 149 | * @param {jspb.ByteSource} bytes The bytes to deserialize. 150 | * @return {!proto.pb.ClientMessage} 151 | */ 152 | proto.pb.ClientMessage.deserializeBinary = function(bytes) { 153 | var reader = new jspb.BinaryReader(bytes); 154 | var msg = new proto.pb.ClientMessage; 155 | return proto.pb.ClientMessage.deserializeBinaryFromReader(msg, reader); 156 | }; 157 | 158 | 159 | /** 160 | * Deserializes binary data (in protobuf wire format) from the 161 | * given reader into the given message object. 162 | * @param {!proto.pb.ClientMessage} msg The message object to deserialize into. 163 | * @param {!jspb.BinaryReader} reader The BinaryReader to use. 164 | * @return {!proto.pb.ClientMessage} 165 | */ 166 | proto.pb.ClientMessage.deserializeBinaryFromReader = function(msg, reader) { 167 | while (reader.nextField()) { 168 | if (reader.isEndGroup()) { 169 | break; 170 | } 171 | var field = reader.getFieldNumber(); 172 | switch (field) { 173 | case 1: 174 | var value = /** @type {!proto.pb.ClientMessageType} */ (reader.readEnum()); 175 | msg.setMessageType(value); 176 | break; 177 | case 2: 178 | var value = /** @type {!Uint8Array} */ (reader.readBytes()); 179 | msg.setMessage(value); 180 | break; 181 | case 3: 182 | var value = /** @type {!proto.pb.CompressionType} */ (reader.readEnum()); 183 | msg.setCompressionType(value); 184 | break; 185 | default: 186 | reader.skipField(); 187 | break; 188 | } 189 | } 190 | return msg; 191 | }; 192 | 193 | 194 | /** 195 | * Serializes the message to binary data (in protobuf wire format). 196 | * @return {!Uint8Array} 197 | */ 198 | proto.pb.ClientMessage.prototype.serializeBinary = function() { 199 | var writer = new jspb.BinaryWriter(); 200 | proto.pb.ClientMessage.serializeBinaryToWriter(this, writer); 201 | return writer.getResultBuffer(); 202 | }; 203 | 204 | 205 | /** 206 | * Serializes the given message to binary data (in protobuf wire 207 | * format), writing to the given BinaryWriter. 208 | * @param {!proto.pb.ClientMessage} message 209 | * @param {!jspb.BinaryWriter} writer 210 | * @suppress {unusedLocalVariables} f is only used for nested messages 211 | */ 212 | proto.pb.ClientMessage.serializeBinaryToWriter = function(message, writer) { 213 | var f = undefined; 214 | f = message.getMessageType(); 215 | if (f !== 0.0) { 216 | writer.writeEnum( 217 | 1, 218 | f 219 | ); 220 | } 221 | f = message.getMessage_asU8(); 222 | if (f.length > 0) { 223 | writer.writeBytes( 224 | 2, 225 | f 226 | ); 227 | } 228 | f = message.getCompressionType(); 229 | if (f !== 0.0) { 230 | writer.writeEnum( 231 | 3, 232 | f 233 | ); 234 | } 235 | }; 236 | 237 | 238 | /** 239 | * optional ClientMessageType message_type = 1; 240 | * @return {!proto.pb.ClientMessageType} 241 | */ 242 | proto.pb.ClientMessage.prototype.getMessageType = function() { 243 | return /** @type {!proto.pb.ClientMessageType} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); 244 | }; 245 | 246 | 247 | /** @param {!proto.pb.ClientMessageType} value */ 248 | proto.pb.ClientMessage.prototype.setMessageType = function(value) { 249 | jspb.Message.setProto3EnumField(this, 1, value); 250 | }; 251 | 252 | 253 | /** 254 | * optional bytes message = 2; 255 | * @return {!(string|Uint8Array)} 256 | */ 257 | proto.pb.ClientMessage.prototype.getMessage = function() { 258 | return /** @type {!(string|Uint8Array)} */ (jspb.Message.getFieldWithDefault(this, 2, "")); 259 | }; 260 | 261 | 262 | /** 263 | * optional bytes message = 2; 264 | * This is a type-conversion wrapper around `getMessage()` 265 | * @return {string} 266 | */ 267 | proto.pb.ClientMessage.prototype.getMessage_asB64 = function() { 268 | return /** @type {string} */ (jspb.Message.bytesAsB64( 269 | this.getMessage())); 270 | }; 271 | 272 | 273 | /** 274 | * optional bytes message = 2; 275 | * Note that Uint8Array is not supported on all browsers. 276 | * @see http://caniuse.com/Uint8Array 277 | * This is a type-conversion wrapper around `getMessage()` 278 | * @return {!Uint8Array} 279 | */ 280 | proto.pb.ClientMessage.prototype.getMessage_asU8 = function() { 281 | return /** @type {!Uint8Array} */ (jspb.Message.bytesAsU8( 282 | this.getMessage())); 283 | }; 284 | 285 | 286 | /** @param {!(string|Uint8Array)} value */ 287 | proto.pb.ClientMessage.prototype.setMessage = function(value) { 288 | jspb.Message.setProto3BytesField(this, 2, value); 289 | }; 290 | 291 | 292 | /** 293 | * optional CompressionType compression_type = 3; 294 | * @return {!proto.pb.CompressionType} 295 | */ 296 | proto.pb.ClientMessage.prototype.getCompressionType = function() { 297 | return /** @type {!proto.pb.CompressionType} */ (jspb.Message.getFieldWithDefault(this, 3, 0)); 298 | }; 299 | 300 | 301 | /** @param {!proto.pb.CompressionType} value */ 302 | proto.pb.ClientMessage.prototype.setCompressionType = function(value) { 303 | jspb.Message.setProto3EnumField(this, 3, value); 304 | }; 305 | 306 | 307 | 308 | /** 309 | * List of repeated fields within this message type. 310 | * @private {!Array} 311 | * @const 312 | */ 313 | proto.pb.OutboundMessage.repeatedFields_ = [3,7,8]; 314 | 315 | 316 | 317 | if (jspb.Message.GENERATE_TO_OBJECT) { 318 | /** 319 | * Creates an object representation of this proto suitable for use in Soy templates. 320 | * Field names that are reserved in JavaScript and will be renamed to pb_name. 321 | * To access a reserved field use, foo.pb_, eg, foo.pb_default. 322 | * For the list of reserved names please see: 323 | * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. 324 | * @param {boolean=} opt_includeInstance Whether to include the JSPB instance 325 | * for transitional soy proto support: http://goto/soy-param-migration 326 | * @return {!Object} 327 | */ 328 | proto.pb.OutboundMessage.prototype.toObject = function(opt_includeInstance) { 329 | return proto.pb.OutboundMessage.toObject(opt_includeInstance, this); 330 | }; 331 | 332 | 333 | /** 334 | * Static version of the {@see toObject} method. 335 | * @param {boolean|undefined} includeInstance Whether to include the JSPB 336 | * instance for transitional soy proto support: 337 | * http://goto/soy-param-migration 338 | * @param {!proto.pb.OutboundMessage} msg The msg instance to transform. 339 | * @return {!Object} 340 | * @suppress {unusedLocalVariables} f is only used for nested messages 341 | */ 342 | proto.pb.OutboundMessage.toObject = function(includeInstance, msg) { 343 | var f, obj = { 344 | dest: jspb.Message.getFieldWithDefault(msg, 1, ""), 345 | payload: msg.getPayload_asB64(), 346 | destsList: jspb.Message.getRepeatedField(msg, 3), 347 | maxHoldingSeconds: jspb.Message.getFieldWithDefault(msg, 4, 0), 348 | nonce: jspb.Message.getFieldWithDefault(msg, 5, 0), 349 | blockHash: msg.getBlockHash_asB64(), 350 | signaturesList: msg.getSignaturesList_asB64(), 351 | payloadsList: msg.getPayloadsList_asB64() 352 | }; 353 | 354 | if (includeInstance) { 355 | obj.$jspbMessageInstance = msg; 356 | } 357 | return obj; 358 | }; 359 | } 360 | 361 | 362 | /** 363 | * Deserializes binary data (in protobuf wire format). 364 | * @param {jspb.ByteSource} bytes The bytes to deserialize. 365 | * @return {!proto.pb.OutboundMessage} 366 | */ 367 | proto.pb.OutboundMessage.deserializeBinary = function(bytes) { 368 | var reader = new jspb.BinaryReader(bytes); 369 | var msg = new proto.pb.OutboundMessage; 370 | return proto.pb.OutboundMessage.deserializeBinaryFromReader(msg, reader); 371 | }; 372 | 373 | 374 | /** 375 | * Deserializes binary data (in protobuf wire format) from the 376 | * given reader into the given message object. 377 | * @param {!proto.pb.OutboundMessage} msg The message object to deserialize into. 378 | * @param {!jspb.BinaryReader} reader The BinaryReader to use. 379 | * @return {!proto.pb.OutboundMessage} 380 | */ 381 | proto.pb.OutboundMessage.deserializeBinaryFromReader = function(msg, reader) { 382 | while (reader.nextField()) { 383 | if (reader.isEndGroup()) { 384 | break; 385 | } 386 | var field = reader.getFieldNumber(); 387 | switch (field) { 388 | case 1: 389 | var value = /** @type {string} */ (reader.readString()); 390 | msg.setDest(value); 391 | break; 392 | case 2: 393 | var value = /** @type {!Uint8Array} */ (reader.readBytes()); 394 | msg.setPayload(value); 395 | break; 396 | case 3: 397 | var value = /** @type {string} */ (reader.readString()); 398 | msg.addDests(value); 399 | break; 400 | case 4: 401 | var value = /** @type {number} */ (reader.readUint32()); 402 | msg.setMaxHoldingSeconds(value); 403 | break; 404 | case 5: 405 | var value = /** @type {number} */ (reader.readUint32()); 406 | msg.setNonce(value); 407 | break; 408 | case 6: 409 | var value = /** @type {!Uint8Array} */ (reader.readBytes()); 410 | msg.setBlockHash(value); 411 | break; 412 | case 7: 413 | var value = /** @type {!Uint8Array} */ (reader.readBytes()); 414 | msg.addSignatures(value); 415 | break; 416 | case 8: 417 | var value = /** @type {!Uint8Array} */ (reader.readBytes()); 418 | msg.addPayloads(value); 419 | break; 420 | default: 421 | reader.skipField(); 422 | break; 423 | } 424 | } 425 | return msg; 426 | }; 427 | 428 | 429 | /** 430 | * Serializes the message to binary data (in protobuf wire format). 431 | * @return {!Uint8Array} 432 | */ 433 | proto.pb.OutboundMessage.prototype.serializeBinary = function() { 434 | var writer = new jspb.BinaryWriter(); 435 | proto.pb.OutboundMessage.serializeBinaryToWriter(this, writer); 436 | return writer.getResultBuffer(); 437 | }; 438 | 439 | 440 | /** 441 | * Serializes the given message to binary data (in protobuf wire 442 | * format), writing to the given BinaryWriter. 443 | * @param {!proto.pb.OutboundMessage} message 444 | * @param {!jspb.BinaryWriter} writer 445 | * @suppress {unusedLocalVariables} f is only used for nested messages 446 | */ 447 | proto.pb.OutboundMessage.serializeBinaryToWriter = function(message, writer) { 448 | var f = undefined; 449 | f = message.getDest(); 450 | if (f.length > 0) { 451 | writer.writeString( 452 | 1, 453 | f 454 | ); 455 | } 456 | f = message.getPayload_asU8(); 457 | if (f.length > 0) { 458 | writer.writeBytes( 459 | 2, 460 | f 461 | ); 462 | } 463 | f = message.getDestsList(); 464 | if (f.length > 0) { 465 | writer.writeRepeatedString( 466 | 3, 467 | f 468 | ); 469 | } 470 | f = message.getMaxHoldingSeconds(); 471 | if (f !== 0) { 472 | writer.writeUint32( 473 | 4, 474 | f 475 | ); 476 | } 477 | f = message.getNonce(); 478 | if (f !== 0) { 479 | writer.writeUint32( 480 | 5, 481 | f 482 | ); 483 | } 484 | f = message.getBlockHash_asU8(); 485 | if (f.length > 0) { 486 | writer.writeBytes( 487 | 6, 488 | f 489 | ); 490 | } 491 | f = message.getSignaturesList_asU8(); 492 | if (f.length > 0) { 493 | writer.writeRepeatedBytes( 494 | 7, 495 | f 496 | ); 497 | } 498 | f = message.getPayloadsList_asU8(); 499 | if (f.length > 0) { 500 | writer.writeRepeatedBytes( 501 | 8, 502 | f 503 | ); 504 | } 505 | }; 506 | 507 | 508 | /** 509 | * optional string dest = 1; 510 | * @return {string} 511 | */ 512 | proto.pb.OutboundMessage.prototype.getDest = function() { 513 | return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); 514 | }; 515 | 516 | 517 | /** @param {string} value */ 518 | proto.pb.OutboundMessage.prototype.setDest = function(value) { 519 | jspb.Message.setProto3StringField(this, 1, value); 520 | }; 521 | 522 | 523 | /** 524 | * optional bytes payload = 2; 525 | * @return {!(string|Uint8Array)} 526 | */ 527 | proto.pb.OutboundMessage.prototype.getPayload = function() { 528 | return /** @type {!(string|Uint8Array)} */ (jspb.Message.getFieldWithDefault(this, 2, "")); 529 | }; 530 | 531 | 532 | /** 533 | * optional bytes payload = 2; 534 | * This is a type-conversion wrapper around `getPayload()` 535 | * @return {string} 536 | */ 537 | proto.pb.OutboundMessage.prototype.getPayload_asB64 = function() { 538 | return /** @type {string} */ (jspb.Message.bytesAsB64( 539 | this.getPayload())); 540 | }; 541 | 542 | 543 | /** 544 | * optional bytes payload = 2; 545 | * Note that Uint8Array is not supported on all browsers. 546 | * @see http://caniuse.com/Uint8Array 547 | * This is a type-conversion wrapper around `getPayload()` 548 | * @return {!Uint8Array} 549 | */ 550 | proto.pb.OutboundMessage.prototype.getPayload_asU8 = function() { 551 | return /** @type {!Uint8Array} */ (jspb.Message.bytesAsU8( 552 | this.getPayload())); 553 | }; 554 | 555 | 556 | /** @param {!(string|Uint8Array)} value */ 557 | proto.pb.OutboundMessage.prototype.setPayload = function(value) { 558 | jspb.Message.setProto3BytesField(this, 2, value); 559 | }; 560 | 561 | 562 | /** 563 | * repeated string dests = 3; 564 | * @return {!Array} 565 | */ 566 | proto.pb.OutboundMessage.prototype.getDestsList = function() { 567 | return /** @type {!Array} */ (jspb.Message.getRepeatedField(this, 3)); 568 | }; 569 | 570 | 571 | /** @param {!Array} value */ 572 | proto.pb.OutboundMessage.prototype.setDestsList = function(value) { 573 | jspb.Message.setField(this, 3, value || []); 574 | }; 575 | 576 | 577 | /** 578 | * @param {string} value 579 | * @param {number=} opt_index 580 | */ 581 | proto.pb.OutboundMessage.prototype.addDests = function(value, opt_index) { 582 | jspb.Message.addToRepeatedField(this, 3, value, opt_index); 583 | }; 584 | 585 | 586 | /** 587 | * Clears the list making it empty but non-null. 588 | */ 589 | proto.pb.OutboundMessage.prototype.clearDestsList = function() { 590 | this.setDestsList([]); 591 | }; 592 | 593 | 594 | /** 595 | * optional uint32 max_holding_seconds = 4; 596 | * @return {number} 597 | */ 598 | proto.pb.OutboundMessage.prototype.getMaxHoldingSeconds = function() { 599 | return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 4, 0)); 600 | }; 601 | 602 | 603 | /** @param {number} value */ 604 | proto.pb.OutboundMessage.prototype.setMaxHoldingSeconds = function(value) { 605 | jspb.Message.setProto3IntField(this, 4, value); 606 | }; 607 | 608 | 609 | /** 610 | * optional uint32 nonce = 5; 611 | * @return {number} 612 | */ 613 | proto.pb.OutboundMessage.prototype.getNonce = function() { 614 | return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 5, 0)); 615 | }; 616 | 617 | 618 | /** @param {number} value */ 619 | proto.pb.OutboundMessage.prototype.setNonce = function(value) { 620 | jspb.Message.setProto3IntField(this, 5, value); 621 | }; 622 | 623 | 624 | /** 625 | * optional bytes block_hash = 6; 626 | * @return {!(string|Uint8Array)} 627 | */ 628 | proto.pb.OutboundMessage.prototype.getBlockHash = function() { 629 | return /** @type {!(string|Uint8Array)} */ (jspb.Message.getFieldWithDefault(this, 6, "")); 630 | }; 631 | 632 | 633 | /** 634 | * optional bytes block_hash = 6; 635 | * This is a type-conversion wrapper around `getBlockHash()` 636 | * @return {string} 637 | */ 638 | proto.pb.OutboundMessage.prototype.getBlockHash_asB64 = function() { 639 | return /** @type {string} */ (jspb.Message.bytesAsB64( 640 | this.getBlockHash())); 641 | }; 642 | 643 | 644 | /** 645 | * optional bytes block_hash = 6; 646 | * Note that Uint8Array is not supported on all browsers. 647 | * @see http://caniuse.com/Uint8Array 648 | * This is a type-conversion wrapper around `getBlockHash()` 649 | * @return {!Uint8Array} 650 | */ 651 | proto.pb.OutboundMessage.prototype.getBlockHash_asU8 = function() { 652 | return /** @type {!Uint8Array} */ (jspb.Message.bytesAsU8( 653 | this.getBlockHash())); 654 | }; 655 | 656 | 657 | /** @param {!(string|Uint8Array)} value */ 658 | proto.pb.OutboundMessage.prototype.setBlockHash = function(value) { 659 | jspb.Message.setProto3BytesField(this, 6, value); 660 | }; 661 | 662 | 663 | /** 664 | * repeated bytes signatures = 7; 665 | * @return {!(Array|Array)} 666 | */ 667 | proto.pb.OutboundMessage.prototype.getSignaturesList = function() { 668 | return /** @type {!(Array|Array)} */ (jspb.Message.getRepeatedField(this, 7)); 669 | }; 670 | 671 | 672 | /** 673 | * repeated bytes signatures = 7; 674 | * This is a type-conversion wrapper around `getSignaturesList()` 675 | * @return {!Array} 676 | */ 677 | proto.pb.OutboundMessage.prototype.getSignaturesList_asB64 = function() { 678 | return /** @type {!Array} */ (jspb.Message.bytesListAsB64( 679 | this.getSignaturesList())); 680 | }; 681 | 682 | 683 | /** 684 | * repeated bytes signatures = 7; 685 | * Note that Uint8Array is not supported on all browsers. 686 | * @see http://caniuse.com/Uint8Array 687 | * This is a type-conversion wrapper around `getSignaturesList()` 688 | * @return {!Array} 689 | */ 690 | proto.pb.OutboundMessage.prototype.getSignaturesList_asU8 = function() { 691 | return /** @type {!Array} */ (jspb.Message.bytesListAsU8( 692 | this.getSignaturesList())); 693 | }; 694 | 695 | 696 | /** @param {!(Array|Array)} value */ 697 | proto.pb.OutboundMessage.prototype.setSignaturesList = function(value) { 698 | jspb.Message.setField(this, 7, value || []); 699 | }; 700 | 701 | 702 | /** 703 | * @param {!(string|Uint8Array)} value 704 | * @param {number=} opt_index 705 | */ 706 | proto.pb.OutboundMessage.prototype.addSignatures = function(value, opt_index) { 707 | jspb.Message.addToRepeatedField(this, 7, value, opt_index); 708 | }; 709 | 710 | 711 | /** 712 | * Clears the list making it empty but non-null. 713 | */ 714 | proto.pb.OutboundMessage.prototype.clearSignaturesList = function() { 715 | this.setSignaturesList([]); 716 | }; 717 | 718 | 719 | /** 720 | * repeated bytes payloads = 8; 721 | * @return {!(Array|Array)} 722 | */ 723 | proto.pb.OutboundMessage.prototype.getPayloadsList = function() { 724 | return /** @type {!(Array|Array)} */ (jspb.Message.getRepeatedField(this, 8)); 725 | }; 726 | 727 | 728 | /** 729 | * repeated bytes payloads = 8; 730 | * This is a type-conversion wrapper around `getPayloadsList()` 731 | * @return {!Array} 732 | */ 733 | proto.pb.OutboundMessage.prototype.getPayloadsList_asB64 = function() { 734 | return /** @type {!Array} */ (jspb.Message.bytesListAsB64( 735 | this.getPayloadsList())); 736 | }; 737 | 738 | 739 | /** 740 | * repeated bytes payloads = 8; 741 | * Note that Uint8Array is not supported on all browsers. 742 | * @see http://caniuse.com/Uint8Array 743 | * This is a type-conversion wrapper around `getPayloadsList()` 744 | * @return {!Array} 745 | */ 746 | proto.pb.OutboundMessage.prototype.getPayloadsList_asU8 = function() { 747 | return /** @type {!Array} */ (jspb.Message.bytesListAsU8( 748 | this.getPayloadsList())); 749 | }; 750 | 751 | 752 | /** @param {!(Array|Array)} value */ 753 | proto.pb.OutboundMessage.prototype.setPayloadsList = function(value) { 754 | jspb.Message.setField(this, 8, value || []); 755 | }; 756 | 757 | 758 | /** 759 | * @param {!(string|Uint8Array)} value 760 | * @param {number=} opt_index 761 | */ 762 | proto.pb.OutboundMessage.prototype.addPayloads = function(value, opt_index) { 763 | jspb.Message.addToRepeatedField(this, 8, value, opt_index); 764 | }; 765 | 766 | 767 | /** 768 | * Clears the list making it empty but non-null. 769 | */ 770 | proto.pb.OutboundMessage.prototype.clearPayloadsList = function() { 771 | this.setPayloadsList([]); 772 | }; 773 | 774 | 775 | 776 | 777 | 778 | if (jspb.Message.GENERATE_TO_OBJECT) { 779 | /** 780 | * Creates an object representation of this proto suitable for use in Soy templates. 781 | * Field names that are reserved in JavaScript and will be renamed to pb_name. 782 | * To access a reserved field use, foo.pb_, eg, foo.pb_default. 783 | * For the list of reserved names please see: 784 | * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. 785 | * @param {boolean=} opt_includeInstance Whether to include the JSPB instance 786 | * for transitional soy proto support: http://goto/soy-param-migration 787 | * @return {!Object} 788 | */ 789 | proto.pb.InboundMessage.prototype.toObject = function(opt_includeInstance) { 790 | return proto.pb.InboundMessage.toObject(opt_includeInstance, this); 791 | }; 792 | 793 | 794 | /** 795 | * Static version of the {@see toObject} method. 796 | * @param {boolean|undefined} includeInstance Whether to include the JSPB 797 | * instance for transitional soy proto support: 798 | * http://goto/soy-param-migration 799 | * @param {!proto.pb.InboundMessage} msg The msg instance to transform. 800 | * @return {!Object} 801 | * @suppress {unusedLocalVariables} f is only used for nested messages 802 | */ 803 | proto.pb.InboundMessage.toObject = function(includeInstance, msg) { 804 | var f, obj = { 805 | src: jspb.Message.getFieldWithDefault(msg, 1, ""), 806 | payload: msg.getPayload_asB64(), 807 | prevSignature: msg.getPrevSignature_asB64() 808 | }; 809 | 810 | if (includeInstance) { 811 | obj.$jspbMessageInstance = msg; 812 | } 813 | return obj; 814 | }; 815 | } 816 | 817 | 818 | /** 819 | * Deserializes binary data (in protobuf wire format). 820 | * @param {jspb.ByteSource} bytes The bytes to deserialize. 821 | * @return {!proto.pb.InboundMessage} 822 | */ 823 | proto.pb.InboundMessage.deserializeBinary = function(bytes) { 824 | var reader = new jspb.BinaryReader(bytes); 825 | var msg = new proto.pb.InboundMessage; 826 | return proto.pb.InboundMessage.deserializeBinaryFromReader(msg, reader); 827 | }; 828 | 829 | 830 | /** 831 | * Deserializes binary data (in protobuf wire format) from the 832 | * given reader into the given message object. 833 | * @param {!proto.pb.InboundMessage} msg The message object to deserialize into. 834 | * @param {!jspb.BinaryReader} reader The BinaryReader to use. 835 | * @return {!proto.pb.InboundMessage} 836 | */ 837 | proto.pb.InboundMessage.deserializeBinaryFromReader = function(msg, reader) { 838 | while (reader.nextField()) { 839 | if (reader.isEndGroup()) { 840 | break; 841 | } 842 | var field = reader.getFieldNumber(); 843 | switch (field) { 844 | case 1: 845 | var value = /** @type {string} */ (reader.readString()); 846 | msg.setSrc(value); 847 | break; 848 | case 2: 849 | var value = /** @type {!Uint8Array} */ (reader.readBytes()); 850 | msg.setPayload(value); 851 | break; 852 | case 3: 853 | var value = /** @type {!Uint8Array} */ (reader.readBytes()); 854 | msg.setPrevSignature(value); 855 | break; 856 | default: 857 | reader.skipField(); 858 | break; 859 | } 860 | } 861 | return msg; 862 | }; 863 | 864 | 865 | /** 866 | * Serializes the message to binary data (in protobuf wire format). 867 | * @return {!Uint8Array} 868 | */ 869 | proto.pb.InboundMessage.prototype.serializeBinary = function() { 870 | var writer = new jspb.BinaryWriter(); 871 | proto.pb.InboundMessage.serializeBinaryToWriter(this, writer); 872 | return writer.getResultBuffer(); 873 | }; 874 | 875 | 876 | /** 877 | * Serializes the given message to binary data (in protobuf wire 878 | * format), writing to the given BinaryWriter. 879 | * @param {!proto.pb.InboundMessage} message 880 | * @param {!jspb.BinaryWriter} writer 881 | * @suppress {unusedLocalVariables} f is only used for nested messages 882 | */ 883 | proto.pb.InboundMessage.serializeBinaryToWriter = function(message, writer) { 884 | var f = undefined; 885 | f = message.getSrc(); 886 | if (f.length > 0) { 887 | writer.writeString( 888 | 1, 889 | f 890 | ); 891 | } 892 | f = message.getPayload_asU8(); 893 | if (f.length > 0) { 894 | writer.writeBytes( 895 | 2, 896 | f 897 | ); 898 | } 899 | f = message.getPrevSignature_asU8(); 900 | if (f.length > 0) { 901 | writer.writeBytes( 902 | 3, 903 | f 904 | ); 905 | } 906 | }; 907 | 908 | 909 | /** 910 | * optional string src = 1; 911 | * @return {string} 912 | */ 913 | proto.pb.InboundMessage.prototype.getSrc = function() { 914 | return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); 915 | }; 916 | 917 | 918 | /** @param {string} value */ 919 | proto.pb.InboundMessage.prototype.setSrc = function(value) { 920 | jspb.Message.setProto3StringField(this, 1, value); 921 | }; 922 | 923 | 924 | /** 925 | * optional bytes payload = 2; 926 | * @return {!(string|Uint8Array)} 927 | */ 928 | proto.pb.InboundMessage.prototype.getPayload = function() { 929 | return /** @type {!(string|Uint8Array)} */ (jspb.Message.getFieldWithDefault(this, 2, "")); 930 | }; 931 | 932 | 933 | /** 934 | * optional bytes payload = 2; 935 | * This is a type-conversion wrapper around `getPayload()` 936 | * @return {string} 937 | */ 938 | proto.pb.InboundMessage.prototype.getPayload_asB64 = function() { 939 | return /** @type {string} */ (jspb.Message.bytesAsB64( 940 | this.getPayload())); 941 | }; 942 | 943 | 944 | /** 945 | * optional bytes payload = 2; 946 | * Note that Uint8Array is not supported on all browsers. 947 | * @see http://caniuse.com/Uint8Array 948 | * This is a type-conversion wrapper around `getPayload()` 949 | * @return {!Uint8Array} 950 | */ 951 | proto.pb.InboundMessage.prototype.getPayload_asU8 = function() { 952 | return /** @type {!Uint8Array} */ (jspb.Message.bytesAsU8( 953 | this.getPayload())); 954 | }; 955 | 956 | 957 | /** @param {!(string|Uint8Array)} value */ 958 | proto.pb.InboundMessage.prototype.setPayload = function(value) { 959 | jspb.Message.setProto3BytesField(this, 2, value); 960 | }; 961 | 962 | 963 | /** 964 | * optional bytes prev_signature = 3; 965 | * @return {!(string|Uint8Array)} 966 | */ 967 | proto.pb.InboundMessage.prototype.getPrevSignature = function() { 968 | return /** @type {!(string|Uint8Array)} */ (jspb.Message.getFieldWithDefault(this, 3, "")); 969 | }; 970 | 971 | 972 | /** 973 | * optional bytes prev_signature = 3; 974 | * This is a type-conversion wrapper around `getPrevSignature()` 975 | * @return {string} 976 | */ 977 | proto.pb.InboundMessage.prototype.getPrevSignature_asB64 = function() { 978 | return /** @type {string} */ (jspb.Message.bytesAsB64( 979 | this.getPrevSignature())); 980 | }; 981 | 982 | 983 | /** 984 | * optional bytes prev_signature = 3; 985 | * Note that Uint8Array is not supported on all browsers. 986 | * @see http://caniuse.com/Uint8Array 987 | * This is a type-conversion wrapper around `getPrevSignature()` 988 | * @return {!Uint8Array} 989 | */ 990 | proto.pb.InboundMessage.prototype.getPrevSignature_asU8 = function() { 991 | return /** @type {!Uint8Array} */ (jspb.Message.bytesAsU8( 992 | this.getPrevSignature())); 993 | }; 994 | 995 | 996 | /** @param {!(string|Uint8Array)} value */ 997 | proto.pb.InboundMessage.prototype.setPrevSignature = function(value) { 998 | jspb.Message.setProto3BytesField(this, 3, value); 999 | }; 1000 | 1001 | 1002 | 1003 | 1004 | 1005 | if (jspb.Message.GENERATE_TO_OBJECT) { 1006 | /** 1007 | * Creates an object representation of this proto suitable for use in Soy templates. 1008 | * Field names that are reserved in JavaScript and will be renamed to pb_name. 1009 | * To access a reserved field use, foo.pb_, eg, foo.pb_default. 1010 | * For the list of reserved names please see: 1011 | * com.google.apps.jspb.JsClassTemplate.JS_RESERVED_WORDS. 1012 | * @param {boolean=} opt_includeInstance Whether to include the JSPB instance 1013 | * for transitional soy proto support: http://goto/soy-param-migration 1014 | * @return {!Object} 1015 | */ 1016 | proto.pb.Receipt.prototype.toObject = function(opt_includeInstance) { 1017 | return proto.pb.Receipt.toObject(opt_includeInstance, this); 1018 | }; 1019 | 1020 | 1021 | /** 1022 | * Static version of the {@see toObject} method. 1023 | * @param {boolean|undefined} includeInstance Whether to include the JSPB 1024 | * instance for transitional soy proto support: 1025 | * http://goto/soy-param-migration 1026 | * @param {!proto.pb.Receipt} msg The msg instance to transform. 1027 | * @return {!Object} 1028 | * @suppress {unusedLocalVariables} f is only used for nested messages 1029 | */ 1030 | proto.pb.Receipt.toObject = function(includeInstance, msg) { 1031 | var f, obj = { 1032 | prevSignature: msg.getPrevSignature_asB64(), 1033 | signature: msg.getSignature_asB64() 1034 | }; 1035 | 1036 | if (includeInstance) { 1037 | obj.$jspbMessageInstance = msg; 1038 | } 1039 | return obj; 1040 | }; 1041 | } 1042 | 1043 | 1044 | /** 1045 | * Deserializes binary data (in protobuf wire format). 1046 | * @param {jspb.ByteSource} bytes The bytes to deserialize. 1047 | * @return {!proto.pb.Receipt} 1048 | */ 1049 | proto.pb.Receipt.deserializeBinary = function(bytes) { 1050 | var reader = new jspb.BinaryReader(bytes); 1051 | var msg = new proto.pb.Receipt; 1052 | return proto.pb.Receipt.deserializeBinaryFromReader(msg, reader); 1053 | }; 1054 | 1055 | 1056 | /** 1057 | * Deserializes binary data (in protobuf wire format) from the 1058 | * given reader into the given message object. 1059 | * @param {!proto.pb.Receipt} msg The message object to deserialize into. 1060 | * @param {!jspb.BinaryReader} reader The BinaryReader to use. 1061 | * @return {!proto.pb.Receipt} 1062 | */ 1063 | proto.pb.Receipt.deserializeBinaryFromReader = function(msg, reader) { 1064 | while (reader.nextField()) { 1065 | if (reader.isEndGroup()) { 1066 | break; 1067 | } 1068 | var field = reader.getFieldNumber(); 1069 | switch (field) { 1070 | case 1: 1071 | var value = /** @type {!Uint8Array} */ (reader.readBytes()); 1072 | msg.setPrevSignature(value); 1073 | break; 1074 | case 2: 1075 | var value = /** @type {!Uint8Array} */ (reader.readBytes()); 1076 | msg.setSignature(value); 1077 | break; 1078 | default: 1079 | reader.skipField(); 1080 | break; 1081 | } 1082 | } 1083 | return msg; 1084 | }; 1085 | 1086 | 1087 | /** 1088 | * Serializes the message to binary data (in protobuf wire format). 1089 | * @return {!Uint8Array} 1090 | */ 1091 | proto.pb.Receipt.prototype.serializeBinary = function() { 1092 | var writer = new jspb.BinaryWriter(); 1093 | proto.pb.Receipt.serializeBinaryToWriter(this, writer); 1094 | return writer.getResultBuffer(); 1095 | }; 1096 | 1097 | 1098 | /** 1099 | * Serializes the given message to binary data (in protobuf wire 1100 | * format), writing to the given BinaryWriter. 1101 | * @param {!proto.pb.Receipt} message 1102 | * @param {!jspb.BinaryWriter} writer 1103 | * @suppress {unusedLocalVariables} f is only used for nested messages 1104 | */ 1105 | proto.pb.Receipt.serializeBinaryToWriter = function(message, writer) { 1106 | var f = undefined; 1107 | f = message.getPrevSignature_asU8(); 1108 | if (f.length > 0) { 1109 | writer.writeBytes( 1110 | 1, 1111 | f 1112 | ); 1113 | } 1114 | f = message.getSignature_asU8(); 1115 | if (f.length > 0) { 1116 | writer.writeBytes( 1117 | 2, 1118 | f 1119 | ); 1120 | } 1121 | }; 1122 | 1123 | 1124 | /** 1125 | * optional bytes prev_signature = 1; 1126 | * @return {!(string|Uint8Array)} 1127 | */ 1128 | proto.pb.Receipt.prototype.getPrevSignature = function() { 1129 | return /** @type {!(string|Uint8Array)} */ (jspb.Message.getFieldWithDefault(this, 1, "")); 1130 | }; 1131 | 1132 | 1133 | /** 1134 | * optional bytes prev_signature = 1; 1135 | * This is a type-conversion wrapper around `getPrevSignature()` 1136 | * @return {string} 1137 | */ 1138 | proto.pb.Receipt.prototype.getPrevSignature_asB64 = function() { 1139 | return /** @type {string} */ (jspb.Message.bytesAsB64( 1140 | this.getPrevSignature())); 1141 | }; 1142 | 1143 | 1144 | /** 1145 | * optional bytes prev_signature = 1; 1146 | * Note that Uint8Array is not supported on all browsers. 1147 | * @see http://caniuse.com/Uint8Array 1148 | * This is a type-conversion wrapper around `getPrevSignature()` 1149 | * @return {!Uint8Array} 1150 | */ 1151 | proto.pb.Receipt.prototype.getPrevSignature_asU8 = function() { 1152 | return /** @type {!Uint8Array} */ (jspb.Message.bytesAsU8( 1153 | this.getPrevSignature())); 1154 | }; 1155 | 1156 | 1157 | /** @param {!(string|Uint8Array)} value */ 1158 | proto.pb.Receipt.prototype.setPrevSignature = function(value) { 1159 | jspb.Message.setProto3BytesField(this, 1, value); 1160 | }; 1161 | 1162 | 1163 | /** 1164 | * optional bytes signature = 2; 1165 | * @return {!(string|Uint8Array)} 1166 | */ 1167 | proto.pb.Receipt.prototype.getSignature = function() { 1168 | return /** @type {!(string|Uint8Array)} */ (jspb.Message.getFieldWithDefault(this, 2, "")); 1169 | }; 1170 | 1171 | 1172 | /** 1173 | * optional bytes signature = 2; 1174 | * This is a type-conversion wrapper around `getSignature()` 1175 | * @return {string} 1176 | */ 1177 | proto.pb.Receipt.prototype.getSignature_asB64 = function() { 1178 | return /** @type {string} */ (jspb.Message.bytesAsB64( 1179 | this.getSignature())); 1180 | }; 1181 | 1182 | 1183 | /** 1184 | * optional bytes signature = 2; 1185 | * Note that Uint8Array is not supported on all browsers. 1186 | * @see http://caniuse.com/Uint8Array 1187 | * This is a type-conversion wrapper around `getSignature()` 1188 | * @return {!Uint8Array} 1189 | */ 1190 | proto.pb.Receipt.prototype.getSignature_asU8 = function() { 1191 | return /** @type {!Uint8Array} */ (jspb.Message.bytesAsU8( 1192 | this.getSignature())); 1193 | }; 1194 | 1195 | 1196 | /** @param {!(string|Uint8Array)} value */ 1197 | proto.pb.Receipt.prototype.setSignature = function(value) { 1198 | jspb.Message.setProto3BytesField(this, 2, value); 1199 | }; 1200 | 1201 | 1202 | /** 1203 | * @enum {number} 1204 | */ 1205 | proto.pb.ClientMessageType = { 1206 | OUTBOUND_MESSAGE: 0, 1207 | INBOUND_MESSAGE: 1, 1208 | RECEIPT: 2 1209 | }; 1210 | 1211 | /** 1212 | * @enum {number} 1213 | */ 1214 | proto.pb.CompressionType = { 1215 | COMPRESSION_NONE: 0, 1216 | COMPRESSION_ZLIB: 1 1217 | }; 1218 | 1219 | goog.object.extend(exports, proto.pb); 1220 | --------------------------------------------------------------------------------