id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
15,200
postmanlabs/postman-collection
lib/collection/response.js
function () { var sizeInfo = { body: 0, header: 0, total: 0 }, contentEncoding = this.headers.get(CONTENT_ENCODING), contentLength = this.headers.get(CONTENT_LENGTH), isCompressed = false, byteLength; // if server sent encoded data, we should first try deriving length from headers if (_.isString(contentEncoding)) { // desensitise case of content encoding contentEncoding = contentEncoding.toLowerCase(); // eslint-disable-next-line lodash/prefer-includes isCompressed = (contentEncoding.indexOf('gzip') > -1) || (contentEncoding.indexOf('deflate') > -1); } // if 'Content-Length' header is present and encoding is of type gzip/deflate, we take body as declared by // server. else we need to compute the same. if (contentLength && isCompressed && util.isNumeric(contentLength)) { sizeInfo.body = _.parseInt(contentLength, 10); } // if there is a stream defined which looks like buffer, use it's data and move on else if (this.stream) { byteLength = this.stream.byteLength; sizeInfo.body = util.isNumeric(byteLength) ? byteLength : 0; } // otherwise, if body is defined, we try get the true length of the body else if (!_.isNil(this.body)) { sizeInfo.body = supportsBuffer ? Buffer.byteLength(this.body.toString()) : this.body.toString().length; } // size of header is added // https://tools.ietf.org/html/rfc7230#section-3 // HTTP-message = start-line (request-line / status-line) // *( header-field CRLF ) // CRLF // [ message-body ] // status-line = HTTP-version SP status-code SP reason-phrase CRLF sizeInfo.header = (HTTP_X_X + SP + this.code + SP + this.reason() + CRLF + CRLF).length + this.headers.contentSize(); // compute the approximate total body size by adding size of header and body sizeInfo.total = (sizeInfo.body || 0) + (sizeInfo.header || 0); return sizeInfo; }
javascript
function () { var sizeInfo = { body: 0, header: 0, total: 0 }, contentEncoding = this.headers.get(CONTENT_ENCODING), contentLength = this.headers.get(CONTENT_LENGTH), isCompressed = false, byteLength; // if server sent encoded data, we should first try deriving length from headers if (_.isString(contentEncoding)) { // desensitise case of content encoding contentEncoding = contentEncoding.toLowerCase(); // eslint-disable-next-line lodash/prefer-includes isCompressed = (contentEncoding.indexOf('gzip') > -1) || (contentEncoding.indexOf('deflate') > -1); } // if 'Content-Length' header is present and encoding is of type gzip/deflate, we take body as declared by // server. else we need to compute the same. if (contentLength && isCompressed && util.isNumeric(contentLength)) { sizeInfo.body = _.parseInt(contentLength, 10); } // if there is a stream defined which looks like buffer, use it's data and move on else if (this.stream) { byteLength = this.stream.byteLength; sizeInfo.body = util.isNumeric(byteLength) ? byteLength : 0; } // otherwise, if body is defined, we try get the true length of the body else if (!_.isNil(this.body)) { sizeInfo.body = supportsBuffer ? Buffer.byteLength(this.body.toString()) : this.body.toString().length; } // size of header is added // https://tools.ietf.org/html/rfc7230#section-3 // HTTP-message = start-line (request-line / status-line) // *( header-field CRLF ) // CRLF // [ message-body ] // status-line = HTTP-version SP status-code SP reason-phrase CRLF sizeInfo.header = (HTTP_X_X + SP + this.code + SP + this.reason() + CRLF + CRLF).length + this.headers.contentSize(); // compute the approximate total body size by adding size of header and body sizeInfo.total = (sizeInfo.body || 0) + (sizeInfo.header || 0); return sizeInfo; }
[ "function", "(", ")", "{", "var", "sizeInfo", "=", "{", "body", ":", "0", ",", "header", ":", "0", ",", "total", ":", "0", "}", ",", "contentEncoding", "=", "this", ".", "headers", ".", "get", "(", "CONTENT_ENCODING", ")", ",", "contentLength", "=", "this", ".", "headers", ".", "get", "(", "CONTENT_LENGTH", ")", ",", "isCompressed", "=", "false", ",", "byteLength", ";", "// if server sent encoded data, we should first try deriving length from headers", "if", "(", "_", ".", "isString", "(", "contentEncoding", ")", ")", "{", "// desensitise case of content encoding", "contentEncoding", "=", "contentEncoding", ".", "toLowerCase", "(", ")", ";", "// eslint-disable-next-line lodash/prefer-includes", "isCompressed", "=", "(", "contentEncoding", ".", "indexOf", "(", "'gzip'", ")", ">", "-", "1", ")", "||", "(", "contentEncoding", ".", "indexOf", "(", "'deflate'", ")", ">", "-", "1", ")", ";", "}", "// if 'Content-Length' header is present and encoding is of type gzip/deflate, we take body as declared by", "// server. else we need to compute the same.", "if", "(", "contentLength", "&&", "isCompressed", "&&", "util", ".", "isNumeric", "(", "contentLength", ")", ")", "{", "sizeInfo", ".", "body", "=", "_", ".", "parseInt", "(", "contentLength", ",", "10", ")", ";", "}", "// if there is a stream defined which looks like buffer, use it's data and move on", "else", "if", "(", "this", ".", "stream", ")", "{", "byteLength", "=", "this", ".", "stream", ".", "byteLength", ";", "sizeInfo", ".", "body", "=", "util", ".", "isNumeric", "(", "byteLength", ")", "?", "byteLength", ":", "0", ";", "}", "// otherwise, if body is defined, we try get the true length of the body", "else", "if", "(", "!", "_", ".", "isNil", "(", "this", ".", "body", ")", ")", "{", "sizeInfo", ".", "body", "=", "supportsBuffer", "?", "Buffer", ".", "byteLength", "(", "this", ".", "body", ".", "toString", "(", ")", ")", ":", "this", ".", "body", ".", "toString", "(", ")", ".", "length", ";", "}", "// size of header is added", "// https://tools.ietf.org/html/rfc7230#section-3", "// HTTP-message = start-line (request-line / status-line)", "// *( header-field CRLF )", "// CRLF", "// [ message-body ]", "// status-line = HTTP-version SP status-code SP reason-phrase CRLF", "sizeInfo", ".", "header", "=", "(", "HTTP_X_X", "+", "SP", "+", "this", ".", "code", "+", "SP", "+", "this", ".", "reason", "(", ")", "+", "CRLF", "+", "CRLF", ")", ".", "length", "+", "this", ".", "headers", ".", "contentSize", "(", ")", ";", "// compute the approximate total body size by adding size of header and body", "sizeInfo", ".", "total", "=", "(", "sizeInfo", ".", "body", "||", "0", ")", "+", "(", "sizeInfo", ".", "header", "||", "0", ")", ";", "return", "sizeInfo", ";", "}" ]
Get the response size by computing the same from content length header or using the actual response body. @returns {Number} @todo write unit tests
[ "Get", "the", "response", "size", "by", "computing", "the", "same", "from", "content", "length", "header", "or", "using", "the", "actual", "response", "body", "." ]
1cacd38a98c82f86d3f6c61d16a57465bbd78b63
https://github.com/postmanlabs/postman-collection/blob/1cacd38a98c82f86d3f6c61d16a57465bbd78b63/lib/collection/response.js#L439-L487
15,201
postmanlabs/postman-collection
lib/collection/response.js
function () { var contentEncoding = this.headers.get(CONTENT_ENCODING), body = this.stream || this.body, source; if (contentEncoding) { source = HEADER; } // if the encoding is not found, we check else if (body) { // @todo add detection for deflate // eslint-disable-next-line lodash/prefer-matches if (body[0] === 0x1F && body[1] === 0x8B && body[2] === 0x8) { contentEncoding = GZIP; } if (contentEncoding) { source = BODY; } } return { format: contentEncoding, source: source }; }
javascript
function () { var contentEncoding = this.headers.get(CONTENT_ENCODING), body = this.stream || this.body, source; if (contentEncoding) { source = HEADER; } // if the encoding is not found, we check else if (body) { // @todo add detection for deflate // eslint-disable-next-line lodash/prefer-matches if (body[0] === 0x1F && body[1] === 0x8B && body[2] === 0x8) { contentEncoding = GZIP; } if (contentEncoding) { source = BODY; } } return { format: contentEncoding, source: source }; }
[ "function", "(", ")", "{", "var", "contentEncoding", "=", "this", ".", "headers", ".", "get", "(", "CONTENT_ENCODING", ")", ",", "body", "=", "this", ".", "stream", "||", "this", ".", "body", ",", "source", ";", "if", "(", "contentEncoding", ")", "{", "source", "=", "HEADER", ";", "}", "// if the encoding is not found, we check", "else", "if", "(", "body", ")", "{", "// @todo add detection for deflate", "// eslint-disable-next-line lodash/prefer-matches", "if", "(", "body", "[", "0", "]", "===", "0x1F", "&&", "body", "[", "1", "]", "===", "0x8B", "&&", "body", "[", "2", "]", "===", "0x8", ")", "{", "contentEncoding", "=", "GZIP", ";", "}", "if", "(", "contentEncoding", ")", "{", "source", "=", "BODY", ";", "}", "}", "return", "{", "format", ":", "contentEncoding", ",", "source", ":", "source", "}", ";", "}" ]
Returns the response encoding defined as header or detected from body. @private @returns {Object} - {format: string, source: string}
[ "Returns", "the", "response", "encoding", "defined", "as", "header", "or", "detected", "from", "body", "." ]
1cacd38a98c82f86d3f6c61d16a57465bbd78b63
https://github.com/postmanlabs/postman-collection/blob/1cacd38a98c82f86d3f6c61d16a57465bbd78b63/lib/collection/response.js#L495-L520
15,202
postmanlabs/postman-collection
lib/collection/response.js
function (response, cookies) { return new Response({ cookie: cookies, body: response.body.toString(), stream: response.body, header: response.headers, code: response.statusCode, status: response.statusMessage, responseTime: response.elapsedTime }); }
javascript
function (response, cookies) { return new Response({ cookie: cookies, body: response.body.toString(), stream: response.body, header: response.headers, code: response.statusCode, status: response.statusMessage, responseTime: response.elapsedTime }); }
[ "function", "(", "response", ",", "cookies", ")", "{", "return", "new", "Response", "(", "{", "cookie", ":", "cookies", ",", "body", ":", "response", ".", "body", ".", "toString", "(", ")", ",", "stream", ":", "response", ".", "body", ",", "header", ":", "response", ".", "headers", ",", "code", ":", "response", ".", "statusCode", ",", "status", ":", "response", ".", "statusMessage", ",", "responseTime", ":", "response", ".", "elapsedTime", "}", ")", ";", "}" ]
Converts the response object from the request module to the postman responseBody format @param {Object} response The response object, as received from the request module @param {Object} cookies @returns {Object} The transformed responseBody @todo Add a key: `originalRequest` to the returned object as well, referring to response.request
[ "Converts", "the", "response", "object", "from", "the", "request", "module", "to", "the", "postman", "responseBody", "format" ]
1cacd38a98c82f86d3f6c61d16a57465bbd78b63
https://github.com/postmanlabs/postman-collection/blob/1cacd38a98c82f86d3f6c61d16a57465bbd78b63/lib/collection/response.js#L551-L561
15,203
postmanlabs/postman-collection
lib/collection/response.js
function (timings) { // bail out if timing information is not provided if (!(timings && timings.offset)) { return; } var phases, offset = timings.offset; // REFER: https://github.com/postmanlabs/postman-request/blob/v2.88.1-postman.5/request.js#L996 phases = { prepare: offset.request, wait: offset.socket - offset.request, dns: offset.lookup - offset.socket, tcp: offset.connect - offset.lookup, firstByte: offset.response - offset.connect, download: offset.end - offset.response, process: offset.done - offset.end, total: offset.done }; if (offset.secureConnect) { phases.secureHandshake = offset.secureConnect - offset.connect; phases.firstByte = offset.response - offset.secureConnect; } return phases; }
javascript
function (timings) { // bail out if timing information is not provided if (!(timings && timings.offset)) { return; } var phases, offset = timings.offset; // REFER: https://github.com/postmanlabs/postman-request/blob/v2.88.1-postman.5/request.js#L996 phases = { prepare: offset.request, wait: offset.socket - offset.request, dns: offset.lookup - offset.socket, tcp: offset.connect - offset.lookup, firstByte: offset.response - offset.connect, download: offset.end - offset.response, process: offset.done - offset.end, total: offset.done }; if (offset.secureConnect) { phases.secureHandshake = offset.secureConnect - offset.connect; phases.firstByte = offset.response - offset.secureConnect; } return phases; }
[ "function", "(", "timings", ")", "{", "// bail out if timing information is not provided", "if", "(", "!", "(", "timings", "&&", "timings", ".", "offset", ")", ")", "{", "return", ";", "}", "var", "phases", ",", "offset", "=", "timings", ".", "offset", ";", "// REFER: https://github.com/postmanlabs/postman-request/blob/v2.88.1-postman.5/request.js#L996", "phases", "=", "{", "prepare", ":", "offset", ".", "request", ",", "wait", ":", "offset", ".", "socket", "-", "offset", ".", "request", ",", "dns", ":", "offset", ".", "lookup", "-", "offset", ".", "socket", ",", "tcp", ":", "offset", ".", "connect", "-", "offset", ".", "lookup", ",", "firstByte", ":", "offset", ".", "response", "-", "offset", ".", "connect", ",", "download", ":", "offset", ".", "end", "-", "offset", ".", "response", ",", "process", ":", "offset", ".", "done", "-", "offset", ".", "end", ",", "total", ":", "offset", ".", "done", "}", ";", "if", "(", "offset", ".", "secureConnect", ")", "{", "phases", ".", "secureHandshake", "=", "offset", ".", "secureConnect", "-", "offset", ".", "connect", ";", "phases", ".", "firstByte", "=", "offset", ".", "response", "-", "offset", ".", "secureConnect", ";", "}", "return", "phases", ";", "}" ]
Returns the durations of each request phase in milliseconds @typedef Response~timings @property {Number} start - timestamp of the request sent from the client (in Unix Epoch milliseconds) @property {Object} offset - event timestamps in millisecond resolution relative to start @property {Number} offset.request - timestamp of the start of the request @property {Number} offset.socket - timestamp when the socket is assigned to the request @property {Number} offset.lookup - timestamp when the DNS has been resolved @property {Number} offset.connect - timestamp when the server acknowledges the TCP connection @property {Number} offset.secureConnect - timestamp when secure handshaking process is completed @property {Number} offset.response - timestamp when the first bytes are received from the server @property {Number} offset.end - timestamp when the last bytes of the response are received @property {Number} offset.done - timestamp when the response is received at the client @note If there were redirects, the properties reflect the timings of the final request in the redirect chain @param {Response~timings} timings @returns {Object} @example Output Request.timingPhases(timings); { prepare: Number, // duration of request preparation wait: Number, // duration of socket initialization dns: Number, // duration of DNS lookup tcp: Number, // duration of TCP connection secureHandshake: Number, // duration of secure handshake firstByte: Number, // duration of HTTP server response download: Number, // duration of HTTP download process: Number, // duration of response processing total: Number // duration entire HTTP round-trip } @note if there were redirects, the properties reflect the timings of the final request in the redirect chain.
[ "Returns", "the", "durations", "of", "each", "request", "phase", "in", "milliseconds" ]
1cacd38a98c82f86d3f6c61d16a57465bbd78b63
https://github.com/postmanlabs/postman-collection/blob/1cacd38a98c82f86d3f6c61d16a57465bbd78b63/lib/collection/response.js#L640-L667
15,204
evanw/node-source-map-support
source-map-support.js
getErrorSource
function getErrorSource(error) { var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack); if (match) { var source = match[1]; var line = +match[2]; var column = +match[3]; // Support the inline sourceContents inside the source map var contents = fileContentsCache[source]; // Support files on disk if (!contents && fs && fs.existsSync(source)) { try { contents = fs.readFileSync(source, 'utf8'); } catch (er) { contents = ''; } } // Format the line from the original source code like node does if (contents) { var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1]; if (code) { return source + ':' + line + '\n' + code + '\n' + new Array(column).join(' ') + '^'; } } } return null; }
javascript
function getErrorSource(error) { var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack); if (match) { var source = match[1]; var line = +match[2]; var column = +match[3]; // Support the inline sourceContents inside the source map var contents = fileContentsCache[source]; // Support files on disk if (!contents && fs && fs.existsSync(source)) { try { contents = fs.readFileSync(source, 'utf8'); } catch (er) { contents = ''; } } // Format the line from the original source code like node does if (contents) { var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1]; if (code) { return source + ':' + line + '\n' + code + '\n' + new Array(column).join(' ') + '^'; } } } return null; }
[ "function", "getErrorSource", "(", "error", ")", "{", "var", "match", "=", "/", "\\n at [^(]+ \\((.*):(\\d+):(\\d+)\\)", "/", ".", "exec", "(", "error", ".", "stack", ")", ";", "if", "(", "match", ")", "{", "var", "source", "=", "match", "[", "1", "]", ";", "var", "line", "=", "+", "match", "[", "2", "]", ";", "var", "column", "=", "+", "match", "[", "3", "]", ";", "// Support the inline sourceContents inside the source map", "var", "contents", "=", "fileContentsCache", "[", "source", "]", ";", "// Support files on disk", "if", "(", "!", "contents", "&&", "fs", "&&", "fs", ".", "existsSync", "(", "source", ")", ")", "{", "try", "{", "contents", "=", "fs", ".", "readFileSync", "(", "source", ",", "'utf8'", ")", ";", "}", "catch", "(", "er", ")", "{", "contents", "=", "''", ";", "}", "}", "// Format the line from the original source code like node does", "if", "(", "contents", ")", "{", "var", "code", "=", "contents", ".", "split", "(", "/", "(?:\\r\\n|\\r|\\n)", "/", ")", "[", "line", "-", "1", "]", ";", "if", "(", "code", ")", "{", "return", "source", "+", "':'", "+", "line", "+", "'\\n'", "+", "code", "+", "'\\n'", "+", "new", "Array", "(", "column", ")", ".", "join", "(", "' '", ")", "+", "'^'", ";", "}", "}", "}", "return", "null", ";", "}" ]
Generate position and snippet of original source with pointer
[ "Generate", "position", "and", "snippet", "of", "original", "source", "with", "pointer" ]
208d1df2865143dd74ae83f42db2fdab584dc0bd
https://github.com/evanw/node-source-map-support/blob/208d1df2865143dd74ae83f42db2fdab584dc0bd/source-map-support.js#L404-L433
15,205
dturing/node-gstreamer-superficial
examples/m-jpeg-streamer/server.js
function() { appsink.pull(function(buf, caps) { if (caps) { //console.log("CAPS", caps); mimeType = caps['name']; } if (buf) { //console.log("BUFFER size",buf.length); for( c in clients ) { // write header contained in caps clients[c].write('--'+boundary+'\r\n'); clients[c].write('Content-Type: ' + mimeType + '\r\n' + 'Content-Length: ' + buf.length + '\r\n'); clients[c].write('\r\n'); /* debug to ensure the jpeg is good if(bOnce == 1) { fs.writeFile("buffer.jpeg", buf); bOnce = 0; } */ clients[c].write(buf, 'binary'); clients[c].write('\r\n'); } pull(); } else { setTimeout(pull, 500); } }); }
javascript
function() { appsink.pull(function(buf, caps) { if (caps) { //console.log("CAPS", caps); mimeType = caps['name']; } if (buf) { //console.log("BUFFER size",buf.length); for( c in clients ) { // write header contained in caps clients[c].write('--'+boundary+'\r\n'); clients[c].write('Content-Type: ' + mimeType + '\r\n' + 'Content-Length: ' + buf.length + '\r\n'); clients[c].write('\r\n'); /* debug to ensure the jpeg is good if(bOnce == 1) { fs.writeFile("buffer.jpeg", buf); bOnce = 0; } */ clients[c].write(buf, 'binary'); clients[c].write('\r\n'); } pull(); } else { setTimeout(pull, 500); } }); }
[ "function", "(", ")", "{", "appsink", ".", "pull", "(", "function", "(", "buf", ",", "caps", ")", "{", "if", "(", "caps", ")", "{", "//console.log(\"CAPS\", caps);", "mimeType", "=", "caps", "[", "'name'", "]", ";", "}", "if", "(", "buf", ")", "{", "//console.log(\"BUFFER size\",buf.length);", "for", "(", "c", "in", "clients", ")", "{", "// write header contained in caps", "clients", "[", "c", "]", ".", "write", "(", "'--'", "+", "boundary", "+", "'\\r\\n'", ")", ";", "clients", "[", "c", "]", ".", "write", "(", "'Content-Type: '", "+", "mimeType", "+", "'\\r\\n'", "+", "'Content-Length: '", "+", "buf", ".", "length", "+", "'\\r\\n'", ")", ";", "clients", "[", "c", "]", ".", "write", "(", "'\\r\\n'", ")", ";", "/* debug to ensure the jpeg is good\n\t\t\t if(bOnce == 1) {\n \t\t\t fs.writeFile(\"buffer.jpeg\", buf);\n \t\t\t\tbOnce = 0;\n\t\t\t }\n\t\t\t */", "clients", "[", "c", "]", ".", "write", "(", "buf", ",", "'binary'", ")", ";", "clients", "[", "c", "]", ".", "write", "(", "'\\r\\n'", ")", ";", "}", "pull", "(", ")", ";", "}", "else", "{", "setTimeout", "(", "pull", ",", "500", ")", ";", "}", "}", ")", ";", "}" ]
var bOnce = 1;
[ "var", "bOnce", "=", "1", ";" ]
0b569e89acf67160720563e8da88fb4562c3a253
https://github.com/dturing/node-gstreamer-superficial/blob/0b569e89acf67160720563e8da88fb4562c3a253/examples/m-jpeg-streamer/server.js#L20-L49
15,206
fontello/ttf2eot
index.js
strbuf
function strbuf(str) { var b = new ByteBuffer(str.length + 4); b.setUint16 (0, str.length, true); for (var i = 0; i < str.length; i += 2) { b.setUint16 (i + 2, str.getUint16 (i), true); } b.setUint16 (b.length - 2, 0, true); return b; }
javascript
function strbuf(str) { var b = new ByteBuffer(str.length + 4); b.setUint16 (0, str.length, true); for (var i = 0; i < str.length; i += 2) { b.setUint16 (i + 2, str.getUint16 (i), true); } b.setUint16 (b.length - 2, 0, true); return b; }
[ "function", "strbuf", "(", "str", ")", "{", "var", "b", "=", "new", "ByteBuffer", "(", "str", ".", "length", "+", "4", ")", ";", "b", ".", "setUint16", "(", "0", ",", "str", ".", "length", ",", "true", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "str", ".", "length", ";", "i", "+=", "2", ")", "{", "b", ".", "setUint16", "(", "i", "+", "2", ",", "str", ".", "getUint16", "(", "i", ")", ",", "true", ")", ";", "}", "b", ".", "setUint16", "(", "b", ".", "length", "-", "2", ",", "0", ",", "true", ")", ";", "return", "b", ";", "}" ]
Utility function to convert buffer of utf16be chars to buffer of utf16le chars prefixed with length and suffixed with zero
[ "Utility", "function", "to", "convert", "buffer", "of", "utf16be", "chars", "to", "buffer", "of", "utf16le", "chars", "prefixed", "with", "length", "and", "suffixed", "with", "zero" ]
6ad3ea45567eda77ba3b5986e356ab970d887203
https://github.com/fontello/ttf2eot/blob/6ad3ea45567eda77ba3b5986e356ab970d887203/index.js#L89-L101
15,207
trivago/parallel-webpack
src/watchModeIPC.js
startWatchIPCServer
function startWatchIPCServer(callback, configIndices) { ipc.config.id = serverName; ipc.config.retry = 3; ipc.config.silent = true; ipc.serve( function() { ipc.server.on( 'done', watchDoneHandler.bind(this, callback, ipc, configIndices) ); } ); ipc.server.start(); }
javascript
function startWatchIPCServer(callback, configIndices) { ipc.config.id = serverName; ipc.config.retry = 3; ipc.config.silent = true; ipc.serve( function() { ipc.server.on( 'done', watchDoneHandler.bind(this, callback, ipc, configIndices) ); } ); ipc.server.start(); }
[ "function", "startWatchIPCServer", "(", "callback", ",", "configIndices", ")", "{", "ipc", ".", "config", ".", "id", "=", "serverName", ";", "ipc", ".", "config", ".", "retry", "=", "3", ";", "ipc", ".", "config", ".", "silent", "=", "true", ";", "ipc", ".", "serve", "(", "function", "(", ")", "{", "ipc", ".", "server", ".", "on", "(", "'done'", ",", "watchDoneHandler", ".", "bind", "(", "this", ",", "callback", ",", "ipc", ",", "configIndices", ")", ")", ";", "}", ")", ";", "ipc", ".", "server", ".", "start", "(", ")", ";", "}" ]
Start IPC server and listens for 'done' message from child processes @param {any} callback - callback invoked once 'done' has been emitted by each confugration @param {any} configIndices - array indices of configuration
[ "Start", "IPC", "server", "and", "listens", "for", "done", "message", "from", "child", "processes" ]
66da53e44a04795ab8ea705c28f9848ae5e7c7d7
https://github.com/trivago/parallel-webpack/blob/66da53e44a04795ab8ea705c28f9848ae5e7c7d7/src/watchModeIPC.js#L12-L26
15,208
trivago/parallel-webpack
index.js
run
function run(configPath, options, callback) { var config, argvBackup = process.argv, farmOptions = assign({}, options); options = options || {}; if(options.colors === undefined) { options.colors = chalk.supportsColor; } if(!options.argv) { options.argv = []; } options.argv.unshift(process.execPath, 'parallel-webpack'); try { process.argv = options.argv; config = loadConfigurationFile(configPath); process.argv = argvBackup; } catch(e) { process.argv = argvBackup; return Promise.reject(new Error( chalk.red('[WEBPACK]') + ' Could not load configuration file ' + chalk.underline(configPath) + "\n" + e )); } if (!validate(farmOptions)) { return Promise.reject(new Error( 'Options validation failed:\n' + validate.errors.map(function(error) { return 'Property: "options' + error.dataPath + '" ' + error.message; }).join('\n') )); } var workers = workerFarm(farmOptions, require.resolve('./src/webpackWorker')); var shutdownCallback = function() { if (notSilent(options)) { console.log(chalk.red('[WEBPACK]') + ' Forcefully shutting down'); } workerFarm.end(workers); }; function keepAliveAfterFinishCallback(cb){ if(options.keepAliveAfterFinish){ setTimeout(cb, options.keepAliveAfterFinish); } else { cb(); } } function finalCallback(){ workerFarm.end(workers); process.removeListener("SIGINT", shutdownCallback); } process.on('SIGINT', shutdownCallback); var startTime = Date.now(); var farmPromise = startFarm( config, configPath, options, Promise.promisify(workers), callback ).error(function(err) { if(notSilent(options)) { console.log('%s Build failed after %s seconds', chalk.red('[WEBPACK]'), chalk.blue((Date.now() - startTime) / 1000)); } return Promise.reject(err); }).then(function (results) { if(notSilent(options)) { console.log('%s Finished build after %s seconds', chalk.blue('[WEBPACK]'), chalk.blue((Date.now() - startTime) / 1000)); } results = results.filter(function(result) { return result; }); if(results.length) { return results; } }).finally(function() { keepAliveAfterFinishCallback(finalCallback); }); if (!options.watch) { farmPromise.asCallback(callback); } return farmPromise; }
javascript
function run(configPath, options, callback) { var config, argvBackup = process.argv, farmOptions = assign({}, options); options = options || {}; if(options.colors === undefined) { options.colors = chalk.supportsColor; } if(!options.argv) { options.argv = []; } options.argv.unshift(process.execPath, 'parallel-webpack'); try { process.argv = options.argv; config = loadConfigurationFile(configPath); process.argv = argvBackup; } catch(e) { process.argv = argvBackup; return Promise.reject(new Error( chalk.red('[WEBPACK]') + ' Could not load configuration file ' + chalk.underline(configPath) + "\n" + e )); } if (!validate(farmOptions)) { return Promise.reject(new Error( 'Options validation failed:\n' + validate.errors.map(function(error) { return 'Property: "options' + error.dataPath + '" ' + error.message; }).join('\n') )); } var workers = workerFarm(farmOptions, require.resolve('./src/webpackWorker')); var shutdownCallback = function() { if (notSilent(options)) { console.log(chalk.red('[WEBPACK]') + ' Forcefully shutting down'); } workerFarm.end(workers); }; function keepAliveAfterFinishCallback(cb){ if(options.keepAliveAfterFinish){ setTimeout(cb, options.keepAliveAfterFinish); } else { cb(); } } function finalCallback(){ workerFarm.end(workers); process.removeListener("SIGINT", shutdownCallback); } process.on('SIGINT', shutdownCallback); var startTime = Date.now(); var farmPromise = startFarm( config, configPath, options, Promise.promisify(workers), callback ).error(function(err) { if(notSilent(options)) { console.log('%s Build failed after %s seconds', chalk.red('[WEBPACK]'), chalk.blue((Date.now() - startTime) / 1000)); } return Promise.reject(err); }).then(function (results) { if(notSilent(options)) { console.log('%s Finished build after %s seconds', chalk.blue('[WEBPACK]'), chalk.blue((Date.now() - startTime) / 1000)); } results = results.filter(function(result) { return result; }); if(results.length) { return results; } }).finally(function() { keepAliveAfterFinishCallback(finalCallback); }); if (!options.watch) { farmPromise.asCallback(callback); } return farmPromise; }
[ "function", "run", "(", "configPath", ",", "options", ",", "callback", ")", "{", "var", "config", ",", "argvBackup", "=", "process", ".", "argv", ",", "farmOptions", "=", "assign", "(", "{", "}", ",", "options", ")", ";", "options", "=", "options", "||", "{", "}", ";", "if", "(", "options", ".", "colors", "===", "undefined", ")", "{", "options", ".", "colors", "=", "chalk", ".", "supportsColor", ";", "}", "if", "(", "!", "options", ".", "argv", ")", "{", "options", ".", "argv", "=", "[", "]", ";", "}", "options", ".", "argv", ".", "unshift", "(", "process", ".", "execPath", ",", "'parallel-webpack'", ")", ";", "try", "{", "process", ".", "argv", "=", "options", ".", "argv", ";", "config", "=", "loadConfigurationFile", "(", "configPath", ")", ";", "process", ".", "argv", "=", "argvBackup", ";", "}", "catch", "(", "e", ")", "{", "process", ".", "argv", "=", "argvBackup", ";", "return", "Promise", ".", "reject", "(", "new", "Error", "(", "chalk", ".", "red", "(", "'[WEBPACK]'", ")", "+", "' Could not load configuration file '", "+", "chalk", ".", "underline", "(", "configPath", ")", "+", "\"\\n\"", "+", "e", ")", ")", ";", "}", "if", "(", "!", "validate", "(", "farmOptions", ")", ")", "{", "return", "Promise", ".", "reject", "(", "new", "Error", "(", "'Options validation failed:\\n'", "+", "validate", ".", "errors", ".", "map", "(", "function", "(", "error", ")", "{", "return", "'Property: \"options'", "+", "error", ".", "dataPath", "+", "'\" '", "+", "error", ".", "message", ";", "}", ")", ".", "join", "(", "'\\n'", ")", ")", ")", ";", "}", "var", "workers", "=", "workerFarm", "(", "farmOptions", ",", "require", ".", "resolve", "(", "'./src/webpackWorker'", ")", ")", ";", "var", "shutdownCallback", "=", "function", "(", ")", "{", "if", "(", "notSilent", "(", "options", ")", ")", "{", "console", ".", "log", "(", "chalk", ".", "red", "(", "'[WEBPACK]'", ")", "+", "' Forcefully shutting down'", ")", ";", "}", "workerFarm", ".", "end", "(", "workers", ")", ";", "}", ";", "function", "keepAliveAfterFinishCallback", "(", "cb", ")", "{", "if", "(", "options", ".", "keepAliveAfterFinish", ")", "{", "setTimeout", "(", "cb", ",", "options", ".", "keepAliveAfterFinish", ")", ";", "}", "else", "{", "cb", "(", ")", ";", "}", "}", "function", "finalCallback", "(", ")", "{", "workerFarm", ".", "end", "(", "workers", ")", ";", "process", ".", "removeListener", "(", "\"SIGINT\"", ",", "shutdownCallback", ")", ";", "}", "process", ".", "on", "(", "'SIGINT'", ",", "shutdownCallback", ")", ";", "var", "startTime", "=", "Date", ".", "now", "(", ")", ";", "var", "farmPromise", "=", "startFarm", "(", "config", ",", "configPath", ",", "options", ",", "Promise", ".", "promisify", "(", "workers", ")", ",", "callback", ")", ".", "error", "(", "function", "(", "err", ")", "{", "if", "(", "notSilent", "(", "options", ")", ")", "{", "console", ".", "log", "(", "'%s Build failed after %s seconds'", ",", "chalk", ".", "red", "(", "'[WEBPACK]'", ")", ",", "chalk", ".", "blue", "(", "(", "Date", ".", "now", "(", ")", "-", "startTime", ")", "/", "1000", ")", ")", ";", "}", "return", "Promise", ".", "reject", "(", "err", ")", ";", "}", ")", ".", "then", "(", "function", "(", "results", ")", "{", "if", "(", "notSilent", "(", "options", ")", ")", "{", "console", ".", "log", "(", "'%s Finished build after %s seconds'", ",", "chalk", ".", "blue", "(", "'[WEBPACK]'", ")", ",", "chalk", ".", "blue", "(", "(", "Date", ".", "now", "(", ")", "-", "startTime", ")", "/", "1000", ")", ")", ";", "}", "results", "=", "results", ".", "filter", "(", "function", "(", "result", ")", "{", "return", "result", ";", "}", ")", ";", "if", "(", "results", ".", "length", ")", "{", "return", "results", ";", "}", "}", ")", ".", "finally", "(", "function", "(", ")", "{", "keepAliveAfterFinishCallback", "(", "finalCallback", ")", ";", "}", ")", ";", "if", "(", "!", "options", ".", "watch", ")", "{", "farmPromise", ".", "asCallback", "(", "callback", ")", ";", "}", "return", "farmPromise", ";", "}" ]
Runs the specified webpack configuration in parallel. @param {String} configPath The path to the webpack.config.js @param {Object} options @param {Boolean} [options.watch=false] If `true`, Webpack will run in `watch-mode`. @param {Number} [options.maxCallsPerWorker=Infinity] The maximum amount of calls per parallel worker @param {Number} [options.maxConcurrentWorkers=require('os').cpus().length] The maximum number of parallel workers @param {Number} [options.maxConcurrentCallsPerWorker=10] The maximum number of concurrent call per prallel worker @param {Number} [options.maxConcurrentCalls=Infinity] The maximum number of concurrent calls @param {Number} [options.maxRetries=0] The maximum amount of retries on build error @param {Function} [callback] A callback to be invoked once the build has been completed @return {Promise} A Promise that is resolved once all builds have been created
[ "Runs", "the", "specified", "webpack", "configuration", "in", "parallel", "." ]
66da53e44a04795ab8ea705c28f9848ae5e7c7d7
https://github.com/trivago/parallel-webpack/blob/66da53e44a04795ab8ea705c28f9848ae5e7c7d7/index.js#L75-L162
15,209
RafaelVidaurre/angular-permission
src/permission-ui/authorization/StatePermissionMap.js
StatePermissionMap
function StatePermissionMap(state) { var toStateObject = state.$$permissionState(); var toStatePath = toStateObject.path; angular.forEach(toStatePath, function (state) { if (areSetStatePermissions(state)) { var permissionMap = new PermPermissionMap(state.data.permissions); this.extendPermissionMap(permissionMap); } }, this); }
javascript
function StatePermissionMap(state) { var toStateObject = state.$$permissionState(); var toStatePath = toStateObject.path; angular.forEach(toStatePath, function (state) { if (areSetStatePermissions(state)) { var permissionMap = new PermPermissionMap(state.data.permissions); this.extendPermissionMap(permissionMap); } }, this); }
[ "function", "StatePermissionMap", "(", "state", ")", "{", "var", "toStateObject", "=", "state", ".", "$$permissionState", "(", ")", ";", "var", "toStatePath", "=", "toStateObject", ".", "path", ";", "angular", ".", "forEach", "(", "toStatePath", ",", "function", "(", "state", ")", "{", "if", "(", "areSetStatePermissions", "(", "state", ")", ")", "{", "var", "permissionMap", "=", "new", "PermPermissionMap", "(", "state", ".", "data", ".", "permissions", ")", ";", "this", ".", "extendPermissionMap", "(", "permissionMap", ")", ";", "}", "}", ",", "this", ")", ";", "}" ]
Constructs map instructing authorization service how to handle authorizing @constructor permission.ui.PermStatePermissionMap @extends permission.PermPermissionMap
[ "Constructs", "map", "instructing", "authorization", "service", "how", "to", "handle", "authorizing" ]
6c9762060617de02226b8ec14aaa95f434f13638
https://github.com/RafaelVidaurre/angular-permission/blob/6c9762060617de02226b8ec14aaa95f434f13638/src/permission-ui/authorization/StatePermissionMap.js#L22-L32
15,210
RafaelVidaurre/angular-permission
dist/angular-permission-ui.js
handleOnBeforeWebHook
function handleOnBeforeWebHook(transition) { setTransitionProperties(transition); var statePermissionMap = new PermStatePermissionMap(PermTransitionProperties.toState); return PermStateAuthorization .authorizeByPermissionMap(statePermissionMap) .catch(function (rejectedPermission) { return statePermissionMap .resolveRedirectState(rejectedPermission) .then(function (redirect) { return transition.router.stateService.target(redirect.state, redirect.params, redirect.options); }); }); /** * Updates values of `PermTransitionProperties` holder object * @method * @private */ function setTransitionProperties(transition) { PermTransitionProperties.toState = transition.to(); PermTransitionProperties.toParams = transition.params('to'); PermTransitionProperties.fromState = transition.from(); PermTransitionProperties.fromParams = transition.params('from'); PermTransitionProperties.options = transition.options(); } }
javascript
function handleOnBeforeWebHook(transition) { setTransitionProperties(transition); var statePermissionMap = new PermStatePermissionMap(PermTransitionProperties.toState); return PermStateAuthorization .authorizeByPermissionMap(statePermissionMap) .catch(function (rejectedPermission) { return statePermissionMap .resolveRedirectState(rejectedPermission) .then(function (redirect) { return transition.router.stateService.target(redirect.state, redirect.params, redirect.options); }); }); /** * Updates values of `PermTransitionProperties` holder object * @method * @private */ function setTransitionProperties(transition) { PermTransitionProperties.toState = transition.to(); PermTransitionProperties.toParams = transition.params('to'); PermTransitionProperties.fromState = transition.from(); PermTransitionProperties.fromParams = transition.params('from'); PermTransitionProperties.options = transition.options(); } }
[ "function", "handleOnBeforeWebHook", "(", "transition", ")", "{", "setTransitionProperties", "(", "transition", ")", ";", "var", "statePermissionMap", "=", "new", "PermStatePermissionMap", "(", "PermTransitionProperties", ".", "toState", ")", ";", "return", "PermStateAuthorization", ".", "authorizeByPermissionMap", "(", "statePermissionMap", ")", ".", "catch", "(", "function", "(", "rejectedPermission", ")", "{", "return", "statePermissionMap", ".", "resolveRedirectState", "(", "rejectedPermission", ")", ".", "then", "(", "function", "(", "redirect", ")", "{", "return", "transition", ".", "router", ".", "stateService", ".", "target", "(", "redirect", ".", "state", ",", "redirect", ".", "params", ",", "redirect", ".", "options", ")", ";", "}", ")", ";", "}", ")", ";", "/**\n * Updates values of `PermTransitionProperties` holder object\n * @method\n * @private\n */", "function", "setTransitionProperties", "(", "transition", ")", "{", "PermTransitionProperties", ".", "toState", "=", "transition", ".", "to", "(", ")", ";", "PermTransitionProperties", ".", "toParams", "=", "transition", ".", "params", "(", "'to'", ")", ";", "PermTransitionProperties", ".", "fromState", "=", "transition", ".", "from", "(", ")", ";", "PermTransitionProperties", ".", "fromParams", "=", "transition", ".", "params", "(", "'from'", ")", ";", "PermTransitionProperties", ".", "options", "=", "transition", ".", "options", "(", ")", ";", "}", "}" ]
State transition web hook @param transition {Object}
[ "State", "transition", "web", "hook" ]
6c9762060617de02226b8ec14aaa95f434f13638
https://github.com/RafaelVidaurre/angular-permission/blob/6c9762060617de02226b8ec14aaa95f434f13638/dist/angular-permission-ui.js#L74-L100
15,211
RafaelVidaurre/angular-permission
dist/angular-permission-ui.js
handleAuthorizedState
function handleAuthorizedState() { PermTransitionEvents.broadcastPermissionAcceptedEvent(); // Overwrite notify option to broadcast it later var transitionOptions = angular.extend({}, PermTransitionProperties.options, { notify: false, location: true }); $state .go(PermTransitionProperties.toState.name, PermTransitionProperties.toParams, transitionOptions) .then(function () { PermTransitionEvents.broadcastStateChangeSuccessEvent(); }); }
javascript
function handleAuthorizedState() { PermTransitionEvents.broadcastPermissionAcceptedEvent(); // Overwrite notify option to broadcast it later var transitionOptions = angular.extend({}, PermTransitionProperties.options, { notify: false, location: true }); $state .go(PermTransitionProperties.toState.name, PermTransitionProperties.toParams, transitionOptions) .then(function () { PermTransitionEvents.broadcastStateChangeSuccessEvent(); }); }
[ "function", "handleAuthorizedState", "(", ")", "{", "PermTransitionEvents", ".", "broadcastPermissionAcceptedEvent", "(", ")", ";", "// Overwrite notify option to broadcast it later", "var", "transitionOptions", "=", "angular", ".", "extend", "(", "{", "}", ",", "PermTransitionProperties", ".", "options", ",", "{", "notify", ":", "false", ",", "location", ":", "true", "}", ")", ";", "$state", ".", "go", "(", "PermTransitionProperties", ".", "toState", ".", "name", ",", "PermTransitionProperties", ".", "toParams", ",", "transitionOptions", ")", ".", "then", "(", "function", "(", ")", "{", "PermTransitionEvents", ".", "broadcastStateChangeSuccessEvent", "(", ")", ";", "}", ")", ";", "}" ]
Handles redirection for authorized access @method @private
[ "Handles", "redirection", "for", "authorized", "access" ]
6c9762060617de02226b8ec14aaa95f434f13638
https://github.com/RafaelVidaurre/angular-permission/blob/6c9762060617de02226b8ec14aaa95f434f13638/dist/angular-permission-ui.js#L175-L189
15,212
RafaelVidaurre/angular-permission
dist/angular-permission.js
$permission
function $permission() { 'ngInject'; var defaultOnAuthorizedMethod = 'showElement'; var defaultOnUnauthorizedMethod = 'hideElement'; var suppressUndefinedPermissionWarning = false; /** * Methods allowing to alter default directive onAuthorized behaviour in permission directive * @methodOf permission.permissionProvider * * @param onAuthorizedMethod {String} One of permission.PermPermissionStrategies method names */ this.setDefaultOnAuthorizedMethod = function (onAuthorizedMethod) { // jshint ignore:line defaultOnAuthorizedMethod = onAuthorizedMethod; }; /** * Methods allowing to alter default directive onUnauthorized behaviour in permission directive * @methodOf permission.permissionProvider * * @param onUnauthorizedMethod {String} One of permission.PermPermissionStrategies method names */ this.setDefaultOnUnauthorizedMethod = function (onUnauthorizedMethod) { // jshint ignore:line defaultOnUnauthorizedMethod = onUnauthorizedMethod; }; /** * When set to true hides permission warning for undefined roles and permissions * @methodOf permission.permissionProvider * * @param value {Boolean} */ this.suppressUndefinedPermissionWarning = function (value) { // jshint ignore:line suppressUndefinedPermissionWarning = value; }; this.$get = function () { // jshint ignore:line return { defaultOnAuthorizedMethod: defaultOnAuthorizedMethod, defaultOnUnauthorizedMethod: defaultOnUnauthorizedMethod, suppressUndefinedPermissionWarning: suppressUndefinedPermissionWarning }; }; }
javascript
function $permission() { 'ngInject'; var defaultOnAuthorizedMethod = 'showElement'; var defaultOnUnauthorizedMethod = 'hideElement'; var suppressUndefinedPermissionWarning = false; /** * Methods allowing to alter default directive onAuthorized behaviour in permission directive * @methodOf permission.permissionProvider * * @param onAuthorizedMethod {String} One of permission.PermPermissionStrategies method names */ this.setDefaultOnAuthorizedMethod = function (onAuthorizedMethod) { // jshint ignore:line defaultOnAuthorizedMethod = onAuthorizedMethod; }; /** * Methods allowing to alter default directive onUnauthorized behaviour in permission directive * @methodOf permission.permissionProvider * * @param onUnauthorizedMethod {String} One of permission.PermPermissionStrategies method names */ this.setDefaultOnUnauthorizedMethod = function (onUnauthorizedMethod) { // jshint ignore:line defaultOnUnauthorizedMethod = onUnauthorizedMethod; }; /** * When set to true hides permission warning for undefined roles and permissions * @methodOf permission.permissionProvider * * @param value {Boolean} */ this.suppressUndefinedPermissionWarning = function (value) { // jshint ignore:line suppressUndefinedPermissionWarning = value; }; this.$get = function () { // jshint ignore:line return { defaultOnAuthorizedMethod: defaultOnAuthorizedMethod, defaultOnUnauthorizedMethod: defaultOnUnauthorizedMethod, suppressUndefinedPermissionWarning: suppressUndefinedPermissionWarning }; }; }
[ "function", "$permission", "(", ")", "{", "'ngInject'", ";", "var", "defaultOnAuthorizedMethod", "=", "'showElement'", ";", "var", "defaultOnUnauthorizedMethod", "=", "'hideElement'", ";", "var", "suppressUndefinedPermissionWarning", "=", "false", ";", "/**\n * Methods allowing to alter default directive onAuthorized behaviour in permission directive\n * @methodOf permission.permissionProvider\n *\n * @param onAuthorizedMethod {String} One of permission.PermPermissionStrategies method names\n */", "this", ".", "setDefaultOnAuthorizedMethod", "=", "function", "(", "onAuthorizedMethod", ")", "{", "// jshint ignore:line", "defaultOnAuthorizedMethod", "=", "onAuthorizedMethod", ";", "}", ";", "/**\n * Methods allowing to alter default directive onUnauthorized behaviour in permission directive\n * @methodOf permission.permissionProvider\n *\n * @param onUnauthorizedMethod {String} One of permission.PermPermissionStrategies method names\n */", "this", ".", "setDefaultOnUnauthorizedMethod", "=", "function", "(", "onUnauthorizedMethod", ")", "{", "// jshint ignore:line", "defaultOnUnauthorizedMethod", "=", "onUnauthorizedMethod", ";", "}", ";", "/**\n * When set to true hides permission warning for undefined roles and permissions\n * @methodOf permission.permissionProvider\n *\n * @param value {Boolean}\n */", "this", ".", "suppressUndefinedPermissionWarning", "=", "function", "(", "value", ")", "{", "// jshint ignore:line", "suppressUndefinedPermissionWarning", "=", "value", ";", "}", ";", "this", ".", "$get", "=", "function", "(", ")", "{", "// jshint ignore:line", "return", "{", "defaultOnAuthorizedMethod", ":", "defaultOnAuthorizedMethod", ",", "defaultOnUnauthorizedMethod", ":", "defaultOnUnauthorizedMethod", ",", "suppressUndefinedPermissionWarning", ":", "suppressUndefinedPermissionWarning", "}", ";", "}", ";", "}" ]
Permission module configuration provider @name permission.permissionProvider
[ "Permission", "module", "configuration", "provider" ]
6c9762060617de02226b8ec14aaa95f434f13638
https://github.com/RafaelVidaurre/angular-permission/blob/6c9762060617de02226b8ec14aaa95f434f13638/dist/angular-permission.js#L37-L83
15,213
RafaelVidaurre/angular-permission
dist/angular-permission.js
onAuthorizedAccess
function onAuthorizedAccess() { if (angular.isFunction(permission.onAuthorized)) { permission.onAuthorized()($element); } else { var onAuthorizedMethodName = $permission.defaultOnAuthorizedMethod; PermPermissionStrategies[onAuthorizedMethodName]($element); } }
javascript
function onAuthorizedAccess() { if (angular.isFunction(permission.onAuthorized)) { permission.onAuthorized()($element); } else { var onAuthorizedMethodName = $permission.defaultOnAuthorizedMethod; PermPermissionStrategies[onAuthorizedMethodName]($element); } }
[ "function", "onAuthorizedAccess", "(", ")", "{", "if", "(", "angular", ".", "isFunction", "(", "permission", ".", "onAuthorized", ")", ")", "{", "permission", ".", "onAuthorized", "(", ")", "(", "$element", ")", ";", "}", "else", "{", "var", "onAuthorizedMethodName", "=", "$permission", ".", "defaultOnAuthorizedMethod", ";", "PermPermissionStrategies", "[", "onAuthorizedMethodName", "]", "(", "$element", ")", ";", "}", "}" ]
Calls `onAuthorized` function if provided or show element @private
[ "Calls", "onAuthorized", "function", "if", "provided", "or", "show", "element" ]
6c9762060617de02226b8ec14aaa95f434f13638
https://github.com/RafaelVidaurre/angular-permission/blob/6c9762060617de02226b8ec14aaa95f434f13638/dist/angular-permission.js#L816-L823
15,214
RafaelVidaurre/angular-permission
dist/angular-permission.js
onUnauthorizedAccess
function onUnauthorizedAccess() { if (angular.isFunction(permission.onUnauthorized)) { permission.onUnauthorized()($element); } else { var onUnauthorizedMethodName = $permission.defaultOnUnauthorizedMethod; PermPermissionStrategies[onUnauthorizedMethodName]($element); } }
javascript
function onUnauthorizedAccess() { if (angular.isFunction(permission.onUnauthorized)) { permission.onUnauthorized()($element); } else { var onUnauthorizedMethodName = $permission.defaultOnUnauthorizedMethod; PermPermissionStrategies[onUnauthorizedMethodName]($element); } }
[ "function", "onUnauthorizedAccess", "(", ")", "{", "if", "(", "angular", ".", "isFunction", "(", "permission", ".", "onUnauthorized", ")", ")", "{", "permission", ".", "onUnauthorized", "(", ")", "(", "$element", ")", ";", "}", "else", "{", "var", "onUnauthorizedMethodName", "=", "$permission", ".", "defaultOnUnauthorizedMethod", ";", "PermPermissionStrategies", "[", "onUnauthorizedMethodName", "]", "(", "$element", ")", ";", "}", "}" ]
Calls `onUnauthorized` function if provided or hide element @private
[ "Calls", "onUnauthorized", "function", "if", "provided", "or", "hide", "element" ]
6c9762060617de02226b8ec14aaa95f434f13638
https://github.com/RafaelVidaurre/angular-permission/blob/6c9762060617de02226b8ec14aaa95f434f13638/dist/angular-permission.js#L829-L836
15,215
RafaelVidaurre/angular-permission
src/permission-ui/permission-ui.js
handleStateChangeStartEvent
function handleStateChangeStartEvent(event, toState, toParams, fromState, fromParams, options) { if (!isAuthorizationFinished()) { setStateAuthorizationStatus(true); setTransitionProperties(); if (!PermTransitionEvents.areEventsDefaultPrevented()) { PermTransitionEvents.broadcastPermissionStartEvent(); event.preventDefault(); var statePermissionMap = new PermStatePermissionMap(PermTransitionProperties.toState); PermStateAuthorization .authorizeByPermissionMap(statePermissionMap) .then(function () { handleAuthorizedState(); }) .catch(function (rejectedPermission) { handleUnauthorizedState(rejectedPermission, statePermissionMap); }) .finally(function () { setStateAuthorizationStatus(false); }); } else { setStateAuthorizationStatus(false); } } /** * Updates values of `PermTransitionProperties` holder object * @method * @private */ function setTransitionProperties() { PermTransitionProperties.toState = toState; PermTransitionProperties.toParams = toParams; PermTransitionProperties.fromState = fromState; PermTransitionProperties.fromParams = fromParams; PermTransitionProperties.options = options; } /** * Sets internal state `$$finishedAuthorization` variable to prevent looping * @method * @private * * @param status {boolean} When true authorization has been already preceded */ function setStateAuthorizationStatus(status) { angular.extend(toState, {'$$isAuthorizationFinished': status}); } /** * Checks if state has been already checked for authorization * @method * @private * * @returns {boolean} */ function isAuthorizationFinished() { return toState.$$isAuthorizationFinished; } /** * Handles redirection for authorized access * @method * @private */ function handleAuthorizedState() { PermTransitionEvents.broadcastPermissionAcceptedEvent(); // Overwrite notify option to broadcast it later var transitionOptions = angular.extend({}, PermTransitionProperties.options, {notify: false, location: true}); $state .go(PermTransitionProperties.toState.name, PermTransitionProperties.toParams, transitionOptions) .then(function () { PermTransitionEvents.broadcastStateChangeSuccessEvent(); }); } /** * Handles redirection for unauthorized access * @method * @private * * @param rejectedPermission {String} Rejected access right * @param statePermissionMap {permission.ui.PermPermissionMap} State permission map */ function handleUnauthorizedState(rejectedPermission, statePermissionMap) { PermTransitionEvents.broadcastPermissionDeniedEvent(); statePermissionMap .resolveRedirectState(rejectedPermission) .then(function (redirect) { $state.go(redirect.state, redirect.params, redirect.options); }); } }
javascript
function handleStateChangeStartEvent(event, toState, toParams, fromState, fromParams, options) { if (!isAuthorizationFinished()) { setStateAuthorizationStatus(true); setTransitionProperties(); if (!PermTransitionEvents.areEventsDefaultPrevented()) { PermTransitionEvents.broadcastPermissionStartEvent(); event.preventDefault(); var statePermissionMap = new PermStatePermissionMap(PermTransitionProperties.toState); PermStateAuthorization .authorizeByPermissionMap(statePermissionMap) .then(function () { handleAuthorizedState(); }) .catch(function (rejectedPermission) { handleUnauthorizedState(rejectedPermission, statePermissionMap); }) .finally(function () { setStateAuthorizationStatus(false); }); } else { setStateAuthorizationStatus(false); } } /** * Updates values of `PermTransitionProperties` holder object * @method * @private */ function setTransitionProperties() { PermTransitionProperties.toState = toState; PermTransitionProperties.toParams = toParams; PermTransitionProperties.fromState = fromState; PermTransitionProperties.fromParams = fromParams; PermTransitionProperties.options = options; } /** * Sets internal state `$$finishedAuthorization` variable to prevent looping * @method * @private * * @param status {boolean} When true authorization has been already preceded */ function setStateAuthorizationStatus(status) { angular.extend(toState, {'$$isAuthorizationFinished': status}); } /** * Checks if state has been already checked for authorization * @method * @private * * @returns {boolean} */ function isAuthorizationFinished() { return toState.$$isAuthorizationFinished; } /** * Handles redirection for authorized access * @method * @private */ function handleAuthorizedState() { PermTransitionEvents.broadcastPermissionAcceptedEvent(); // Overwrite notify option to broadcast it later var transitionOptions = angular.extend({}, PermTransitionProperties.options, {notify: false, location: true}); $state .go(PermTransitionProperties.toState.name, PermTransitionProperties.toParams, transitionOptions) .then(function () { PermTransitionEvents.broadcastStateChangeSuccessEvent(); }); } /** * Handles redirection for unauthorized access * @method * @private * * @param rejectedPermission {String} Rejected access right * @param statePermissionMap {permission.ui.PermPermissionMap} State permission map */ function handleUnauthorizedState(rejectedPermission, statePermissionMap) { PermTransitionEvents.broadcastPermissionDeniedEvent(); statePermissionMap .resolveRedirectState(rejectedPermission) .then(function (redirect) { $state.go(redirect.state, redirect.params, redirect.options); }); } }
[ "function", "handleStateChangeStartEvent", "(", "event", ",", "toState", ",", "toParams", ",", "fromState", ",", "fromParams", ",", "options", ")", "{", "if", "(", "!", "isAuthorizationFinished", "(", ")", ")", "{", "setStateAuthorizationStatus", "(", "true", ")", ";", "setTransitionProperties", "(", ")", ";", "if", "(", "!", "PermTransitionEvents", ".", "areEventsDefaultPrevented", "(", ")", ")", "{", "PermTransitionEvents", ".", "broadcastPermissionStartEvent", "(", ")", ";", "event", ".", "preventDefault", "(", ")", ";", "var", "statePermissionMap", "=", "new", "PermStatePermissionMap", "(", "PermTransitionProperties", ".", "toState", ")", ";", "PermStateAuthorization", ".", "authorizeByPermissionMap", "(", "statePermissionMap", ")", ".", "then", "(", "function", "(", ")", "{", "handleAuthorizedState", "(", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "rejectedPermission", ")", "{", "handleUnauthorizedState", "(", "rejectedPermission", ",", "statePermissionMap", ")", ";", "}", ")", ".", "finally", "(", "function", "(", ")", "{", "setStateAuthorizationStatus", "(", "false", ")", ";", "}", ")", ";", "}", "else", "{", "setStateAuthorizationStatus", "(", "false", ")", ";", "}", "}", "/**\n * Updates values of `PermTransitionProperties` holder object\n * @method\n * @private\n */", "function", "setTransitionProperties", "(", ")", "{", "PermTransitionProperties", ".", "toState", "=", "toState", ";", "PermTransitionProperties", ".", "toParams", "=", "toParams", ";", "PermTransitionProperties", ".", "fromState", "=", "fromState", ";", "PermTransitionProperties", ".", "fromParams", "=", "fromParams", ";", "PermTransitionProperties", ".", "options", "=", "options", ";", "}", "/**\n * Sets internal state `$$finishedAuthorization` variable to prevent looping\n * @method\n * @private\n *\n * @param status {boolean} When true authorization has been already preceded\n */", "function", "setStateAuthorizationStatus", "(", "status", ")", "{", "angular", ".", "extend", "(", "toState", ",", "{", "'$$isAuthorizationFinished'", ":", "status", "}", ")", ";", "}", "/**\n * Checks if state has been already checked for authorization\n * @method\n * @private\n *\n * @returns {boolean}\n */", "function", "isAuthorizationFinished", "(", ")", "{", "return", "toState", ".", "$$isAuthorizationFinished", ";", "}", "/**\n * Handles redirection for authorized access\n * @method\n * @private\n */", "function", "handleAuthorizedState", "(", ")", "{", "PermTransitionEvents", ".", "broadcastPermissionAcceptedEvent", "(", ")", ";", "// Overwrite notify option to broadcast it later", "var", "transitionOptions", "=", "angular", ".", "extend", "(", "{", "}", ",", "PermTransitionProperties", ".", "options", ",", "{", "notify", ":", "false", ",", "location", ":", "true", "}", ")", ";", "$state", ".", "go", "(", "PermTransitionProperties", ".", "toState", ".", "name", ",", "PermTransitionProperties", ".", "toParams", ",", "transitionOptions", ")", ".", "then", "(", "function", "(", ")", "{", "PermTransitionEvents", ".", "broadcastStateChangeSuccessEvent", "(", ")", ";", "}", ")", ";", "}", "/**\n * Handles redirection for unauthorized access\n * @method\n * @private\n *\n * @param rejectedPermission {String} Rejected access right\n * @param statePermissionMap {permission.ui.PermPermissionMap} State permission map\n */", "function", "handleUnauthorizedState", "(", "rejectedPermission", ",", "statePermissionMap", ")", "{", "PermTransitionEvents", ".", "broadcastPermissionDeniedEvent", "(", ")", ";", "statePermissionMap", ".", "resolveRedirectState", "(", "rejectedPermission", ")", ".", "then", "(", "function", "(", "redirect", ")", "{", "$state", ".", "go", "(", "redirect", ".", "state", ",", "redirect", ".", "params", ",", "redirect", ".", "options", ")", ";", "}", ")", ";", "}", "}" ]
State transition event interceptor
[ "State", "transition", "event", "interceptor" ]
6c9762060617de02226b8ec14aaa95f434f13638
https://github.com/RafaelVidaurre/angular-permission/blob/6c9762060617de02226b8ec14aaa95f434f13638/src/permission-ui/permission-ui.js#L89-L187
15,216
zachleat/BigText
demo/js/modernizr-1.6.js
set_prefixed_value_css
function set_prefixed_value_css(element, property, value, extra) { property += ':'; element.style.cssText = (property + prefixes.join(value + ';' + property)).slice(0, -property.length) + (extra || ''); }
javascript
function set_prefixed_value_css(element, property, value, extra) { property += ':'; element.style.cssText = (property + prefixes.join(value + ';' + property)).slice(0, -property.length) + (extra || ''); }
[ "function", "set_prefixed_value_css", "(", "element", ",", "property", ",", "value", ",", "extra", ")", "{", "property", "+=", "':'", ";", "element", ".", "style", ".", "cssText", "=", "(", "property", "+", "prefixes", ".", "join", "(", "value", "+", "';'", "+", "property", ")", ")", ".", "slice", "(", "0", ",", "-", "property", ".", "length", ")", "+", "(", "extra", "||", "''", ")", ";", "}" ]
set_prefixed_value_css sets the property of a specified element adding vendor prefixes to the VALUE of the property. @param {Element} element @param {string} property The property name. This will not be prefixed. @param {string} value The value of the property. This WILL be prefixed. @param {string=} extra Additional CSS to append unmodified to the end of the CSS string.
[ "set_prefixed_value_css", "sets", "the", "property", "of", "a", "specified", "element", "adding", "vendor", "prefixes", "to", "the", "VALUE", "of", "the", "property", "." ]
4649d726278fe4914e3255084ef92ce48cb14bb2
https://github.com/zachleat/BigText/blob/4649d726278fe4914e3255084ef92ce48cb14bb2/demo/js/modernizr-1.6.js#L243-L246
15,217
zachleat/BigText
demo/js/modernizr-1.6.js
set_prefixed_property_css
function set_prefixed_property_css(element, property, value, extra) { element.style.cssText = prefixes.join(property + ':' + value + ';') + (extra || ''); }
javascript
function set_prefixed_property_css(element, property, value, extra) { element.style.cssText = prefixes.join(property + ':' + value + ';') + (extra || ''); }
[ "function", "set_prefixed_property_css", "(", "element", ",", "property", ",", "value", ",", "extra", ")", "{", "element", ".", "style", ".", "cssText", "=", "prefixes", ".", "join", "(", "property", "+", "':'", "+", "value", "+", "';'", ")", "+", "(", "extra", "||", "''", ")", ";", "}" ]
set_prefixed_property_css sets the property of a specified element adding vendor prefixes to the NAME of the property. @param {Element} element @param {string} property The property name. This WILL be prefixed. @param {string} value The value of the property. This will not be prefixed. @param {string=} extra Additional CSS to append unmodified to the end of the CSS string.
[ "set_prefixed_property_css", "sets", "the", "property", "of", "a", "specified", "element", "adding", "vendor", "prefixes", "to", "the", "NAME", "of", "the", "property", "." ]
4649d726278fe4914e3255084ef92ce48cb14bb2
https://github.com/zachleat/BigText/blob/4649d726278fe4914e3255084ef92ce48cb14bb2/demo/js/modernizr-1.6.js#L257-L259
15,218
zachleat/BigText
demo/js/modernizr-1.6.js
webforms
function webforms(){ // Run through HTML5's new input attributes to see if the UA understands any. // We're using f which is the <input> element created early on // Mike Taylr has created a comprehensive resource for testing these attributes // when applied to all input types: // http://miketaylr.com/code/input-type-attr.html // spec: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary ret['input'] = (function(props) { for (var i = 0,len=props.length;i<len;i++) { attrs[ props[i] ] = !!(props[i] in f); } return attrs; })('autocomplete autofocus list placeholder max min multiple pattern required step'.split(' ')); // Run through HTML5's new input types to see if the UA understands any. // This is put behind the tests runloop because it doesn't return a // true/false like all the other tests; instead, it returns an object // containing each input type with its corresponding true/false value // Big thanks to @miketaylr for the html5 forms expertise. http://miketaylr.com/ ret['inputtypes'] = (function(props) { for (var i = 0, bool, len=props.length ; i < len ; i++) { f.setAttribute('type', props[i]); bool = f.type !== 'text'; // Chrome likes to falsely purport support, so we feed it a textual value; // if that doesnt succeed then we know there's a custom UI if (bool){ f.value = smile; if (/^range$/.test(f.type) && f.style.WebkitAppearance !== undefined){ docElement.appendChild(f); var defaultView = doc.defaultView; // Safari 2-4 allows the smiley as a value, despite making a slider bool = defaultView.getComputedStyle && defaultView.getComputedStyle(f, null).WebkitAppearance !== 'textfield' && // Mobile android web browser has false positive, so must // check the height to see if the widget is actually there. (f.offsetHeight !== 0); docElement.removeChild(f); } else if (/^(search|tel)$/.test(f.type)){ // Spec doesnt define any special parsing or detectable UI // behaviors so we pass these through as true // Interestingly, opera fails the earlier test, so it doesn't // even make it here. } else if (/^(url|email)$/.test(f.type)) { // Real url and email support comes with prebaked validation. bool = f.checkValidity && f.checkValidity() === false; } else { // If the upgraded input compontent rejects the :) text, we got a winner bool = f.value != smile; } } inputs[ props[i] ] = !!bool; } return inputs; })('search tel url email datetime date month week time datetime-local number range color'.split(' ')); }
javascript
function webforms(){ // Run through HTML5's new input attributes to see if the UA understands any. // We're using f which is the <input> element created early on // Mike Taylr has created a comprehensive resource for testing these attributes // when applied to all input types: // http://miketaylr.com/code/input-type-attr.html // spec: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary ret['input'] = (function(props) { for (var i = 0,len=props.length;i<len;i++) { attrs[ props[i] ] = !!(props[i] in f); } return attrs; })('autocomplete autofocus list placeholder max min multiple pattern required step'.split(' ')); // Run through HTML5's new input types to see if the UA understands any. // This is put behind the tests runloop because it doesn't return a // true/false like all the other tests; instead, it returns an object // containing each input type with its corresponding true/false value // Big thanks to @miketaylr for the html5 forms expertise. http://miketaylr.com/ ret['inputtypes'] = (function(props) { for (var i = 0, bool, len=props.length ; i < len ; i++) { f.setAttribute('type', props[i]); bool = f.type !== 'text'; // Chrome likes to falsely purport support, so we feed it a textual value; // if that doesnt succeed then we know there's a custom UI if (bool){ f.value = smile; if (/^range$/.test(f.type) && f.style.WebkitAppearance !== undefined){ docElement.appendChild(f); var defaultView = doc.defaultView; // Safari 2-4 allows the smiley as a value, despite making a slider bool = defaultView.getComputedStyle && defaultView.getComputedStyle(f, null).WebkitAppearance !== 'textfield' && // Mobile android web browser has false positive, so must // check the height to see if the widget is actually there. (f.offsetHeight !== 0); docElement.removeChild(f); } else if (/^(search|tel)$/.test(f.type)){ // Spec doesnt define any special parsing or detectable UI // behaviors so we pass these through as true // Interestingly, opera fails the earlier test, so it doesn't // even make it here. } else if (/^(url|email)$/.test(f.type)) { // Real url and email support comes with prebaked validation. bool = f.checkValidity && f.checkValidity() === false; } else { // If the upgraded input compontent rejects the :) text, we got a winner bool = f.value != smile; } } inputs[ props[i] ] = !!bool; } return inputs; })('search tel url email datetime date month week time datetime-local number range color'.split(' ')); }
[ "function", "webforms", "(", ")", "{", "// Run through HTML5's new input attributes to see if the UA understands any.", "// We're using f which is the <input> element created early on", "// Mike Taylr has created a comprehensive resource for testing these attributes", "// when applied to all input types: ", "// http://miketaylr.com/code/input-type-attr.html", "// spec: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary", "ret", "[", "'input'", "]", "=", "(", "function", "(", "props", ")", "{", "for", "(", "var", "i", "=", "0", ",", "len", "=", "props", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "attrs", "[", "props", "[", "i", "]", "]", "=", "!", "!", "(", "props", "[", "i", "]", "in", "f", ")", ";", "}", "return", "attrs", ";", "}", ")", "(", "'autocomplete autofocus list placeholder max min multiple pattern required step'", ".", "split", "(", "' '", ")", ")", ";", "// Run through HTML5's new input types to see if the UA understands any.", "// This is put behind the tests runloop because it doesn't return a", "// true/false like all the other tests; instead, it returns an object", "// containing each input type with its corresponding true/false value ", "// Big thanks to @miketaylr for the html5 forms expertise. http://miketaylr.com/", "ret", "[", "'inputtypes'", "]", "=", "(", "function", "(", "props", ")", "{", "for", "(", "var", "i", "=", "0", ",", "bool", ",", "len", "=", "props", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "f", ".", "setAttribute", "(", "'type'", ",", "props", "[", "i", "]", ")", ";", "bool", "=", "f", ".", "type", "!==", "'text'", ";", "// Chrome likes to falsely purport support, so we feed it a textual value;", "// if that doesnt succeed then we know there's a custom UI", "if", "(", "bool", ")", "{", "f", ".", "value", "=", "smile", ";", "if", "(", "/", "^range$", "/", ".", "test", "(", "f", ".", "type", ")", "&&", "f", ".", "style", ".", "WebkitAppearance", "!==", "undefined", ")", "{", "docElement", ".", "appendChild", "(", "f", ")", ";", "var", "defaultView", "=", "doc", ".", "defaultView", ";", "// Safari 2-4 allows the smiley as a value, despite making a slider", "bool", "=", "defaultView", ".", "getComputedStyle", "&&", "defaultView", ".", "getComputedStyle", "(", "f", ",", "null", ")", ".", "WebkitAppearance", "!==", "'textfield'", "&&", "// Mobile android web browser has false positive, so must", "// check the height to see if the widget is actually there.", "(", "f", ".", "offsetHeight", "!==", "0", ")", ";", "docElement", ".", "removeChild", "(", "f", ")", ";", "}", "else", "if", "(", "/", "^(search|tel)$", "/", ".", "test", "(", "f", ".", "type", ")", ")", "{", "// Spec doesnt define any special parsing or detectable UI ", "// behaviors so we pass these through as true", "// Interestingly, opera fails the earlier test, so it doesn't", "// even make it here.", "}", "else", "if", "(", "/", "^(url|email)$", "/", ".", "test", "(", "f", ".", "type", ")", ")", "{", "// Real url and email support comes with prebaked validation.", "bool", "=", "f", ".", "checkValidity", "&&", "f", ".", "checkValidity", "(", ")", "===", "false", ";", "}", "else", "{", "// If the upgraded input compontent rejects the :) text, we got a winner", "bool", "=", "f", ".", "value", "!=", "smile", ";", "}", "}", "inputs", "[", "props", "[", "i", "]", "]", "=", "!", "!", "bool", ";", "}", "return", "inputs", ";", "}", ")", "(", "'search tel url email datetime date month week time datetime-local number range color'", ".", "split", "(", "' '", ")", ")", ";", "}" ]
input features and input types go directly onto the ret object, bypassing the tests loop. Hold this guy to execute in a moment.
[ "input", "features", "and", "input", "types", "go", "directly", "onto", "the", "ret", "object", "bypassing", "the", "tests", "loop", ".", "Hold", "this", "guy", "to", "execute", "in", "a", "moment", "." ]
4649d726278fe4914e3255084ef92ce48cb14bb2
https://github.com/zachleat/BigText/blob/4649d726278fe4914e3255084ef92ce48cb14bb2/demo/js/modernizr-1.6.js#L740-L811
15,219
jeffbski/redux-logic
src/createLogicMiddleware.js
mw
function mw(store) { if (savedStore && savedStore !== store) { throw new Error('cannot assign logicMiddleware instance to multiple stores, create separate instance for each'); } savedStore = store; return next => { savedNext = next; const { action$, sub, logicCount: cnt } = applyLogic(arrLogic, savedStore, savedNext, logicSub, actionSrc$, deps, logicCount, monitor$); actionEnd$ = action$; logicSub = sub; logicCount = cnt; return action => { debug('starting off', action); monitor$.next({ action, op: 'top' }); actionSrc$.next(action); return action; }; }; }
javascript
function mw(store) { if (savedStore && savedStore !== store) { throw new Error('cannot assign logicMiddleware instance to multiple stores, create separate instance for each'); } savedStore = store; return next => { savedNext = next; const { action$, sub, logicCount: cnt } = applyLogic(arrLogic, savedStore, savedNext, logicSub, actionSrc$, deps, logicCount, monitor$); actionEnd$ = action$; logicSub = sub; logicCount = cnt; return action => { debug('starting off', action); monitor$.next({ action, op: 'top' }); actionSrc$.next(action); return action; }; }; }
[ "function", "mw", "(", "store", ")", "{", "if", "(", "savedStore", "&&", "savedStore", "!==", "store", ")", "{", "throw", "new", "Error", "(", "'cannot assign logicMiddleware instance to multiple stores, create separate instance for each'", ")", ";", "}", "savedStore", "=", "store", ";", "return", "next", "=>", "{", "savedNext", "=", "next", ";", "const", "{", "action$", ",", "sub", ",", "logicCount", ":", "cnt", "}", "=", "applyLogic", "(", "arrLogic", ",", "savedStore", ",", "savedNext", ",", "logicSub", ",", "actionSrc$", ",", "deps", ",", "logicCount", ",", "monitor$", ")", ";", "actionEnd$", "=", "action$", ";", "logicSub", "=", "sub", ";", "logicCount", "=", "cnt", ";", "return", "action", "=>", "{", "debug", "(", "'starting off'", ",", "action", ")", ";", "monitor$", ".", "next", "(", "{", "action", ",", "op", ":", "'top'", "}", ")", ";", "actionSrc$", ".", "next", "(", "action", ")", ";", "return", "action", ";", "}", ";", "}", ";", "}" ]
keep for uniqueness check
[ "keep", "for", "uniqueness", "check" ]
4b0951af03dbe3097e4bad5710fe274c2f3f1e6b
https://github.com/jeffbski/redux-logic/blob/4b0951af03dbe3097e4bad5710fe274c2f3f1e6b/src/createLogicMiddleware.js#L74-L97
15,220
jeffbski/redux-logic
src/createLogicMiddleware.js
naming
function naming(logic, idx) { if (logic.name) { return logic; } return { ...logic, name: `L(${stringifyType(logic.type)})-${idx}` }; }
javascript
function naming(logic, idx) { if (logic.name) { return logic; } return { ...logic, name: `L(${stringifyType(logic.type)})-${idx}` }; }
[ "function", "naming", "(", "logic", ",", "idx", ")", "{", "if", "(", "logic", ".", "name", ")", "{", "return", "logic", ";", "}", "return", "{", "...", "logic", ",", "name", ":", "`", "${", "stringifyType", "(", "logic", ".", "type", ")", "}", "${", "idx", "}", "`", "}", ";", "}" ]
Implement default names for logic using type and idx @param {object} logic named or unnamed logic object @param {number} idx index in the logic array @return {object} namedLogic named logic
[ "Implement", "default", "names", "for", "logic", "using", "type", "and", "idx" ]
4b0951af03dbe3097e4bad5710fe274c2f3f1e6b
https://github.com/jeffbski/redux-logic/blob/4b0951af03dbe3097e4bad5710fe274c2f3f1e6b/src/createLogicMiddleware.js#L244-L250
15,221
jeffbski/redux-logic
src/createLogicMiddleware.js
findDuplicates
function findDuplicates(arrLogic) { return arrLogic.reduce((acc, x1, idx1) => { if (arrLogic.some((x2, idx2) => (idx1 !== idx2 && x1 === x2))) { acc.push(idx1); } return acc; }, []); }
javascript
function findDuplicates(arrLogic) { return arrLogic.reduce((acc, x1, idx1) => { if (arrLogic.some((x2, idx2) => (idx1 !== idx2 && x1 === x2))) { acc.push(idx1); } return acc; }, []); }
[ "function", "findDuplicates", "(", "arrLogic", ")", "{", "return", "arrLogic", ".", "reduce", "(", "(", "acc", ",", "x1", ",", "idx1", ")", "=>", "{", "if", "(", "arrLogic", ".", "some", "(", "(", "x2", ",", "idx2", ")", "=>", "(", "idx1", "!==", "idx2", "&&", "x1", "===", "x2", ")", ")", ")", "{", "acc", ".", "push", "(", "idx1", ")", ";", "}", "return", "acc", ";", "}", ",", "[", "]", ")", ";", "}" ]
Find duplicates in arrLogic by checking if ref to same logic object @param {array} arrLogic array of logic to check @return {array} array of indexes to duplicates, empty array if none
[ "Find", "duplicates", "in", "arrLogic", "by", "checking", "if", "ref", "to", "same", "logic", "object" ]
4b0951af03dbe3097e4bad5710fe274c2f3f1e6b
https://github.com/jeffbski/redux-logic/blob/4b0951af03dbe3097e4bad5710fe274c2f3f1e6b/src/createLogicMiddleware.js#L257-L264
15,222
jeffbski/redux-logic
examples/async-await-proc-options/scripts/start.js
formatMessage
function formatMessage(message) { return message // Make some common errors shorter: .replace( // Babel syntax error 'Module build failed: SyntaxError:', friendlySyntaxErrorLabel ) .replace( // Webpack file not found error /Module not found: Error: Cannot resolve 'file' or 'directory'/, 'Module not found:' ) // Internal stacks are generally useless so we strip them .replace(/^\s*at\s.*:\d+:\d+[\s\)]*\n/gm, '') // at ... ...:x:y // Webpack loader names obscure CSS filenames .replace('./~/css-loader!./~/postcss-loader!', ''); }
javascript
function formatMessage(message) { return message // Make some common errors shorter: .replace( // Babel syntax error 'Module build failed: SyntaxError:', friendlySyntaxErrorLabel ) .replace( // Webpack file not found error /Module not found: Error: Cannot resolve 'file' or 'directory'/, 'Module not found:' ) // Internal stacks are generally useless so we strip them .replace(/^\s*at\s.*:\d+:\d+[\s\)]*\n/gm, '') // at ... ...:x:y // Webpack loader names obscure CSS filenames .replace('./~/css-loader!./~/postcss-loader!', ''); }
[ "function", "formatMessage", "(", "message", ")", "{", "return", "message", "// Make some common errors shorter:", ".", "replace", "(", "// Babel syntax error", "'Module build failed: SyntaxError:'", ",", "friendlySyntaxErrorLabel", ")", ".", "replace", "(", "// Webpack file not found error", "/", "Module not found: Error: Cannot resolve 'file' or 'directory'", "/", ",", "'Module not found:'", ")", "// Internal stacks are generally useless so we strip them", ".", "replace", "(", "/", "^\\s*at\\s.*:\\d+:\\d+[\\s\\)]*\\n", "/", "gm", ",", "''", ")", "// at ... ...:x:y", "// Webpack loader names obscure CSS filenames", ".", "replace", "(", "'./~/css-loader!./~/postcss-loader!'", ",", "''", ")", ";", "}" ]
This is a little hacky. It would be easier if webpack provided a rich error object.
[ "This", "is", "a", "little", "hacky", ".", "It", "would", "be", "easier", "if", "webpack", "provided", "a", "rich", "error", "object", "." ]
4b0951af03dbe3097e4bad5710fe274c2f3f1e6b
https://github.com/jeffbski/redux-logic/blob/4b0951af03dbe3097e4bad5710fe274c2f3f1e6b/examples/async-await-proc-options/scripts/start.js#L40-L57
15,223
formio/ngFormBuilder
src/components/select.js
function(components) { var fields = []; FormioUtils.eachComponent(components, function(component) { if (component.key && component.input && (component.type !== 'button') && component.key !== $scope.component.key) { var comp = _clone(component); if (!comp.label) { comp.label = comp.key; } fields.push(comp); } }); return fields; }
javascript
function(components) { var fields = []; FormioUtils.eachComponent(components, function(component) { if (component.key && component.input && (component.type !== 'button') && component.key !== $scope.component.key) { var comp = _clone(component); if (!comp.label) { comp.label = comp.key; } fields.push(comp); } }); return fields; }
[ "function", "(", "components", ")", "{", "var", "fields", "=", "[", "]", ";", "FormioUtils", ".", "eachComponent", "(", "components", ",", "function", "(", "component", ")", "{", "if", "(", "component", ".", "key", "&&", "component", ".", "input", "&&", "(", "component", ".", "type", "!==", "'button'", ")", "&&", "component", ".", "key", "!==", "$scope", ".", "component", ".", "key", ")", "{", "var", "comp", "=", "_clone", "(", "component", ")", ";", "if", "(", "!", "comp", ".", "label", ")", "{", "comp", ".", "label", "=", "comp", ".", "key", ";", "}", "fields", ".", "push", "(", "comp", ")", ";", "}", "}", ")", ";", "return", "fields", ";", "}" ]
Returns only input fields we are interested in.
[ "Returns", "only", "input", "fields", "we", "are", "interested", "in", "." ]
ba4de78ace60898e1ce25dd9a0d12d8b31f35ce8
https://github.com/formio/ngFormBuilder/blob/ba4de78ace60898e1ce25dd9a0d12d8b31f35ce8/src/components/select.js#L46-L58
15,224
formio/ngFormBuilder
src/components/select.js
function() { if (!$scope.component.data.resource || ($scope.resources.length === 0)) { return; } var selected = null; $scope.resourceFields = [ { property: '', title: '{Entire Object}' }, { property: '_id', title: 'Submission Id' } ]; if ($scope.formio.projectId) { $scope.component.data.project = $scope.formio.projectId; } for (var index in $scope.resources) { if ($scope.resources[index]._id.toString() === $scope.component.data.resource) { selected = $scope.resources[index]; break; } } if (selected) { var fields = getInputFields(selected.components); for (var i in fields) { var field = fields[i]; var title = field.label || field.key; $scope.resourceFields.push({ property: 'data.' + field.key, title: title }); } if (!$scope.component.valueProperty && $scope.resourceFields.length) { $scope.component.valueProperty = $scope.resourceFields[0].property; } } }
javascript
function() { if (!$scope.component.data.resource || ($scope.resources.length === 0)) { return; } var selected = null; $scope.resourceFields = [ { property: '', title: '{Entire Object}' }, { property: '_id', title: 'Submission Id' } ]; if ($scope.formio.projectId) { $scope.component.data.project = $scope.formio.projectId; } for (var index in $scope.resources) { if ($scope.resources[index]._id.toString() === $scope.component.data.resource) { selected = $scope.resources[index]; break; } } if (selected) { var fields = getInputFields(selected.components); for (var i in fields) { var field = fields[i]; var title = field.label || field.key; $scope.resourceFields.push({ property: 'data.' + field.key, title: title }); } if (!$scope.component.valueProperty && $scope.resourceFields.length) { $scope.component.valueProperty = $scope.resourceFields[0].property; } } }
[ "function", "(", ")", "{", "if", "(", "!", "$scope", ".", "component", ".", "data", ".", "resource", "||", "(", "$scope", ".", "resources", ".", "length", "===", "0", ")", ")", "{", "return", ";", "}", "var", "selected", "=", "null", ";", "$scope", ".", "resourceFields", "=", "[", "{", "property", ":", "''", ",", "title", ":", "'{Entire Object}'", "}", ",", "{", "property", ":", "'_id'", ",", "title", ":", "'Submission Id'", "}", "]", ";", "if", "(", "$scope", ".", "formio", ".", "projectId", ")", "{", "$scope", ".", "component", ".", "data", ".", "project", "=", "$scope", ".", "formio", ".", "projectId", ";", "}", "for", "(", "var", "index", "in", "$scope", ".", "resources", ")", "{", "if", "(", "$scope", ".", "resources", "[", "index", "]", ".", "_id", ".", "toString", "(", ")", "===", "$scope", ".", "component", ".", "data", ".", "resource", ")", "{", "selected", "=", "$scope", ".", "resources", "[", "index", "]", ";", "break", ";", "}", "}", "if", "(", "selected", ")", "{", "var", "fields", "=", "getInputFields", "(", "selected", ".", "components", ")", ";", "for", "(", "var", "i", "in", "fields", ")", "{", "var", "field", "=", "fields", "[", "i", "]", ";", "var", "title", "=", "field", ".", "label", "||", "field", ".", "key", ";", "$scope", ".", "resourceFields", ".", "push", "(", "{", "property", ":", "'data.'", "+", "field", ".", "key", ",", "title", ":", "title", "}", ")", ";", "}", "if", "(", "!", "$scope", ".", "component", ".", "valueProperty", "&&", "$scope", ".", "resourceFields", ".", "length", ")", "{", "$scope", ".", "component", ".", "valueProperty", "=", "$scope", ".", "resourceFields", "[", "0", "]", ".", "property", ";", "}", "}", "}" ]
Loads the selected fields.
[ "Loads", "the", "selected", "fields", "." ]
ba4de78ace60898e1ce25dd9a0d12d8b31f35ce8
https://github.com/formio/ngFormBuilder/blob/ba4de78ace60898e1ce25dd9a0d12d8b31f35ce8/src/components/select.js#L63-L101
15,225
formio/ngFormBuilder
src/ngFormBuilder.js
function() { jQuery(dropZone).removeClass('enabled'); dropZone.removeEventListener('dragover', dragOver, false); dropZone.removeEventListener('drop', dragDrop, false); }
javascript
function() { jQuery(dropZone).removeClass('enabled'); dropZone.removeEventListener('dragover', dragOver, false); dropZone.removeEventListener('drop', dragDrop, false); }
[ "function", "(", ")", "{", "jQuery", "(", "dropZone", ")", ".", "removeClass", "(", "'enabled'", ")", ";", "dropZone", ".", "removeEventListener", "(", "'dragover'", ",", "dragOver", ",", "false", ")", ";", "dropZone", ".", "removeEventListener", "(", "'drop'", ",", "dragDrop", ",", "false", ")", ";", "}" ]
Drag end event handler.
[ "Drag", "end", "event", "handler", "." ]
ba4de78ace60898e1ce25dd9a0d12d8b31f35ce8
https://github.com/formio/ngFormBuilder/blob/ba4de78ace60898e1ce25dd9a0d12d8b31f35ce8/src/ngFormBuilder.js#L43-L47
15,226
formio/ngFormBuilder
src/ngFormBuilder.js
function(event) { if (event.preventDefault) { event.preventDefault(); } if (event.stopPropagation) { event.stopPropagation(); } var dropOffset = jQuery(dropZone).offset(); var dragData = angular.copy(scope.formBuilderDraggable); dragData.fbDropX = event.pageX - dropOffset.left; dragData.fbDropY = event.pageY - dropOffset.top; angular.element(dropZone).scope().$emit('fbDragDrop', dragData); dragEnd(); return false; }
javascript
function(event) { if (event.preventDefault) { event.preventDefault(); } if (event.stopPropagation) { event.stopPropagation(); } var dropOffset = jQuery(dropZone).offset(); var dragData = angular.copy(scope.formBuilderDraggable); dragData.fbDropX = event.pageX - dropOffset.left; dragData.fbDropY = event.pageY - dropOffset.top; angular.element(dropZone).scope().$emit('fbDragDrop', dragData); dragEnd(); return false; }
[ "function", "(", "event", ")", "{", "if", "(", "event", ".", "preventDefault", ")", "{", "event", ".", "preventDefault", "(", ")", ";", "}", "if", "(", "event", ".", "stopPropagation", ")", "{", "event", ".", "stopPropagation", "(", ")", ";", "}", "var", "dropOffset", "=", "jQuery", "(", "dropZone", ")", ".", "offset", "(", ")", ";", "var", "dragData", "=", "angular", ".", "copy", "(", "scope", ".", "formBuilderDraggable", ")", ";", "dragData", ".", "fbDropX", "=", "event", ".", "pageX", "-", "dropOffset", ".", "left", ";", "dragData", ".", "fbDropY", "=", "event", ".", "pageY", "-", "dropOffset", ".", "top", ";", "angular", ".", "element", "(", "dropZone", ")", ".", "scope", "(", ")", ".", "$emit", "(", "'fbDragDrop'", ",", "dragData", ")", ";", "dragEnd", "(", ")", ";", "return", "false", ";", "}" ]
Drag drop event handler.
[ "Drag", "drop", "event", "handler", "." ]
ba4de78ace60898e1ce25dd9a0d12d8b31f35ce8
https://github.com/formio/ngFormBuilder/blob/ba4de78ace60898e1ce25dd9a0d12d8b31f35ce8/src/ngFormBuilder.js#L50-L64
15,227
formio/ngFormBuilder
src/factories/BuilderUtils.js
function(components, input) { // Prebuild a list of existing components. var existingComponents = {}; FormioUtils.eachComponent(components, function(component) { // If theres no key, we cant compare components. if (!component.key) return; // A component is pre-existing if the key is unique, or the key is a duplicate and its not flagged as the new component. if ( (component.key !== input.key) || ((component.key === input.key) && (!!component.isNew !== !!input.isNew)) ) { existingComponents[component.key] = component; } }, true); return existingComponents; }
javascript
function(components, input) { // Prebuild a list of existing components. var existingComponents = {}; FormioUtils.eachComponent(components, function(component) { // If theres no key, we cant compare components. if (!component.key) return; // A component is pre-existing if the key is unique, or the key is a duplicate and its not flagged as the new component. if ( (component.key !== input.key) || ((component.key === input.key) && (!!component.isNew !== !!input.isNew)) ) { existingComponents[component.key] = component; } }, true); return existingComponents; }
[ "function", "(", "components", ",", "input", ")", "{", "// Prebuild a list of existing components.", "var", "existingComponents", "=", "{", "}", ";", "FormioUtils", ".", "eachComponent", "(", "components", ",", "function", "(", "component", ")", "{", "// If theres no key, we cant compare components.", "if", "(", "!", "component", ".", "key", ")", "return", ";", "// A component is pre-existing if the key is unique, or the key is a duplicate and its not flagged as the new component.", "if", "(", "(", "component", ".", "key", "!==", "input", ".", "key", ")", "||", "(", "(", "component", ".", "key", "===", "input", ".", "key", ")", "&&", "(", "!", "!", "component", ".", "isNew", "!==", "!", "!", "input", ".", "isNew", ")", ")", ")", "{", "existingComponents", "[", "component", ".", "key", "]", "=", "component", ";", "}", "}", ",", "true", ")", ";", "return", "existingComponents", ";", "}" ]
Memoize the given form components in a map, using the component keys. @param {Array} components An array of the form components. @param {Object} input The input component we're trying to uniquify. @returns {Object} The memoized form components.
[ "Memoize", "the", "given", "form", "components", "in", "a", "map", "using", "the", "component", "keys", "." ]
ba4de78ace60898e1ce25dd9a0d12d8b31f35ce8
https://github.com/formio/ngFormBuilder/blob/ba4de78ace60898e1ce25dd9a0d12d8b31f35ce8/src/factories/BuilderUtils.js#L20-L37
15,228
formio/ngFormBuilder
src/factories/BuilderUtils.js
function(key) { if (!key.match(suffixRegex)) { return key + '2'; } return key.replace(suffixRegex, function(suffix) { return Number(suffix) + 1; }); }
javascript
function(key) { if (!key.match(suffixRegex)) { return key + '2'; } return key.replace(suffixRegex, function(suffix) { return Number(suffix) + 1; }); }
[ "function", "(", "key", ")", "{", "if", "(", "!", "key", ".", "match", "(", "suffixRegex", ")", ")", "{", "return", "key", "+", "'2'", ";", "}", "return", "key", ".", "replace", "(", "suffixRegex", ",", "function", "(", "suffix", ")", "{", "return", "Number", "(", "suffix", ")", "+", "1", ";", "}", ")", ";", "}" ]
Iterate the given key to make it unique. @param {String} key Modify the component key to be unique. @returns {String} The new component key.
[ "Iterate", "the", "given", "key", "to", "make", "it", "unique", "." ]
ba4de78ace60898e1ce25dd9a0d12d8b31f35ce8
https://github.com/formio/ngFormBuilder/blob/ba4de78ace60898e1ce25dd9a0d12d8b31f35ce8/src/factories/BuilderUtils.js#L66-L74
15,229
formio/ngFormBuilder
src/factories/BuilderUtils.js
function(form, component) { var isNew = component.isNew || false; // Recurse into all child components. FormioUtils.eachComponent([component], function(component) { // Force the component isNew to be the same as the parent. component.isNew = isNew; // Skip key uniquification if this component doesn't have a key. if (!component.key) { return; } var memoization = findExistingComponents(form.components, component); while (keyExists(memoization, component.key)) { component.key = iterateKey(component.key); } }, true); return component; }
javascript
function(form, component) { var isNew = component.isNew || false; // Recurse into all child components. FormioUtils.eachComponent([component], function(component) { // Force the component isNew to be the same as the parent. component.isNew = isNew; // Skip key uniquification if this component doesn't have a key. if (!component.key) { return; } var memoization = findExistingComponents(form.components, component); while (keyExists(memoization, component.key)) { component.key = iterateKey(component.key); } }, true); return component; }
[ "function", "(", "form", ",", "component", ")", "{", "var", "isNew", "=", "component", ".", "isNew", "||", "false", ";", "// Recurse into all child components.", "FormioUtils", ".", "eachComponent", "(", "[", "component", "]", ",", "function", "(", "component", ")", "{", "// Force the component isNew to be the same as the parent.", "component", ".", "isNew", "=", "isNew", ";", "// Skip key uniquification if this component doesn't have a key.", "if", "(", "!", "component", ".", "key", ")", "{", "return", ";", "}", "var", "memoization", "=", "findExistingComponents", "(", "form", ".", "components", ",", "component", ")", ";", "while", "(", "keyExists", "(", "memoization", ",", "component", ".", "key", ")", ")", "{", "component", ".", "key", "=", "iterateKey", "(", "component", ".", "key", ")", ";", "}", "}", ",", "true", ")", ";", "return", "component", ";", "}" ]
Appends a number to a component.key to keep it unique @param {Object} form The components parent form. @param {Object} component The component to uniquify
[ "Appends", "a", "number", "to", "a", "component", ".", "key", "to", "keep", "it", "unique" ]
ba4de78ace60898e1ce25dd9a0d12d8b31f35ce8
https://github.com/formio/ngFormBuilder/blob/ba4de78ace60898e1ce25dd9a0d12d8b31f35ce8/src/factories/BuilderUtils.js#L84-L104
15,230
particle-iot/particle-cli
src/cmd/udev.js
systemSupportsUdev
function systemSupportsUdev() { if (_systemSupportsUdev === undefined) { try { _systemSupportsUdev = fs.existsSync(UDEV_RULES_SYSTEM_PATH); } catch (e) { _systemSupportsUdev = false; } } return _systemSupportsUdev; }
javascript
function systemSupportsUdev() { if (_systemSupportsUdev === undefined) { try { _systemSupportsUdev = fs.existsSync(UDEV_RULES_SYSTEM_PATH); } catch (e) { _systemSupportsUdev = false; } } return _systemSupportsUdev; }
[ "function", "systemSupportsUdev", "(", ")", "{", "if", "(", "_systemSupportsUdev", "===", "undefined", ")", "{", "try", "{", "_systemSupportsUdev", "=", "fs", ".", "existsSync", "(", "UDEV_RULES_SYSTEM_PATH", ")", ";", "}", "catch", "(", "e", ")", "{", "_systemSupportsUdev", "=", "false", ";", "}", "}", "return", "_systemSupportsUdev", ";", "}" ]
Check if the system uses udev. @return {Boolean}
[ "Check", "if", "the", "system", "uses", "udev", "." ]
50143bb34835f200b83b7eaf77cb8ab847f05a13
https://github.com/particle-iot/particle-cli/blob/50143bb34835f200b83b7eaf77cb8ab847f05a13/src/cmd/udev.js#L23-L32
15,231
particle-iot/particle-cli
src/cmd/udev.js
udevRulesInstalled
function udevRulesInstalled() { if (_udevRulesInstalled !== undefined) { return _udevRulesInstalled; } if (!systemSupportsUdev()) { _udevRulesInstalled = false; return false; } // Try to load the installed rules file let current = null; try { current = fs.readFileSync(UDEV_RULES_SYSTEM_FILE); } catch (e) { _udevRulesInstalled = false; return false; } // Compare the installed file with the file bundled with this app const latest = fs.readFileSync(UDEV_RULES_ASSET_FILE); _udevRulesInstalled = current.equals(latest); return _udevRulesInstalled; }
javascript
function udevRulesInstalled() { if (_udevRulesInstalled !== undefined) { return _udevRulesInstalled; } if (!systemSupportsUdev()) { _udevRulesInstalled = false; return false; } // Try to load the installed rules file let current = null; try { current = fs.readFileSync(UDEV_RULES_SYSTEM_FILE); } catch (e) { _udevRulesInstalled = false; return false; } // Compare the installed file with the file bundled with this app const latest = fs.readFileSync(UDEV_RULES_ASSET_FILE); _udevRulesInstalled = current.equals(latest); return _udevRulesInstalled; }
[ "function", "udevRulesInstalled", "(", ")", "{", "if", "(", "_udevRulesInstalled", "!==", "undefined", ")", "{", "return", "_udevRulesInstalled", ";", "}", "if", "(", "!", "systemSupportsUdev", "(", ")", ")", "{", "_udevRulesInstalled", "=", "false", ";", "return", "false", ";", "}", "// Try to load the installed rules file", "let", "current", "=", "null", ";", "try", "{", "current", "=", "fs", ".", "readFileSync", "(", "UDEV_RULES_SYSTEM_FILE", ")", ";", "}", "catch", "(", "e", ")", "{", "_udevRulesInstalled", "=", "false", ";", "return", "false", ";", "}", "// Compare the installed file with the file bundled with this app", "const", "latest", "=", "fs", ".", "readFileSync", "(", "UDEV_RULES_ASSET_FILE", ")", ";", "_udevRulesInstalled", "=", "current", ".", "equals", "(", "latest", ")", ";", "return", "_udevRulesInstalled", ";", "}" ]
Check if the system has the latest udev rules installed. @return {Boolean}
[ "Check", "if", "the", "system", "has", "the", "latest", "udev", "rules", "installed", "." ]
50143bb34835f200b83b7eaf77cb8ab847f05a13
https://github.com/particle-iot/particle-cli/blob/50143bb34835f200b83b7eaf77cb8ab847f05a13/src/cmd/udev.js#L39-L59
15,232
particle-iot/particle-cli
src/cmd/udev.js
installUdevRules
function installUdevRules() { if (!systemSupportsUdev()) { return when.reject(new Error('Not supported')); } return when.promise((resolve, reject) => { const cmd = `sudo cp "${UDEV_RULES_ASSET_FILE}" "${UDEV_RULES_SYSTEM_FILE}"`; console.log(cmd); childProcess.exec(cmd, err => { if (err) { _udevRulesInstalled = undefined; return reject(new VError(err, 'Could not install udev rules')); } _udevRulesInstalled = true; resolve(); }); }); }
javascript
function installUdevRules() { if (!systemSupportsUdev()) { return when.reject(new Error('Not supported')); } return when.promise((resolve, reject) => { const cmd = `sudo cp "${UDEV_RULES_ASSET_FILE}" "${UDEV_RULES_SYSTEM_FILE}"`; console.log(cmd); childProcess.exec(cmd, err => { if (err) { _udevRulesInstalled = undefined; return reject(new VError(err, 'Could not install udev rules')); } _udevRulesInstalled = true; resolve(); }); }); }
[ "function", "installUdevRules", "(", ")", "{", "if", "(", "!", "systemSupportsUdev", "(", ")", ")", "{", "return", "when", ".", "reject", "(", "new", "Error", "(", "'Not supported'", ")", ")", ";", "}", "return", "when", ".", "promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "cmd", "=", "`", "${", "UDEV_RULES_ASSET_FILE", "}", "${", "UDEV_RULES_SYSTEM_FILE", "}", "`", ";", "console", ".", "log", "(", "cmd", ")", ";", "childProcess", ".", "exec", "(", "cmd", ",", "err", "=>", "{", "if", "(", "err", ")", "{", "_udevRulesInstalled", "=", "undefined", ";", "return", "reject", "(", "new", "VError", "(", "err", ",", "'Could not install udev rules'", ")", ")", ";", "}", "_udevRulesInstalled", "=", "true", ";", "resolve", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Install the udev rules. @return {Promise}
[ "Install", "the", "udev", "rules", "." ]
50143bb34835f200b83b7eaf77cb8ab847f05a13
https://github.com/particle-iot/particle-cli/blob/50143bb34835f200b83b7eaf77cb8ab847f05a13/src/cmd/udev.js#L66-L82
15,233
particle-iot/particle-cli
src/cmd/udev.js
promptAndInstallUdevRules
function promptAndInstallUdevRules(err = null) { if (!systemSupportsUdev()) { return when.reject(new Error('Not supported')); } if (udevRulesInstalled()) { if (err) { console.log(chalk.bold.red('Physically unplug and reconnect your Particle devices and try again.')); return when.reject(err); } return when.resolve(); } console.log(chalk.yellow('You are missing the permissions to access USB devices without root.')); return prompt({ type: 'confirm', name: 'install', message: 'Would you like to install a udev rules file to get access?', default: true }) .then(r => { if (!r.install) { if (err) { throw err; } throw new Error('Cancelled'); } return installUdevRules(); }) .then(() => { console.log('udev rules installed.'); if (err) { console.log(chalk.bold.red('Physically unplug and reconnect your Particle devices and try again.')); throw err; } }); }
javascript
function promptAndInstallUdevRules(err = null) { if (!systemSupportsUdev()) { return when.reject(new Error('Not supported')); } if (udevRulesInstalled()) { if (err) { console.log(chalk.bold.red('Physically unplug and reconnect your Particle devices and try again.')); return when.reject(err); } return when.resolve(); } console.log(chalk.yellow('You are missing the permissions to access USB devices without root.')); return prompt({ type: 'confirm', name: 'install', message: 'Would you like to install a udev rules file to get access?', default: true }) .then(r => { if (!r.install) { if (err) { throw err; } throw new Error('Cancelled'); } return installUdevRules(); }) .then(() => { console.log('udev rules installed.'); if (err) { console.log(chalk.bold.red('Physically unplug and reconnect your Particle devices and try again.')); throw err; } }); }
[ "function", "promptAndInstallUdevRules", "(", "err", "=", "null", ")", "{", "if", "(", "!", "systemSupportsUdev", "(", ")", ")", "{", "return", "when", ".", "reject", "(", "new", "Error", "(", "'Not supported'", ")", ")", ";", "}", "if", "(", "udevRulesInstalled", "(", ")", ")", "{", "if", "(", "err", ")", "{", "console", ".", "log", "(", "chalk", ".", "bold", ".", "red", "(", "'Physically unplug and reconnect your Particle devices and try again.'", ")", ")", ";", "return", "when", ".", "reject", "(", "err", ")", ";", "}", "return", "when", ".", "resolve", "(", ")", ";", "}", "console", ".", "log", "(", "chalk", ".", "yellow", "(", "'You are missing the permissions to access USB devices without root.'", ")", ")", ";", "return", "prompt", "(", "{", "type", ":", "'confirm'", ",", "name", ":", "'install'", ",", "message", ":", "'Would you like to install a udev rules file to get access?'", ",", "default", ":", "true", "}", ")", ".", "then", "(", "r", "=>", "{", "if", "(", "!", "r", ".", "install", ")", "{", "if", "(", "err", ")", "{", "throw", "err", ";", "}", "throw", "new", "Error", "(", "'Cancelled'", ")", ";", "}", "return", "installUdevRules", "(", ")", ";", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "console", ".", "log", "(", "'udev rules installed.'", ")", ";", "if", "(", "err", ")", "{", "console", ".", "log", "(", "chalk", ".", "bold", ".", "red", "(", "'Physically unplug and reconnect your Particle devices and try again.'", ")", ")", ";", "throw", "err", ";", "}", "}", ")", ";", "}" ]
Prompts the user to install the udev rules. @param {Error} [err] Original error that led to this prompt. @return {Promise}
[ "Prompts", "the", "user", "to", "install", "the", "udev", "rules", "." ]
50143bb34835f200b83b7eaf77cb8ab847f05a13
https://github.com/particle-iot/particle-cli/blob/50143bb34835f200b83b7eaf77cb8ab847f05a13/src/cmd/udev.js#L90-L124
15,234
particle-iot/particle-cli
settings.js
matchKey
function matchKey(needle, obj, caseInsensitive) { needle = (caseInsensitive) ? needle.toLowerCase() : needle; for (let key in obj) { let keyCopy = (caseInsensitive) ? key.toLowerCase() : key; if (keyCopy === needle) { //return the original return key; } } return null; }
javascript
function matchKey(needle, obj, caseInsensitive) { needle = (caseInsensitive) ? needle.toLowerCase() : needle; for (let key in obj) { let keyCopy = (caseInsensitive) ? key.toLowerCase() : key; if (keyCopy === needle) { //return the original return key; } } return null; }
[ "function", "matchKey", "(", "needle", ",", "obj", ",", "caseInsensitive", ")", "{", "needle", "=", "(", "caseInsensitive", ")", "?", "needle", ".", "toLowerCase", "(", ")", ":", "needle", ";", "for", "(", "let", "key", "in", "obj", ")", "{", "let", "keyCopy", "=", "(", "caseInsensitive", ")", "?", "key", ".", "toLowerCase", "(", ")", ":", "key", ";", "if", "(", "keyCopy", "===", "needle", ")", "{", "//return the original", "return", "key", ";", "}", "}", "return", "null", ";", "}" ]
this is here instead of utilities to prevent a require-loop when files that utilties requires need settings
[ "this", "is", "here", "instead", "of", "utilities", "to", "prevent", "a", "require", "-", "loop", "when", "files", "that", "utilties", "requires", "need", "settings" ]
50143bb34835f200b83b7eaf77cb8ab847f05a13
https://github.com/particle-iot/particle-cli/blob/50143bb34835f200b83b7eaf77cb8ab847f05a13/settings.js#L208-L220
15,235
particle-iot/particle-cli
src/cmd/usb-util.js
openUsbDevice
function openUsbDevice(usbDevice, { dfuMode = false } = {}) { if (!dfuMode && usbDevice.isInDfuMode) { return when.reject(new Error('The device should not be in DFU mode')); } return when.resolve().then(() => usbDevice.open()) .catch(e => handleDeviceOpenError(e)); }
javascript
function openUsbDevice(usbDevice, { dfuMode = false } = {}) { if (!dfuMode && usbDevice.isInDfuMode) { return when.reject(new Error('The device should not be in DFU mode')); } return when.resolve().then(() => usbDevice.open()) .catch(e => handleDeviceOpenError(e)); }
[ "function", "openUsbDevice", "(", "usbDevice", ",", "{", "dfuMode", "=", "false", "}", "=", "{", "}", ")", "{", "if", "(", "!", "dfuMode", "&&", "usbDevice", ".", "isInDfuMode", ")", "{", "return", "when", ".", "reject", "(", "new", "Error", "(", "'The device should not be in DFU mode'", ")", ")", ";", "}", "return", "when", ".", "resolve", "(", ")", ".", "then", "(", "(", ")", "=>", "usbDevice", ".", "open", "(", ")", ")", ".", "catch", "(", "e", "=>", "handleDeviceOpenError", "(", "e", ")", ")", ";", "}" ]
Open a USB device. This function checks whether the user has necessary permissions to access the device. Use this function instead of particle-usb's Device.open(). @param {Object} usbDevice USB device. @param {Object} options Options. @param {Boolean} [options.dfuMode] Set to `true` if the device can be in DFU mode. @return {Promise}
[ "Open", "a", "USB", "device", "." ]
50143bb34835f200b83b7eaf77cb8ab847f05a13
https://github.com/particle-iot/particle-cli/blob/50143bb34835f200b83b7eaf77cb8ab847f05a13/src/cmd/usb-util.js#L38-L44
15,236
particle-iot/particle-cli
src/cmd/usb-util.js
openUsbDeviceById
function openUsbDeviceById({ id, api, auth, dfuMode = false, displayName = null }) { return when.resolve().then(() => { if (isDeviceId(id)) { // Try to open the device straight away return openDeviceById(id).catch(e => { if (!(e instanceof NotFoundError)) { return handleDeviceOpenError(e); } }); } }) .then(usbDevice => { if (!usbDevice) { return getDevice({ id, api, auth, displayName }).then(device => { if (device.id === id) { throw new NotFoundError(); } return openDeviceById(device.id).catch(e => handleDeviceOpenError(e)); }) .catch(e => { if (e instanceof NotFoundError) { throw new Error(`Unable to connect to the device ${displayName || id}. Make sure the device is connected to the host computer via USB`); } throw e; }); } return usbDevice; }) .then(usbDevice => { if (!dfuMode && usbDevice.isInDfuMode) { return usbDevice.close().then(() => { throw new Error('The device should not be in DFU mode'); }); } return usbDevice; }); }
javascript
function openUsbDeviceById({ id, api, auth, dfuMode = false, displayName = null }) { return when.resolve().then(() => { if (isDeviceId(id)) { // Try to open the device straight away return openDeviceById(id).catch(e => { if (!(e instanceof NotFoundError)) { return handleDeviceOpenError(e); } }); } }) .then(usbDevice => { if (!usbDevice) { return getDevice({ id, api, auth, displayName }).then(device => { if (device.id === id) { throw new NotFoundError(); } return openDeviceById(device.id).catch(e => handleDeviceOpenError(e)); }) .catch(e => { if (e instanceof NotFoundError) { throw new Error(`Unable to connect to the device ${displayName || id}. Make sure the device is connected to the host computer via USB`); } throw e; }); } return usbDevice; }) .then(usbDevice => { if (!dfuMode && usbDevice.isInDfuMode) { return usbDevice.close().then(() => { throw new Error('The device should not be in DFU mode'); }); } return usbDevice; }); }
[ "function", "openUsbDeviceById", "(", "{", "id", ",", "api", ",", "auth", ",", "dfuMode", "=", "false", ",", "displayName", "=", "null", "}", ")", "{", "return", "when", ".", "resolve", "(", ")", ".", "then", "(", "(", ")", "=>", "{", "if", "(", "isDeviceId", "(", "id", ")", ")", "{", "// Try to open the device straight away", "return", "openDeviceById", "(", "id", ")", ".", "catch", "(", "e", "=>", "{", "if", "(", "!", "(", "e", "instanceof", "NotFoundError", ")", ")", "{", "return", "handleDeviceOpenError", "(", "e", ")", ";", "}", "}", ")", ";", "}", "}", ")", ".", "then", "(", "usbDevice", "=>", "{", "if", "(", "!", "usbDevice", ")", "{", "return", "getDevice", "(", "{", "id", ",", "api", ",", "auth", ",", "displayName", "}", ")", ".", "then", "(", "device", "=>", "{", "if", "(", "device", ".", "id", "===", "id", ")", "{", "throw", "new", "NotFoundError", "(", ")", ";", "}", "return", "openDeviceById", "(", "device", ".", "id", ")", ".", "catch", "(", "e", "=>", "handleDeviceOpenError", "(", "e", ")", ")", ";", "}", ")", ".", "catch", "(", "e", "=>", "{", "if", "(", "e", "instanceof", "NotFoundError", ")", "{", "throw", "new", "Error", "(", "`", "${", "displayName", "||", "id", "}", "`", ")", ";", "}", "throw", "e", ";", "}", ")", ";", "}", "return", "usbDevice", ";", "}", ")", ".", "then", "(", "usbDevice", "=>", "{", "if", "(", "!", "dfuMode", "&&", "usbDevice", ".", "isInDfuMode", ")", "{", "return", "usbDevice", ".", "close", "(", ")", ".", "then", "(", "(", ")", "=>", "{", "throw", "new", "Error", "(", "'The device should not be in DFU mode'", ")", ";", "}", ")", ";", "}", "return", "usbDevice", ";", "}", ")", ";", "}" ]
Open a USB device with the specified device ID or name. This function checks whether the user has necessary permissions to access the device. Use this function instead of particle-usb's openDeviceById(). @param {Object} options Options. @param {String} options.id Device ID or name. @param {Object} options.api API client. @param {String} options.auth Access token. @param {Boolean} [options.dfuMode] Set to `true` if the device can be in DFU mode. @param {String} [options.displayName] Device name as shown to the user. @return {Promise}
[ "Open", "a", "USB", "device", "with", "the", "specified", "device", "ID", "or", "name", "." ]
50143bb34835f200b83b7eaf77cb8ab847f05a13
https://github.com/particle-iot/particle-cli/blob/50143bb34835f200b83b7eaf77cb8ab847f05a13/src/cmd/usb-util.js#L60-L96
15,237
particle-iot/particle-cli
src/app/command-processor.js
createErrorHandler
function createErrorHandler(yargs) { if (!yargs) { yargs = Yargs; } return consoleErrorLogger.bind(undefined, console, yargs, true); }
javascript
function createErrorHandler(yargs) { if (!yargs) { yargs = Yargs; } return consoleErrorLogger.bind(undefined, console, yargs, true); }
[ "function", "createErrorHandler", "(", "yargs", ")", "{", "if", "(", "!", "yargs", ")", "{", "yargs", "=", "Yargs", ";", "}", "return", "consoleErrorLogger", ".", "bind", "(", "undefined", ",", "console", ",", "yargs", ",", "true", ")", ";", "}" ]
Creates an error handler. The handler displays the error message if there is one, or displays the help if there ie no error or it is a usage error. @param {object} yargs @returns {function(err)} the error handler function
[ "Creates", "an", "error", "handler", ".", "The", "handler", "displays", "the", "error", "message", "if", "there", "is", "one", "or", "displays", "the", "help", "if", "there", "ie", "no", "error", "or", "it", "is", "a", "usage", "error", "." ]
50143bb34835f200b83b7eaf77cb8ab847f05a13
https://github.com/particle-iot/particle-cli/blob/50143bb34835f200b83b7eaf77cb8ab847f05a13/src/app/command-processor.js#L410-L415
15,238
particle-iot/particle-cli
src/app/command-processor.js
parseParams
function parseParams(yargs, argv, path, params) { let required = 0; let optional = 0; let variadic = false; argv.params = {}; const extra = argv._.slice(path.length); argv._ = argv._.slice(0, path.length); params.replace(/(<[^>]+>|\[[^\]]+\])/g, (match) => { if (variadic) { throw variadicParameterPositionError(variadic); } const isRequired = match[0] === '<'; const param = match .slice(1, -1) .replace(/(.*)\.\.\.$/, (m, param) => { variadic = true; return param; }); let value; if (isRequired) { required++; } else { optional++; } if (variadic) { variadic = param; // save the name value = extra.slice(-1 + required + optional).map(String); if (isRequired && !value.length) { throw variadicParameterRequiredError(param); } } else { if (isRequired && optional > 0) { throw requiredParameterPositionError(param); } value = extra[-1 + required + optional]; if (value) { value = String(value); } if (isRequired && typeof value === 'undefined') { throw requiredParameterError(param); } } const params = param.split('|'); params.forEach(p => { argv.params[p] = value; }); }); if (!variadic && required+optional < extra.length) { throw unknownParametersError(extra.slice(required+optional)); } }
javascript
function parseParams(yargs, argv, path, params) { let required = 0; let optional = 0; let variadic = false; argv.params = {}; const extra = argv._.slice(path.length); argv._ = argv._.slice(0, path.length); params.replace(/(<[^>]+>|\[[^\]]+\])/g, (match) => { if (variadic) { throw variadicParameterPositionError(variadic); } const isRequired = match[0] === '<'; const param = match .slice(1, -1) .replace(/(.*)\.\.\.$/, (m, param) => { variadic = true; return param; }); let value; if (isRequired) { required++; } else { optional++; } if (variadic) { variadic = param; // save the name value = extra.slice(-1 + required + optional).map(String); if (isRequired && !value.length) { throw variadicParameterRequiredError(param); } } else { if (isRequired && optional > 0) { throw requiredParameterPositionError(param); } value = extra[-1 + required + optional]; if (value) { value = String(value); } if (isRequired && typeof value === 'undefined') { throw requiredParameterError(param); } } const params = param.split('|'); params.forEach(p => { argv.params[p] = value; }); }); if (!variadic && required+optional < extra.length) { throw unknownParametersError(extra.slice(required+optional)); } }
[ "function", "parseParams", "(", "yargs", ",", "argv", ",", "path", ",", "params", ")", "{", "let", "required", "=", "0", ";", "let", "optional", "=", "0", ";", "let", "variadic", "=", "false", ";", "argv", ".", "params", "=", "{", "}", ";", "const", "extra", "=", "argv", ".", "_", ".", "slice", "(", "path", ".", "length", ")", ";", "argv", ".", "_", "=", "argv", ".", "_", ".", "slice", "(", "0", ",", "path", ".", "length", ")", ";", "params", ".", "replace", "(", "/", "(<[^>]+>|\\[[^\\]]+\\])", "/", "g", ",", "(", "match", ")", "=>", "{", "if", "(", "variadic", ")", "{", "throw", "variadicParameterPositionError", "(", "variadic", ")", ";", "}", "const", "isRequired", "=", "match", "[", "0", "]", "===", "'<'", ";", "const", "param", "=", "match", ".", "slice", "(", "1", ",", "-", "1", ")", ".", "replace", "(", "/", "(.*)\\.\\.\\.$", "/", ",", "(", "m", ",", "param", ")", "=>", "{", "variadic", "=", "true", ";", "return", "param", ";", "}", ")", ";", "let", "value", ";", "if", "(", "isRequired", ")", "{", "required", "++", ";", "}", "else", "{", "optional", "++", ";", "}", "if", "(", "variadic", ")", "{", "variadic", "=", "param", ";", "// save the name", "value", "=", "extra", ".", "slice", "(", "-", "1", "+", "required", "+", "optional", ")", ".", "map", "(", "String", ")", ";", "if", "(", "isRequired", "&&", "!", "value", ".", "length", ")", "{", "throw", "variadicParameterRequiredError", "(", "param", ")", ";", "}", "}", "else", "{", "if", "(", "isRequired", "&&", "optional", ">", "0", ")", "{", "throw", "requiredParameterPositionError", "(", "param", ")", ";", "}", "value", "=", "extra", "[", "-", "1", "+", "required", "+", "optional", "]", ";", "if", "(", "value", ")", "{", "value", "=", "String", "(", "value", ")", ";", "}", "if", "(", "isRequired", "&&", "typeof", "value", "===", "'undefined'", ")", "{", "throw", "requiredParameterError", "(", "param", ")", ";", "}", "}", "const", "params", "=", "param", ".", "split", "(", "'|'", ")", ";", "params", ".", "forEach", "(", "p", "=>", "{", "argv", ".", "params", "[", "p", "]", "=", "value", ";", "}", ")", ";", "}", ")", ";", "if", "(", "!", "variadic", "&&", "required", "+", "optional", "<", "extra", ".", "length", ")", "{", "throw", "unknownParametersError", "(", "extra", ".", "slice", "(", "required", "+", "optional", ")", ")", ";", "}", "}" ]
Parses parameters specified with the given command. The parsed params are stored as `argv.params`. @param {object} yargs The yargs command line parser @param {Array<String>} argv The parsed command line @param {Array<String>} path The command path the params apply to @param {string} params The params to parse.
[ "Parses", "parameters", "specified", "with", "the", "given", "command", ".", "The", "parsed", "params", "are", "stored", "as", "argv", ".", "params", "." ]
50143bb34835f200b83b7eaf77cb8ab847f05a13
https://github.com/particle-iot/particle-cli/blob/50143bb34835f200b83b7eaf77cb8ab847f05a13/src/app/command-processor.js#L493-L556
15,239
particle-iot/particle-cli
src/app/command-processor.js
parse
function parse(command, args) { Yargs.reset(); Yargs.wrap(Yargs.terminalWidth()); return command.parse(args, Yargs); }
javascript
function parse(command, args) { Yargs.reset(); Yargs.wrap(Yargs.terminalWidth()); return command.parse(args, Yargs); }
[ "function", "parse", "(", "command", ",", "args", ")", "{", "Yargs", ".", "reset", "(", ")", ";", "Yargs", ".", "wrap", "(", "Yargs", ".", "terminalWidth", "(", ")", ")", ";", "return", "command", ".", "parse", "(", "args", ",", "Yargs", ")", ";", "}" ]
Top-level invocation of the command processor. @param {CLICommandItem} command @param {Array} args @returns {*} The argv from yargs parsing. Options/booleans are attributes of the object. The property `clicommand` contains the command corresponding to the requested command. `clierror` contains any error encountered durng parsing.
[ "Top", "-", "level", "invocation", "of", "the", "command", "processor", "." ]
50143bb34835f200b83b7eaf77cb8ab847f05a13
https://github.com/particle-iot/particle-cli/blob/50143bb34835f200b83b7eaf77cb8ab847f05a13/src/app/command-processor.js#L602-L606
15,240
particle-iot/particle-cli
src/cmd/device-util.js
getDevice
function getDevice({ id, api, auth, displayName = null, dontThrow = false }) { const p = when.resolve().then(() => api.getDevice({ deviceId: id, auth })) .then(r => r.body) .catch(e => { if (e.statusCode === 403 || e.statusCode === 404) { if (dontThrow) { return null; } throw new Error(`Device not found: ${displayName || id}`); } throw e; }); return spin(p, 'Getting device information...'); }
javascript
function getDevice({ id, api, auth, displayName = null, dontThrow = false }) { const p = when.resolve().then(() => api.getDevice({ deviceId: id, auth })) .then(r => r.body) .catch(e => { if (e.statusCode === 403 || e.statusCode === 404) { if (dontThrow) { return null; } throw new Error(`Device not found: ${displayName || id}`); } throw e; }); return spin(p, 'Getting device information...'); }
[ "function", "getDevice", "(", "{", "id", ",", "api", ",", "auth", ",", "displayName", "=", "null", ",", "dontThrow", "=", "false", "}", ")", "{", "const", "p", "=", "when", ".", "resolve", "(", ")", ".", "then", "(", "(", ")", "=>", "api", ".", "getDevice", "(", "{", "deviceId", ":", "id", ",", "auth", "}", ")", ")", ".", "then", "(", "r", "=>", "r", ".", "body", ")", ".", "catch", "(", "e", "=>", "{", "if", "(", "e", ".", "statusCode", "===", "403", "||", "e", ".", "statusCode", "===", "404", ")", "{", "if", "(", "dontThrow", ")", "{", "return", "null", ";", "}", "throw", "new", "Error", "(", "`", "${", "displayName", "||", "id", "}", "`", ")", ";", "}", "throw", "e", ";", "}", ")", ";", "return", "spin", "(", "p", ",", "'Getting device information...'", ")", ";", "}" ]
Get device attributes. @param {Object} options Options. @param {String} options.id Device ID or name. @param {Object} options.api API client. @param {String} options.auth Access token. @param {String} [options.displayName] Device name as shown to the user. @param {Boolean} [options.dontThrow] Return 'null' instead of throwing an error if the device cannot be found. @param {Promise<Object>}
[ "Get", "device", "attributes", "." ]
50143bb34835f200b83b7eaf77cb8ab847f05a13
https://github.com/particle-iot/particle-cli/blob/50143bb34835f200b83b7eaf77cb8ab847f05a13/src/cmd/device-util.js#L39-L52
15,241
byteball/ocore
proof_chain.js
buildProofChain
function buildProofChain(later_mci, earlier_mci, unit, arrBalls, onDone){ if (earlier_mci === null) throw Error("earlier_mci=null, unit="+unit); if (later_mci === earlier_mci) return buildLastMileOfProofChain(earlier_mci, unit, arrBalls, onDone); buildProofChainOnMc(later_mci, earlier_mci, arrBalls, function(){ buildLastMileOfProofChain(earlier_mci, unit, arrBalls, onDone); }); }
javascript
function buildProofChain(later_mci, earlier_mci, unit, arrBalls, onDone){ if (earlier_mci === null) throw Error("earlier_mci=null, unit="+unit); if (later_mci === earlier_mci) return buildLastMileOfProofChain(earlier_mci, unit, arrBalls, onDone); buildProofChainOnMc(later_mci, earlier_mci, arrBalls, function(){ buildLastMileOfProofChain(earlier_mci, unit, arrBalls, onDone); }); }
[ "function", "buildProofChain", "(", "later_mci", ",", "earlier_mci", ",", "unit", ",", "arrBalls", ",", "onDone", ")", "{", "if", "(", "earlier_mci", "===", "null", ")", "throw", "Error", "(", "\"earlier_mci=null, unit=\"", "+", "unit", ")", ";", "if", "(", "later_mci", "===", "earlier_mci", ")", "return", "buildLastMileOfProofChain", "(", "earlier_mci", ",", "unit", ",", "arrBalls", ",", "onDone", ")", ";", "buildProofChainOnMc", "(", "later_mci", ",", "earlier_mci", ",", "arrBalls", ",", "function", "(", ")", "{", "buildLastMileOfProofChain", "(", "earlier_mci", ",", "unit", ",", "arrBalls", ",", "onDone", ")", ";", "}", ")", ";", "}" ]
unit's MC index is earlier_mci
[ "unit", "s", "MC", "index", "is", "earlier_mci" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/proof_chain.js#L9-L17
15,242
byteball/ocore
proof_chain.js
buildProofChainOnMc
function buildProofChainOnMc(later_mci, earlier_mci, arrBalls, onDone){ function addBall(mci){ if (mci < 0) throw Error("mci<0, later_mci="+later_mci+", earlier_mci="+earlier_mci); db.query("SELECT unit, ball, content_hash FROM units JOIN balls USING(unit) WHERE main_chain_index=? AND is_on_main_chain=1", [mci], function(rows){ if (rows.length !== 1) throw Error("no prev chain element? mci="+mci+", later_mci="+later_mci+", earlier_mci="+earlier_mci); var objBall = rows[0]; if (objBall.content_hash) objBall.is_nonserial = true; delete objBall.content_hash; db.query( "SELECT ball FROM parenthoods LEFT JOIN balls ON parent_unit=balls.unit WHERE child_unit=? ORDER BY ball", [objBall.unit], function(parent_rows){ if (parent_rows.some(function(parent_row){ return !parent_row.ball; })) throw Error("some parents have no balls"); if (parent_rows.length > 0) objBall.parent_balls = parent_rows.map(function(parent_row){ return parent_row.ball; }); db.query( "SELECT ball, main_chain_index \n\ FROM skiplist_units JOIN units ON skiplist_unit=units.unit LEFT JOIN balls ON units.unit=balls.unit \n\ WHERE skiplist_units.unit=? ORDER BY ball", [objBall.unit], function(srows){ if (srows.some(function(srow){ return !srow.ball; })) throw Error("some skiplist units have no balls"); if (srows.length > 0) objBall.skiplist_balls = srows.map(function(srow){ return srow.ball; }); arrBalls.push(objBall); if (mci === earlier_mci) return onDone(); if (srows.length === 0) // no skiplist return addBall(mci-1); var next_mci = mci - 1; for (var i=0; i<srows.length; i++){ var next_skiplist_mci = srows[i].main_chain_index; if (next_skiplist_mci < next_mci && next_skiplist_mci >= earlier_mci) next_mci = next_skiplist_mci; } addBall(next_mci); } ); } ); }); } if (earlier_mci > later_mci) throw Error("earlier > later"); if (earlier_mci === later_mci) return onDone(); addBall(later_mci - 1); }
javascript
function buildProofChainOnMc(later_mci, earlier_mci, arrBalls, onDone){ function addBall(mci){ if (mci < 0) throw Error("mci<0, later_mci="+later_mci+", earlier_mci="+earlier_mci); db.query("SELECT unit, ball, content_hash FROM units JOIN balls USING(unit) WHERE main_chain_index=? AND is_on_main_chain=1", [mci], function(rows){ if (rows.length !== 1) throw Error("no prev chain element? mci="+mci+", later_mci="+later_mci+", earlier_mci="+earlier_mci); var objBall = rows[0]; if (objBall.content_hash) objBall.is_nonserial = true; delete objBall.content_hash; db.query( "SELECT ball FROM parenthoods LEFT JOIN balls ON parent_unit=balls.unit WHERE child_unit=? ORDER BY ball", [objBall.unit], function(parent_rows){ if (parent_rows.some(function(parent_row){ return !parent_row.ball; })) throw Error("some parents have no balls"); if (parent_rows.length > 0) objBall.parent_balls = parent_rows.map(function(parent_row){ return parent_row.ball; }); db.query( "SELECT ball, main_chain_index \n\ FROM skiplist_units JOIN units ON skiplist_unit=units.unit LEFT JOIN balls ON units.unit=balls.unit \n\ WHERE skiplist_units.unit=? ORDER BY ball", [objBall.unit], function(srows){ if (srows.some(function(srow){ return !srow.ball; })) throw Error("some skiplist units have no balls"); if (srows.length > 0) objBall.skiplist_balls = srows.map(function(srow){ return srow.ball; }); arrBalls.push(objBall); if (mci === earlier_mci) return onDone(); if (srows.length === 0) // no skiplist return addBall(mci-1); var next_mci = mci - 1; for (var i=0; i<srows.length; i++){ var next_skiplist_mci = srows[i].main_chain_index; if (next_skiplist_mci < next_mci && next_skiplist_mci >= earlier_mci) next_mci = next_skiplist_mci; } addBall(next_mci); } ); } ); }); } if (earlier_mci > later_mci) throw Error("earlier > later"); if (earlier_mci === later_mci) return onDone(); addBall(later_mci - 1); }
[ "function", "buildProofChainOnMc", "(", "later_mci", ",", "earlier_mci", ",", "arrBalls", ",", "onDone", ")", "{", "function", "addBall", "(", "mci", ")", "{", "if", "(", "mci", "<", "0", ")", "throw", "Error", "(", "\"mci<0, later_mci=\"", "+", "later_mci", "+", "\", earlier_mci=\"", "+", "earlier_mci", ")", ";", "db", ".", "query", "(", "\"SELECT unit, ball, content_hash FROM units JOIN balls USING(unit) WHERE main_chain_index=? AND is_on_main_chain=1\"", ",", "[", "mci", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "!==", "1", ")", "throw", "Error", "(", "\"no prev chain element? mci=\"", "+", "mci", "+", "\", later_mci=\"", "+", "later_mci", "+", "\", earlier_mci=\"", "+", "earlier_mci", ")", ";", "var", "objBall", "=", "rows", "[", "0", "]", ";", "if", "(", "objBall", ".", "content_hash", ")", "objBall", ".", "is_nonserial", "=", "true", ";", "delete", "objBall", ".", "content_hash", ";", "db", ".", "query", "(", "\"SELECT ball FROM parenthoods LEFT JOIN balls ON parent_unit=balls.unit WHERE child_unit=? ORDER BY ball\"", ",", "[", "objBall", ".", "unit", "]", ",", "function", "(", "parent_rows", ")", "{", "if", "(", "parent_rows", ".", "some", "(", "function", "(", "parent_row", ")", "{", "return", "!", "parent_row", ".", "ball", ";", "}", ")", ")", "throw", "Error", "(", "\"some parents have no balls\"", ")", ";", "if", "(", "parent_rows", ".", "length", ">", "0", ")", "objBall", ".", "parent_balls", "=", "parent_rows", ".", "map", "(", "function", "(", "parent_row", ")", "{", "return", "parent_row", ".", "ball", ";", "}", ")", ";", "db", ".", "query", "(", "\"SELECT ball, main_chain_index \\n\\\n\t\t\t\t\t\tFROM skiplist_units JOIN units ON skiplist_unit=units.unit LEFT JOIN balls ON units.unit=balls.unit \\n\\\n\t\t\t\t\t\tWHERE skiplist_units.unit=? ORDER BY ball\"", ",", "[", "objBall", ".", "unit", "]", ",", "function", "(", "srows", ")", "{", "if", "(", "srows", ".", "some", "(", "function", "(", "srow", ")", "{", "return", "!", "srow", ".", "ball", ";", "}", ")", ")", "throw", "Error", "(", "\"some skiplist units have no balls\"", ")", ";", "if", "(", "srows", ".", "length", ">", "0", ")", "objBall", ".", "skiplist_balls", "=", "srows", ".", "map", "(", "function", "(", "srow", ")", "{", "return", "srow", ".", "ball", ";", "}", ")", ";", "arrBalls", ".", "push", "(", "objBall", ")", ";", "if", "(", "mci", "===", "earlier_mci", ")", "return", "onDone", "(", ")", ";", "if", "(", "srows", ".", "length", "===", "0", ")", "// no skiplist", "return", "addBall", "(", "mci", "-", "1", ")", ";", "var", "next_mci", "=", "mci", "-", "1", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "srows", ".", "length", ";", "i", "++", ")", "{", "var", "next_skiplist_mci", "=", "srows", "[", "i", "]", ".", "main_chain_index", ";", "if", "(", "next_skiplist_mci", "<", "next_mci", "&&", "next_skiplist_mci", ">=", "earlier_mci", ")", "next_mci", "=", "next_skiplist_mci", ";", "}", "addBall", "(", "next_mci", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}", "if", "(", "earlier_mci", ">", "later_mci", ")", "throw", "Error", "(", "\"earlier > later\"", ")", ";", "if", "(", "earlier_mci", "===", "later_mci", ")", "return", "onDone", "(", ")", ";", "addBall", "(", "later_mci", "-", "1", ")", ";", "}" ]
later_mci is already known and not included in the chain
[ "later_mci", "is", "already", "known", "and", "not", "included", "in", "the", "chain" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/proof_chain.js#L20-L74
15,243
byteball/ocore
proof_chain.js
buildLastMileOfProofChain
function buildLastMileOfProofChain(mci, unit, arrBalls, onDone){ function addBall(_unit){ db.query("SELECT unit, ball, content_hash FROM units JOIN balls USING(unit) WHERE unit=?", [_unit], function(rows){ if (rows.length !== 1) throw Error("no unit?"); var objBall = rows[0]; if (objBall.content_hash) objBall.is_nonserial = true; delete objBall.content_hash; db.query( "SELECT ball FROM parenthoods LEFT JOIN balls ON parent_unit=balls.unit WHERE child_unit=? ORDER BY ball", [objBall.unit], function(parent_rows){ if (parent_rows.some(function(parent_row){ return !parent_row.ball; })) throw Error("some parents have no balls"); if (parent_rows.length > 0) objBall.parent_balls = parent_rows.map(function(parent_row){ return parent_row.ball; }); db.query( "SELECT ball \n\ FROM skiplist_units JOIN units ON skiplist_unit=units.unit LEFT JOIN balls ON units.unit=balls.unit \n\ WHERE skiplist_units.unit=? ORDER BY ball", [objBall.unit], function(srows){ if (srows.some(function(srow){ return !srow.ball; })) throw Error("last mile: some skiplist units have no balls"); if (srows.length > 0) objBall.skiplist_balls = srows.map(function(srow){ return srow.ball; }); arrBalls.push(objBall); if (_unit === unit) return onDone(); findParent(_unit); } ); } ); }); } function findParent(interim_unit){ db.query( "SELECT parent_unit FROM parenthoods JOIN units ON parent_unit=unit WHERE child_unit=? AND main_chain_index=?", [interim_unit, mci], function(parent_rows){ var arrParents = parent_rows.map(function(parent_row){ return parent_row.parent_unit; }); if (arrParents.indexOf(unit) >= 0) return addBall(unit); async.eachSeries( arrParents, function(parent_unit, cb){ graph.determineIfIncluded(db, unit, [parent_unit], function(bIncluded){ bIncluded ? cb(parent_unit) : cb(); }); }, function(parent_unit){ if (!parent_unit) throw Error("no parent that includes target unit"); addBall(parent_unit); } ) } ); } // start from MC unit and go back in history db.query("SELECT unit FROM units WHERE main_chain_index=? AND is_on_main_chain=1", [mci], function(rows){ if (rows.length !== 1) throw Error("no mc unit?"); var mc_unit = rows[0].unit; if (mc_unit === unit) return onDone(); findParent(mc_unit); }); }
javascript
function buildLastMileOfProofChain(mci, unit, arrBalls, onDone){ function addBall(_unit){ db.query("SELECT unit, ball, content_hash FROM units JOIN balls USING(unit) WHERE unit=?", [_unit], function(rows){ if (rows.length !== 1) throw Error("no unit?"); var objBall = rows[0]; if (objBall.content_hash) objBall.is_nonserial = true; delete objBall.content_hash; db.query( "SELECT ball FROM parenthoods LEFT JOIN balls ON parent_unit=balls.unit WHERE child_unit=? ORDER BY ball", [objBall.unit], function(parent_rows){ if (parent_rows.some(function(parent_row){ return !parent_row.ball; })) throw Error("some parents have no balls"); if (parent_rows.length > 0) objBall.parent_balls = parent_rows.map(function(parent_row){ return parent_row.ball; }); db.query( "SELECT ball \n\ FROM skiplist_units JOIN units ON skiplist_unit=units.unit LEFT JOIN balls ON units.unit=balls.unit \n\ WHERE skiplist_units.unit=? ORDER BY ball", [objBall.unit], function(srows){ if (srows.some(function(srow){ return !srow.ball; })) throw Error("last mile: some skiplist units have no balls"); if (srows.length > 0) objBall.skiplist_balls = srows.map(function(srow){ return srow.ball; }); arrBalls.push(objBall); if (_unit === unit) return onDone(); findParent(_unit); } ); } ); }); } function findParent(interim_unit){ db.query( "SELECT parent_unit FROM parenthoods JOIN units ON parent_unit=unit WHERE child_unit=? AND main_chain_index=?", [interim_unit, mci], function(parent_rows){ var arrParents = parent_rows.map(function(parent_row){ return parent_row.parent_unit; }); if (arrParents.indexOf(unit) >= 0) return addBall(unit); async.eachSeries( arrParents, function(parent_unit, cb){ graph.determineIfIncluded(db, unit, [parent_unit], function(bIncluded){ bIncluded ? cb(parent_unit) : cb(); }); }, function(parent_unit){ if (!parent_unit) throw Error("no parent that includes target unit"); addBall(parent_unit); } ) } ); } // start from MC unit and go back in history db.query("SELECT unit FROM units WHERE main_chain_index=? AND is_on_main_chain=1", [mci], function(rows){ if (rows.length !== 1) throw Error("no mc unit?"); var mc_unit = rows[0].unit; if (mc_unit === unit) return onDone(); findParent(mc_unit); }); }
[ "function", "buildLastMileOfProofChain", "(", "mci", ",", "unit", ",", "arrBalls", ",", "onDone", ")", "{", "function", "addBall", "(", "_unit", ")", "{", "db", ".", "query", "(", "\"SELECT unit, ball, content_hash FROM units JOIN balls USING(unit) WHERE unit=?\"", ",", "[", "_unit", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "!==", "1", ")", "throw", "Error", "(", "\"no unit?\"", ")", ";", "var", "objBall", "=", "rows", "[", "0", "]", ";", "if", "(", "objBall", ".", "content_hash", ")", "objBall", ".", "is_nonserial", "=", "true", ";", "delete", "objBall", ".", "content_hash", ";", "db", ".", "query", "(", "\"SELECT ball FROM parenthoods LEFT JOIN balls ON parent_unit=balls.unit WHERE child_unit=? ORDER BY ball\"", ",", "[", "objBall", ".", "unit", "]", ",", "function", "(", "parent_rows", ")", "{", "if", "(", "parent_rows", ".", "some", "(", "function", "(", "parent_row", ")", "{", "return", "!", "parent_row", ".", "ball", ";", "}", ")", ")", "throw", "Error", "(", "\"some parents have no balls\"", ")", ";", "if", "(", "parent_rows", ".", "length", ">", "0", ")", "objBall", ".", "parent_balls", "=", "parent_rows", ".", "map", "(", "function", "(", "parent_row", ")", "{", "return", "parent_row", ".", "ball", ";", "}", ")", ";", "db", ".", "query", "(", "\"SELECT ball \\n\\\n\t\t\t\t\t\tFROM skiplist_units JOIN units ON skiplist_unit=units.unit LEFT JOIN balls ON units.unit=balls.unit \\n\\\n\t\t\t\t\t\tWHERE skiplist_units.unit=? ORDER BY ball\"", ",", "[", "objBall", ".", "unit", "]", ",", "function", "(", "srows", ")", "{", "if", "(", "srows", ".", "some", "(", "function", "(", "srow", ")", "{", "return", "!", "srow", ".", "ball", ";", "}", ")", ")", "throw", "Error", "(", "\"last mile: some skiplist units have no balls\"", ")", ";", "if", "(", "srows", ".", "length", ">", "0", ")", "objBall", ".", "skiplist_balls", "=", "srows", ".", "map", "(", "function", "(", "srow", ")", "{", "return", "srow", ".", "ball", ";", "}", ")", ";", "arrBalls", ".", "push", "(", "objBall", ")", ";", "if", "(", "_unit", "===", "unit", ")", "return", "onDone", "(", ")", ";", "findParent", "(", "_unit", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}", "function", "findParent", "(", "interim_unit", ")", "{", "db", ".", "query", "(", "\"SELECT parent_unit FROM parenthoods JOIN units ON parent_unit=unit WHERE child_unit=? AND main_chain_index=?\"", ",", "[", "interim_unit", ",", "mci", "]", ",", "function", "(", "parent_rows", ")", "{", "var", "arrParents", "=", "parent_rows", ".", "map", "(", "function", "(", "parent_row", ")", "{", "return", "parent_row", ".", "parent_unit", ";", "}", ")", ";", "if", "(", "arrParents", ".", "indexOf", "(", "unit", ")", ">=", "0", ")", "return", "addBall", "(", "unit", ")", ";", "async", ".", "eachSeries", "(", "arrParents", ",", "function", "(", "parent_unit", ",", "cb", ")", "{", "graph", ".", "determineIfIncluded", "(", "db", ",", "unit", ",", "[", "parent_unit", "]", ",", "function", "(", "bIncluded", ")", "{", "bIncluded", "?", "cb", "(", "parent_unit", ")", ":", "cb", "(", ")", ";", "}", ")", ";", "}", ",", "function", "(", "parent_unit", ")", "{", "if", "(", "!", "parent_unit", ")", "throw", "Error", "(", "\"no parent that includes target unit\"", ")", ";", "addBall", "(", "parent_unit", ")", ";", "}", ")", "}", ")", ";", "}", "// start from MC unit and go back in history", "db", ".", "query", "(", "\"SELECT unit FROM units WHERE main_chain_index=? AND is_on_main_chain=1\"", ",", "[", "mci", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "!==", "1", ")", "throw", "Error", "(", "\"no mc unit?\"", ")", ";", "var", "mc_unit", "=", "rows", "[", "0", "]", ".", "unit", ";", "if", "(", "mc_unit", "===", "unit", ")", "return", "onDone", "(", ")", ";", "findParent", "(", "mc_unit", ")", ";", "}", ")", ";", "}" ]
unit's MC index is mci, find a path from mci unit to this unit
[ "unit", "s", "MC", "index", "is", "mci", "find", "a", "path", "from", "mci", "unit", "to", "this", "unit" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/proof_chain.js#L77-L149
15,244
byteball/ocore
composer.js
composeTextJoint
function composeTextJoint(arrSigningAddresses, arrPayingAddresses, text, signer, callbacks){ composePaymentAndTextJoint(arrSigningAddresses, arrPayingAddresses, [{address: arrPayingAddresses[0], amount: 0}], text, signer, callbacks); }
javascript
function composeTextJoint(arrSigningAddresses, arrPayingAddresses, text, signer, callbacks){ composePaymentAndTextJoint(arrSigningAddresses, arrPayingAddresses, [{address: arrPayingAddresses[0], amount: 0}], text, signer, callbacks); }
[ "function", "composeTextJoint", "(", "arrSigningAddresses", ",", "arrPayingAddresses", ",", "text", ",", "signer", ",", "callbacks", ")", "{", "composePaymentAndTextJoint", "(", "arrSigningAddresses", ",", "arrPayingAddresses", ",", "[", "{", "address", ":", "arrPayingAddresses", "[", "0", "]", ",", "amount", ":", "0", "}", "]", ",", "text", ",", "signer", ",", "callbacks", ")", ";", "}" ]
change goes back to the first paying address
[ "change", "goes", "back", "to", "the", "first", "paying", "address" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/composer.js#L50-L52
15,245
byteball/ocore
composer.js
function(cb){ if (!fnRetrieveMessages) return cb(); console.log("will retrieve messages"); fnRetrieveMessages(conn, last_ball_mci, bMultiAuthored, arrPayingAddresses, function(err, arrMoreMessages, assocMorePrivatePayloads){ console.log("fnRetrieveMessages callback: err code = "+(err ? err.error_code : "")); if (err) return cb((typeof err === "string") ? ("unable to add additional messages: "+err) : err); Array.prototype.push.apply(objUnit.messages, arrMoreMessages); if (assocMorePrivatePayloads && Object.keys(assocMorePrivatePayloads).length > 0) for (var payload_hash in assocMorePrivatePayloads) assocPrivatePayloads[payload_hash] = assocMorePrivatePayloads[payload_hash]; cb(); }); }
javascript
function(cb){ if (!fnRetrieveMessages) return cb(); console.log("will retrieve messages"); fnRetrieveMessages(conn, last_ball_mci, bMultiAuthored, arrPayingAddresses, function(err, arrMoreMessages, assocMorePrivatePayloads){ console.log("fnRetrieveMessages callback: err code = "+(err ? err.error_code : "")); if (err) return cb((typeof err === "string") ? ("unable to add additional messages: "+err) : err); Array.prototype.push.apply(objUnit.messages, arrMoreMessages); if (assocMorePrivatePayloads && Object.keys(assocMorePrivatePayloads).length > 0) for (var payload_hash in assocMorePrivatePayloads) assocPrivatePayloads[payload_hash] = assocMorePrivatePayloads[payload_hash]; cb(); }); }
[ "function", "(", "cb", ")", "{", "if", "(", "!", "fnRetrieveMessages", ")", "return", "cb", "(", ")", ";", "console", ".", "log", "(", "\"will retrieve messages\"", ")", ";", "fnRetrieveMessages", "(", "conn", ",", "last_ball_mci", ",", "bMultiAuthored", ",", "arrPayingAddresses", ",", "function", "(", "err", ",", "arrMoreMessages", ",", "assocMorePrivatePayloads", ")", "{", "console", ".", "log", "(", "\"fnRetrieveMessages callback: err code = \"", "+", "(", "err", "?", "err", ".", "error_code", ":", "\"\"", ")", ")", ";", "if", "(", "err", ")", "return", "cb", "(", "(", "typeof", "err", "===", "\"string\"", ")", "?", "(", "\"unable to add additional messages: \"", "+", "err", ")", ":", "err", ")", ";", "Array", ".", "prototype", ".", "push", ".", "apply", "(", "objUnit", ".", "messages", ",", "arrMoreMessages", ")", ";", "if", "(", "assocMorePrivatePayloads", "&&", "Object", ".", "keys", "(", "assocMorePrivatePayloads", ")", ".", "length", ">", "0", ")", "for", "(", "var", "payload_hash", "in", "assocMorePrivatePayloads", ")", "assocPrivatePayloads", "[", "payload_hash", "]", "=", "assocMorePrivatePayloads", "[", "payload_hash", "]", ";", "cb", "(", ")", ";", "}", ")", ";", "}" ]
messages retrieved via callback
[ "messages", "retrieved", "via", "callback" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/composer.js#L385-L399
15,246
byteball/ocore
storage.js
readJointWithBall
function readJointWithBall(conn, unit, handleJoint) { readJoint(conn, unit, { ifNotFound: function(){ throw Error("joint not found, unit "+unit); }, ifFound: function(objJoint){ if (objJoint.ball) return handleJoint(objJoint); conn.query("SELECT ball FROM balls WHERE unit=?", [unit], function(rows){ if (rows.length === 1) objJoint.ball = rows[0].ball; handleJoint(objJoint); }); } }); }
javascript
function readJointWithBall(conn, unit, handleJoint) { readJoint(conn, unit, { ifNotFound: function(){ throw Error("joint not found, unit "+unit); }, ifFound: function(objJoint){ if (objJoint.ball) return handleJoint(objJoint); conn.query("SELECT ball FROM balls WHERE unit=?", [unit], function(rows){ if (rows.length === 1) objJoint.ball = rows[0].ball; handleJoint(objJoint); }); } }); }
[ "function", "readJointWithBall", "(", "conn", ",", "unit", ",", "handleJoint", ")", "{", "readJoint", "(", "conn", ",", "unit", ",", "{", "ifNotFound", ":", "function", "(", ")", "{", "throw", "Error", "(", "\"joint not found, unit \"", "+", "unit", ")", ";", "}", ",", "ifFound", ":", "function", "(", "objJoint", ")", "{", "if", "(", "objJoint", ".", "ball", ")", "return", "handleJoint", "(", "objJoint", ")", ";", "conn", ".", "query", "(", "\"SELECT ball FROM balls WHERE unit=?\"", ",", "[", "unit", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "===", "1", ")", "objJoint", ".", "ball", "=", "rows", "[", "0", "]", ".", "ball", ";", "handleJoint", "(", "objJoint", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
add .ball even if it is not retrievable
[ "add", ".", "ball", "even", "if", "it", "is", "not", "retrievable" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/storage.js#L524-L539
15,247
byteball/ocore
storage.js
determineBestParent
function determineBestParent(conn, objUnit, arrWitnesses, handleBestParent){ // choose best parent among compatible parents only conn.query( "SELECT unit \n\ FROM units AS parent_units \n\ WHERE unit IN(?) \n\ AND (witness_list_unit=? OR ( \n\ SELECT COUNT(*) \n\ FROM unit_witnesses AS parent_witnesses \n\ WHERE parent_witnesses.unit IN(parent_units.unit, parent_units.witness_list_unit) AND address IN(?) \n\ )>=?) \n\ ORDER BY witnessed_level DESC, \n\ level-witnessed_level ASC, \n\ unit ASC \n\ LIMIT 1", [objUnit.parent_units, objUnit.witness_list_unit, arrWitnesses, constants.COUNT_WITNESSES - constants.MAX_WITNESS_LIST_MUTATIONS], function(rows){ if (rows.length !== 1) return handleBestParent(null); var best_parent_unit = rows[0].unit; handleBestParent(best_parent_unit); } ); }
javascript
function determineBestParent(conn, objUnit, arrWitnesses, handleBestParent){ // choose best parent among compatible parents only conn.query( "SELECT unit \n\ FROM units AS parent_units \n\ WHERE unit IN(?) \n\ AND (witness_list_unit=? OR ( \n\ SELECT COUNT(*) \n\ FROM unit_witnesses AS parent_witnesses \n\ WHERE parent_witnesses.unit IN(parent_units.unit, parent_units.witness_list_unit) AND address IN(?) \n\ )>=?) \n\ ORDER BY witnessed_level DESC, \n\ level-witnessed_level ASC, \n\ unit ASC \n\ LIMIT 1", [objUnit.parent_units, objUnit.witness_list_unit, arrWitnesses, constants.COUNT_WITNESSES - constants.MAX_WITNESS_LIST_MUTATIONS], function(rows){ if (rows.length !== 1) return handleBestParent(null); var best_parent_unit = rows[0].unit; handleBestParent(best_parent_unit); } ); }
[ "function", "determineBestParent", "(", "conn", ",", "objUnit", ",", "arrWitnesses", ",", "handleBestParent", ")", "{", "// choose best parent among compatible parents only", "conn", ".", "query", "(", "\"SELECT unit \\n\\\n\t\tFROM units AS parent_units \\n\\\n\t\tWHERE unit IN(?) \\n\\\n\t\t\tAND (witness_list_unit=? OR ( \\n\\\n\t\t\t\tSELECT COUNT(*) \\n\\\n\t\t\t\tFROM unit_witnesses AS parent_witnesses \\n\\\n\t\t\t\tWHERE parent_witnesses.unit IN(parent_units.unit, parent_units.witness_list_unit) AND address IN(?) \\n\\\n\t\t\t)>=?) \\n\\\n\t\tORDER BY witnessed_level DESC, \\n\\\n\t\t\tlevel-witnessed_level ASC, \\n\\\n\t\t\tunit ASC \\n\\\n\t\tLIMIT 1\"", ",", "[", "objUnit", ".", "parent_units", ",", "objUnit", ".", "witness_list_unit", ",", "arrWitnesses", ",", "constants", ".", "COUNT_WITNESSES", "-", "constants", ".", "MAX_WITNESS_LIST_MUTATIONS", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "!==", "1", ")", "return", "handleBestParent", "(", "null", ")", ";", "var", "best_parent_unit", "=", "rows", "[", "0", "]", ".", "unit", ";", "handleBestParent", "(", "best_parent_unit", ")", ";", "}", ")", ";", "}" ]
for unit that is not saved to the db yet
[ "for", "unit", "that", "is", "not", "saved", "to", "the", "db", "yet" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/storage.js#L1145-L1169
15,248
byteball/ocore
storage.js
buildListOfMcUnitsWithPotentiallyDifferentWitnesslists
function buildListOfMcUnitsWithPotentiallyDifferentWitnesslists(conn, objUnit, last_ball_unit, arrWitnesses, handleList){ function addAndGoUp(unit){ readStaticUnitProps(conn, unit, function(props){ // the parent has the same witness list and the parent has already passed the MC compatibility test if (objUnit.witness_list_unit && objUnit.witness_list_unit === props.witness_list_unit) return handleList(true, arrMcUnits); else arrMcUnits.push(unit); if (unit === last_ball_unit) return handleList(true, arrMcUnits); if (!props.best_parent_unit) throw Error("no best parent of unit "+unit+"?"); addAndGoUp(props.best_parent_unit); }); } var arrMcUnits = []; determineBestParent(conn, objUnit, arrWitnesses, function(best_parent_unit){ if (!best_parent_unit) return handleList(false); addAndGoUp(best_parent_unit); }); }
javascript
function buildListOfMcUnitsWithPotentiallyDifferentWitnesslists(conn, objUnit, last_ball_unit, arrWitnesses, handleList){ function addAndGoUp(unit){ readStaticUnitProps(conn, unit, function(props){ // the parent has the same witness list and the parent has already passed the MC compatibility test if (objUnit.witness_list_unit && objUnit.witness_list_unit === props.witness_list_unit) return handleList(true, arrMcUnits); else arrMcUnits.push(unit); if (unit === last_ball_unit) return handleList(true, arrMcUnits); if (!props.best_parent_unit) throw Error("no best parent of unit "+unit+"?"); addAndGoUp(props.best_parent_unit); }); } var arrMcUnits = []; determineBestParent(conn, objUnit, arrWitnesses, function(best_parent_unit){ if (!best_parent_unit) return handleList(false); addAndGoUp(best_parent_unit); }); }
[ "function", "buildListOfMcUnitsWithPotentiallyDifferentWitnesslists", "(", "conn", ",", "objUnit", ",", "last_ball_unit", ",", "arrWitnesses", ",", "handleList", ")", "{", "function", "addAndGoUp", "(", "unit", ")", "{", "readStaticUnitProps", "(", "conn", ",", "unit", ",", "function", "(", "props", ")", "{", "// the parent has the same witness list and the parent has already passed the MC compatibility test", "if", "(", "objUnit", ".", "witness_list_unit", "&&", "objUnit", ".", "witness_list_unit", "===", "props", ".", "witness_list_unit", ")", "return", "handleList", "(", "true", ",", "arrMcUnits", ")", ";", "else", "arrMcUnits", ".", "push", "(", "unit", ")", ";", "if", "(", "unit", "===", "last_ball_unit", ")", "return", "handleList", "(", "true", ",", "arrMcUnits", ")", ";", "if", "(", "!", "props", ".", "best_parent_unit", ")", "throw", "Error", "(", "\"no best parent of unit \"", "+", "unit", "+", "\"?\"", ")", ";", "addAndGoUp", "(", "props", ".", "best_parent_unit", ")", ";", "}", ")", ";", "}", "var", "arrMcUnits", "=", "[", "]", ";", "determineBestParent", "(", "conn", ",", "objUnit", ",", "arrWitnesses", ",", "function", "(", "best_parent_unit", ")", "{", "if", "(", "!", "best_parent_unit", ")", "return", "handleList", "(", "false", ")", ";", "addAndGoUp", "(", "best_parent_unit", ")", ";", "}", ")", ";", "}" ]
the MC for this function is the MC built from this unit, not our current MC
[ "the", "MC", "for", "this", "function", "is", "the", "MC", "built", "from", "this", "unit", "not", "our", "current", "MC" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/storage.js#L1198-L1221
15,249
byteball/ocore
private_profile.js
savePrivateProfile
function savePrivateProfile(objPrivateProfile, address, attestor_address, onDone){ db.query( "INSERT "+db.getIgnore()+" INTO private_profiles (unit, payload_hash, attestor_address, address, src_profile) VALUES(?,?,?,?,?)", [objPrivateProfile.unit, objPrivateProfile.payload_hash, attestor_address, address, JSON.stringify(objPrivateProfile.src_profile)], function (res) { var private_profile_id = (res.insertId && res.affectedRows) ? res.insertId : 0; var insert_fields = function(current_src_profile) { var arrQueries = []; var isSrcProfileUpdated = false; for (var field in objPrivateProfile.src_profile){ var arrValueAndBlinding = objPrivateProfile.src_profile[field]; if (ValidationUtils.isArrayOfLength(arrValueAndBlinding, 2)) { if (!current_src_profile || !current_src_profile[field] || !ValidationUtils.isArrayOfLength(current_src_profile[field], 2)) { if (current_src_profile) { isSrcProfileUpdated = true; current_src_profile[field] = arrValueAndBlinding; } db.addQuery(arrQueries, "INSERT INTO private_profile_fields (private_profile_id, field, value, blinding) VALUES(?,?,?,?)", [private_profile_id, field, arrValueAndBlinding[0], arrValueAndBlinding[1] ]); } } } if (isSrcProfileUpdated) db.addQuery(arrQueries, "UPDATE private_profiles SET src_profile=? WHERE private_profile_id=?", [JSON.stringify(current_src_profile), private_profile_id]); async.series(arrQueries, onDone); } if (!private_profile_id) { // already saved profile but with new fields being revealed db.query("SELECT private_profile_id, src_profile FROM private_profiles WHERE payload_hash=?", [objPrivateProfile.payload_hash], function(rows) { if (!rows.length) throw Error("can't insert private profile "+JSON.stringify(objPrivateProfile)); private_profile_id = rows[0].private_profile_id; var src_profile = JSON.parse(rows[0].src_profile); insert_fields(src_profile); }); } else insert_fields(); } ); }
javascript
function savePrivateProfile(objPrivateProfile, address, attestor_address, onDone){ db.query( "INSERT "+db.getIgnore()+" INTO private_profiles (unit, payload_hash, attestor_address, address, src_profile) VALUES(?,?,?,?,?)", [objPrivateProfile.unit, objPrivateProfile.payload_hash, attestor_address, address, JSON.stringify(objPrivateProfile.src_profile)], function (res) { var private_profile_id = (res.insertId && res.affectedRows) ? res.insertId : 0; var insert_fields = function(current_src_profile) { var arrQueries = []; var isSrcProfileUpdated = false; for (var field in objPrivateProfile.src_profile){ var arrValueAndBlinding = objPrivateProfile.src_profile[field]; if (ValidationUtils.isArrayOfLength(arrValueAndBlinding, 2)) { if (!current_src_profile || !current_src_profile[field] || !ValidationUtils.isArrayOfLength(current_src_profile[field], 2)) { if (current_src_profile) { isSrcProfileUpdated = true; current_src_profile[field] = arrValueAndBlinding; } db.addQuery(arrQueries, "INSERT INTO private_profile_fields (private_profile_id, field, value, blinding) VALUES(?,?,?,?)", [private_profile_id, field, arrValueAndBlinding[0], arrValueAndBlinding[1] ]); } } } if (isSrcProfileUpdated) db.addQuery(arrQueries, "UPDATE private_profiles SET src_profile=? WHERE private_profile_id=?", [JSON.stringify(current_src_profile), private_profile_id]); async.series(arrQueries, onDone); } if (!private_profile_id) { // already saved profile but with new fields being revealed db.query("SELECT private_profile_id, src_profile FROM private_profiles WHERE payload_hash=?", [objPrivateProfile.payload_hash], function(rows) { if (!rows.length) throw Error("can't insert private profile "+JSON.stringify(objPrivateProfile)); private_profile_id = rows[0].private_profile_id; var src_profile = JSON.parse(rows[0].src_profile); insert_fields(src_profile); }); } else insert_fields(); } ); }
[ "function", "savePrivateProfile", "(", "objPrivateProfile", ",", "address", ",", "attestor_address", ",", "onDone", ")", "{", "db", ".", "query", "(", "\"INSERT \"", "+", "db", ".", "getIgnore", "(", ")", "+", "\" INTO private_profiles (unit, payload_hash, attestor_address, address, src_profile) VALUES(?,?,?,?,?)\"", ",", "[", "objPrivateProfile", ".", "unit", ",", "objPrivateProfile", ".", "payload_hash", ",", "attestor_address", ",", "address", ",", "JSON", ".", "stringify", "(", "objPrivateProfile", ".", "src_profile", ")", "]", ",", "function", "(", "res", ")", "{", "var", "private_profile_id", "=", "(", "res", ".", "insertId", "&&", "res", ".", "affectedRows", ")", "?", "res", ".", "insertId", ":", "0", ";", "var", "insert_fields", "=", "function", "(", "current_src_profile", ")", "{", "var", "arrQueries", "=", "[", "]", ";", "var", "isSrcProfileUpdated", "=", "false", ";", "for", "(", "var", "field", "in", "objPrivateProfile", ".", "src_profile", ")", "{", "var", "arrValueAndBlinding", "=", "objPrivateProfile", ".", "src_profile", "[", "field", "]", ";", "if", "(", "ValidationUtils", ".", "isArrayOfLength", "(", "arrValueAndBlinding", ",", "2", ")", ")", "{", "if", "(", "!", "current_src_profile", "||", "!", "current_src_profile", "[", "field", "]", "||", "!", "ValidationUtils", ".", "isArrayOfLength", "(", "current_src_profile", "[", "field", "]", ",", "2", ")", ")", "{", "if", "(", "current_src_profile", ")", "{", "isSrcProfileUpdated", "=", "true", ";", "current_src_profile", "[", "field", "]", "=", "arrValueAndBlinding", ";", "}", "db", ".", "addQuery", "(", "arrQueries", ",", "\"INSERT INTO private_profile_fields (private_profile_id, field, value, blinding) VALUES(?,?,?,?)\"", ",", "[", "private_profile_id", ",", "field", ",", "arrValueAndBlinding", "[", "0", "]", ",", "arrValueAndBlinding", "[", "1", "]", "]", ")", ";", "}", "}", "}", "if", "(", "isSrcProfileUpdated", ")", "db", ".", "addQuery", "(", "arrQueries", ",", "\"UPDATE private_profiles SET src_profile=? WHERE private_profile_id=?\"", ",", "[", "JSON", ".", "stringify", "(", "current_src_profile", ")", ",", "private_profile_id", "]", ")", ";", "async", ".", "series", "(", "arrQueries", ",", "onDone", ")", ";", "}", "if", "(", "!", "private_profile_id", ")", "{", "// already saved profile but with new fields being revealed", "db", ".", "query", "(", "\"SELECT private_profile_id, src_profile FROM private_profiles WHERE payload_hash=?\"", ",", "[", "objPrivateProfile", ".", "payload_hash", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "!", "rows", ".", "length", ")", "throw", "Error", "(", "\"can't insert private profile \"", "+", "JSON", ".", "stringify", "(", "objPrivateProfile", ")", ")", ";", "private_profile_id", "=", "rows", "[", "0", "]", ".", "private_profile_id", ";", "var", "src_profile", "=", "JSON", ".", "parse", "(", "rows", "[", "0", "]", ".", "src_profile", ")", ";", "insert_fields", "(", "src_profile", ")", ";", "}", ")", ";", "}", "else", "insert_fields", "(", ")", ";", "}", ")", ";", "}" ]
the profile can be mine or peer's
[ "the", "profile", "can", "be", "mine", "or", "peer", "s" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/private_profile.js#L97-L139
15,250
byteball/ocore
writer.js
updateWitnessedLevelByWitnesslist
function updateWitnessedLevelByWitnesslist(arrWitnesses, cb){ var arrCollectedWitnesses = []; function setWitnessedLevel(witnessed_level){ profiler.start(); if (witnessed_level !== objValidationState.witnessed_level) throwError("different witnessed levels, validation: "+objValidationState.witnessed_level+", writer: "+witnessed_level); objNewUnitProps.witnessed_level = witnessed_level; conn.query("UPDATE units SET witnessed_level=? WHERE unit=?", [witnessed_level, objUnit.unit], function(){ profiler.stop('write-wl-update'); cb(); }); } function addWitnessesAndGoUp(start_unit){ profiler.start(); storage.readStaticUnitProps(conn, start_unit, function(props){ profiler.stop('write-wl-select-bp'); var best_parent_unit = props.best_parent_unit; var level = props.level; if (level === null) throw Error("null level in updateWitnessedLevel"); if (level === 0) // genesis return setWitnessedLevel(0); profiler.start(); storage.readUnitAuthors(conn, start_unit, function(arrAuthors){ profiler.stop('write-wl-select-authors'); profiler.start(); for (var i=0; i<arrAuthors.length; i++){ var address = arrAuthors[i]; if (arrWitnesses.indexOf(address) !== -1 && arrCollectedWitnesses.indexOf(address) === -1) arrCollectedWitnesses.push(address); } profiler.stop('write-wl-search'); (arrCollectedWitnesses.length < constants.MAJORITY_OF_WITNESSES) ? addWitnessesAndGoUp(best_parent_unit) : setWitnessedLevel(level); }); }); } profiler.stop('write-update'); addWitnessesAndGoUp(my_best_parent_unit); }
javascript
function updateWitnessedLevelByWitnesslist(arrWitnesses, cb){ var arrCollectedWitnesses = []; function setWitnessedLevel(witnessed_level){ profiler.start(); if (witnessed_level !== objValidationState.witnessed_level) throwError("different witnessed levels, validation: "+objValidationState.witnessed_level+", writer: "+witnessed_level); objNewUnitProps.witnessed_level = witnessed_level; conn.query("UPDATE units SET witnessed_level=? WHERE unit=?", [witnessed_level, objUnit.unit], function(){ profiler.stop('write-wl-update'); cb(); }); } function addWitnessesAndGoUp(start_unit){ profiler.start(); storage.readStaticUnitProps(conn, start_unit, function(props){ profiler.stop('write-wl-select-bp'); var best_parent_unit = props.best_parent_unit; var level = props.level; if (level === null) throw Error("null level in updateWitnessedLevel"); if (level === 0) // genesis return setWitnessedLevel(0); profiler.start(); storage.readUnitAuthors(conn, start_unit, function(arrAuthors){ profiler.stop('write-wl-select-authors'); profiler.start(); for (var i=0; i<arrAuthors.length; i++){ var address = arrAuthors[i]; if (arrWitnesses.indexOf(address) !== -1 && arrCollectedWitnesses.indexOf(address) === -1) arrCollectedWitnesses.push(address); } profiler.stop('write-wl-search'); (arrCollectedWitnesses.length < constants.MAJORITY_OF_WITNESSES) ? addWitnessesAndGoUp(best_parent_unit) : setWitnessedLevel(level); }); }); } profiler.stop('write-update'); addWitnessesAndGoUp(my_best_parent_unit); }
[ "function", "updateWitnessedLevelByWitnesslist", "(", "arrWitnesses", ",", "cb", ")", "{", "var", "arrCollectedWitnesses", "=", "[", "]", ";", "function", "setWitnessedLevel", "(", "witnessed_level", ")", "{", "profiler", ".", "start", "(", ")", ";", "if", "(", "witnessed_level", "!==", "objValidationState", ".", "witnessed_level", ")", "throwError", "(", "\"different witnessed levels, validation: \"", "+", "objValidationState", ".", "witnessed_level", "+", "\", writer: \"", "+", "witnessed_level", ")", ";", "objNewUnitProps", ".", "witnessed_level", "=", "witnessed_level", ";", "conn", ".", "query", "(", "\"UPDATE units SET witnessed_level=? WHERE unit=?\"", ",", "[", "witnessed_level", ",", "objUnit", ".", "unit", "]", ",", "function", "(", ")", "{", "profiler", ".", "stop", "(", "'write-wl-update'", ")", ";", "cb", "(", ")", ";", "}", ")", ";", "}", "function", "addWitnessesAndGoUp", "(", "start_unit", ")", "{", "profiler", ".", "start", "(", ")", ";", "storage", ".", "readStaticUnitProps", "(", "conn", ",", "start_unit", ",", "function", "(", "props", ")", "{", "profiler", ".", "stop", "(", "'write-wl-select-bp'", ")", ";", "var", "best_parent_unit", "=", "props", ".", "best_parent_unit", ";", "var", "level", "=", "props", ".", "level", ";", "if", "(", "level", "===", "null", ")", "throw", "Error", "(", "\"null level in updateWitnessedLevel\"", ")", ";", "if", "(", "level", "===", "0", ")", "// genesis", "return", "setWitnessedLevel", "(", "0", ")", ";", "profiler", ".", "start", "(", ")", ";", "storage", ".", "readUnitAuthors", "(", "conn", ",", "start_unit", ",", "function", "(", "arrAuthors", ")", "{", "profiler", ".", "stop", "(", "'write-wl-select-authors'", ")", ";", "profiler", ".", "start", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arrAuthors", ".", "length", ";", "i", "++", ")", "{", "var", "address", "=", "arrAuthors", "[", "i", "]", ";", "if", "(", "arrWitnesses", ".", "indexOf", "(", "address", ")", "!==", "-", "1", "&&", "arrCollectedWitnesses", ".", "indexOf", "(", "address", ")", "===", "-", "1", ")", "arrCollectedWitnesses", ".", "push", "(", "address", ")", ";", "}", "profiler", ".", "stop", "(", "'write-wl-search'", ")", ";", "(", "arrCollectedWitnesses", ".", "length", "<", "constants", ".", "MAJORITY_OF_WITNESSES", ")", "?", "addWitnessesAndGoUp", "(", "best_parent_unit", ")", ":", "setWitnessedLevel", "(", "level", ")", ";", "}", ")", ";", "}", ")", ";", "}", "profiler", ".", "stop", "(", "'write-update'", ")", ";", "addWitnessesAndGoUp", "(", "my_best_parent_unit", ")", ";", "}" ]
The level at which we collect at least 7 distinct witnesses while walking up the main chain from our unit. The unit itself is not counted even if it is authored by a witness
[ "The", "level", "at", "which", "we", "collect", "at", "least", "7", "distinct", "witnesses", "while", "walking", "up", "the", "main", "chain", "from", "our", "unit", ".", "The", "unit", "itself", "is", "not", "counted", "even", "if", "it", "is", "authored", "by", "a", "witness" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/writer.js#L453-L495
15,251
byteball/ocore
wallet_defined_by_addresses.js
sendToPeerAllSharedAddressesHavingUnspentOutputs
function sendToPeerAllSharedAddressesHavingUnspentOutputs(device_address, asset, callbacks){ var asset_filter = !asset || asset == "base" ? " AND outputs.asset IS NULL " : " AND outputs.asset='"+asset+"'"; db.query( "SELECT DISTINCT shared_address FROM shared_address_signing_paths CROSS JOIN outputs ON shared_address_signing_paths.shared_address=outputs.address\n\ WHERE device_address=? AND outputs.is_spent=0" + asset_filter, [device_address], function(rows){ if (rows.length === 0) return callbacks.ifNoFundedSharedAddress(); rows.forEach(function(row){ sendSharedAddressToPeer(device_address, row.shared_address, function(err){ if (err) return console.log(err) console.log("Definition for " + row.shared_address + " will be sent to " + device_address); }); }); return callbacks.ifFundedSharedAddress(rows.length); }); }
javascript
function sendToPeerAllSharedAddressesHavingUnspentOutputs(device_address, asset, callbacks){ var asset_filter = !asset || asset == "base" ? " AND outputs.asset IS NULL " : " AND outputs.asset='"+asset+"'"; db.query( "SELECT DISTINCT shared_address FROM shared_address_signing_paths CROSS JOIN outputs ON shared_address_signing_paths.shared_address=outputs.address\n\ WHERE device_address=? AND outputs.is_spent=0" + asset_filter, [device_address], function(rows){ if (rows.length === 0) return callbacks.ifNoFundedSharedAddress(); rows.forEach(function(row){ sendSharedAddressToPeer(device_address, row.shared_address, function(err){ if (err) return console.log(err) console.log("Definition for " + row.shared_address + " will be sent to " + device_address); }); }); return callbacks.ifFundedSharedAddress(rows.length); }); }
[ "function", "sendToPeerAllSharedAddressesHavingUnspentOutputs", "(", "device_address", ",", "asset", ",", "callbacks", ")", "{", "var", "asset_filter", "=", "!", "asset", "||", "asset", "==", "\"base\"", "?", "\" AND outputs.asset IS NULL \"", ":", "\" AND outputs.asset='\"", "+", "asset", "+", "\"'\"", ";", "db", ".", "query", "(", "\"SELECT DISTINCT shared_address FROM shared_address_signing_paths CROSS JOIN outputs ON shared_address_signing_paths.shared_address=outputs.address\\n\\\n\t\t WHERE device_address=? AND outputs.is_spent=0\"", "+", "asset_filter", ",", "[", "device_address", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "===", "0", ")", "return", "callbacks", ".", "ifNoFundedSharedAddress", "(", ")", ";", "rows", ".", "forEach", "(", "function", "(", "row", ")", "{", "sendSharedAddressToPeer", "(", "device_address", ",", "row", ".", "shared_address", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "console", ".", "log", "(", "err", ")", "console", ".", "log", "(", "\"Definition for \"", "+", "row", ".", "shared_address", "+", "\" will be sent to \"", "+", "device_address", ")", ";", "}", ")", ";", "}", ")", ";", "return", "callbacks", ".", "ifFundedSharedAddress", "(", "rows", ".", "length", ")", ";", "}", ")", ";", "}" ]
when a peer has lost shared address definitions after a wallet recovery, we can resend them
[ "when", "a", "peer", "has", "lost", "shared", "address", "definitions", "after", "a", "wallet", "recovery", "we", "can", "resend", "them" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/wallet_defined_by_addresses.js#L52-L68
15,252
byteball/ocore
wallet_defined_by_addresses.js
sendSharedAddressToPeer
function sendSharedAddressToPeer(device_address, shared_address, handle){ var arrDefinition; var assocSignersByPath={}; async.series([ function(cb){ db.query("SELECT definition FROM shared_addresses WHERE shared_address=?", [shared_address], function(rows){ if (!rows[0]) return cb("Definition not found for " + shared_address); arrDefinition = JSON.parse(rows[0].definition); return cb(null); }); }, function(cb){ db.query("SELECT signing_path,address,member_signing_path,device_address FROM shared_address_signing_paths WHERE shared_address=?", [shared_address], function(rows){ if (rows.length<2) return cb("Less than 2 signing paths found for " + shared_address); rows.forEach(function(row){ assocSignersByPath[row.signing_path] = {address: row.address, member_signing_path: row.member_signing_path, device_address: row.device_address}; }); return cb(null); }); } ], function(err){ if (err) return handle(err); sendNewSharedAddress(device_address, shared_address, arrDefinition, assocSignersByPath); return handle(null); }); }
javascript
function sendSharedAddressToPeer(device_address, shared_address, handle){ var arrDefinition; var assocSignersByPath={}; async.series([ function(cb){ db.query("SELECT definition FROM shared_addresses WHERE shared_address=?", [shared_address], function(rows){ if (!rows[0]) return cb("Definition not found for " + shared_address); arrDefinition = JSON.parse(rows[0].definition); return cb(null); }); }, function(cb){ db.query("SELECT signing_path,address,member_signing_path,device_address FROM shared_address_signing_paths WHERE shared_address=?", [shared_address], function(rows){ if (rows.length<2) return cb("Less than 2 signing paths found for " + shared_address); rows.forEach(function(row){ assocSignersByPath[row.signing_path] = {address: row.address, member_signing_path: row.member_signing_path, device_address: row.device_address}; }); return cb(null); }); } ], function(err){ if (err) return handle(err); sendNewSharedAddress(device_address, shared_address, arrDefinition, assocSignersByPath); return handle(null); }); }
[ "function", "sendSharedAddressToPeer", "(", "device_address", ",", "shared_address", ",", "handle", ")", "{", "var", "arrDefinition", ";", "var", "assocSignersByPath", "=", "{", "}", ";", "async", ".", "series", "(", "[", "function", "(", "cb", ")", "{", "db", ".", "query", "(", "\"SELECT definition FROM shared_addresses WHERE shared_address=?\"", ",", "[", "shared_address", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "!", "rows", "[", "0", "]", ")", "return", "cb", "(", "\"Definition not found for \"", "+", "shared_address", ")", ";", "arrDefinition", "=", "JSON", ".", "parse", "(", "rows", "[", "0", "]", ".", "definition", ")", ";", "return", "cb", "(", "null", ")", ";", "}", ")", ";", "}", ",", "function", "(", "cb", ")", "{", "db", ".", "query", "(", "\"SELECT signing_path,address,member_signing_path,device_address FROM shared_address_signing_paths WHERE shared_address=?\"", ",", "[", "shared_address", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "<", "2", ")", "return", "cb", "(", "\"Less than 2 signing paths found for \"", "+", "shared_address", ")", ";", "rows", ".", "forEach", "(", "function", "(", "row", ")", "{", "assocSignersByPath", "[", "row", ".", "signing_path", "]", "=", "{", "address", ":", "row", ".", "address", ",", "member_signing_path", ":", "row", ".", "member_signing_path", ",", "device_address", ":", "row", ".", "device_address", "}", ";", "}", ")", ";", "return", "cb", "(", "null", ")", ";", "}", ")", ";", "}", "]", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "handle", "(", "err", ")", ";", "sendNewSharedAddress", "(", "device_address", ",", "shared_address", ",", "arrDefinition", ",", "assocSignersByPath", ")", ";", "return", "handle", "(", "null", ")", ";", "}", ")", ";", "}" ]
read shared address definition and signing paths then send them to peer
[ "read", "shared", "address", "definition", "and", "signing", "paths", "then", "send", "them", "to", "peer" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/wallet_defined_by_addresses.js#L71-L100
15,253
byteball/ocore
wallet_defined_by_addresses.js
addNewSharedAddress
function addNewSharedAddress(address, arrDefinition, assocSignersByPath, bForwarded, onDone){ // network.addWatchedAddress(address); db.query( "INSERT "+db.getIgnore()+" INTO shared_addresses (shared_address, definition) VALUES (?,?)", [address, JSON.stringify(arrDefinition)], function(){ var arrQueries = []; for (var signing_path in assocSignersByPath){ var signerInfo = assocSignersByPath[signing_path]; db.addQuery(arrQueries, "INSERT "+db.getIgnore()+" INTO shared_address_signing_paths \n\ (shared_address, address, signing_path, member_signing_path, device_address) VALUES (?,?,?,?,?)", [address, signerInfo.address, signing_path, signerInfo.member_signing_path, signerInfo.device_address]); } async.series(arrQueries, function(){ console.log('added new shared address '+address); eventBus.emit("new_address-"+address); if (conf.bLight) network.addLightWatchedAddress(address); if (!bForwarded) forwardNewSharedAddressToCosignersOfMyMemberAddresses(address, arrDefinition, assocSignersByPath); if (onDone) onDone(); }); } ); }
javascript
function addNewSharedAddress(address, arrDefinition, assocSignersByPath, bForwarded, onDone){ // network.addWatchedAddress(address); db.query( "INSERT "+db.getIgnore()+" INTO shared_addresses (shared_address, definition) VALUES (?,?)", [address, JSON.stringify(arrDefinition)], function(){ var arrQueries = []; for (var signing_path in assocSignersByPath){ var signerInfo = assocSignersByPath[signing_path]; db.addQuery(arrQueries, "INSERT "+db.getIgnore()+" INTO shared_address_signing_paths \n\ (shared_address, address, signing_path, member_signing_path, device_address) VALUES (?,?,?,?,?)", [address, signerInfo.address, signing_path, signerInfo.member_signing_path, signerInfo.device_address]); } async.series(arrQueries, function(){ console.log('added new shared address '+address); eventBus.emit("new_address-"+address); if (conf.bLight) network.addLightWatchedAddress(address); if (!bForwarded) forwardNewSharedAddressToCosignersOfMyMemberAddresses(address, arrDefinition, assocSignersByPath); if (onDone) onDone(); }); } ); }
[ "function", "addNewSharedAddress", "(", "address", ",", "arrDefinition", ",", "assocSignersByPath", ",", "bForwarded", ",", "onDone", ")", "{", "//\tnetwork.addWatchedAddress(address);", "db", ".", "query", "(", "\"INSERT \"", "+", "db", ".", "getIgnore", "(", ")", "+", "\" INTO shared_addresses (shared_address, definition) VALUES (?,?)\"", ",", "[", "address", ",", "JSON", ".", "stringify", "(", "arrDefinition", ")", "]", ",", "function", "(", ")", "{", "var", "arrQueries", "=", "[", "]", ";", "for", "(", "var", "signing_path", "in", "assocSignersByPath", ")", "{", "var", "signerInfo", "=", "assocSignersByPath", "[", "signing_path", "]", ";", "db", ".", "addQuery", "(", "arrQueries", ",", "\"INSERT \"", "+", "db", ".", "getIgnore", "(", ")", "+", "\" INTO shared_address_signing_paths \\n\\\n\t\t\t\t\t(shared_address, address, signing_path, member_signing_path, device_address) VALUES (?,?,?,?,?)\"", ",", "[", "address", ",", "signerInfo", ".", "address", ",", "signing_path", ",", "signerInfo", ".", "member_signing_path", ",", "signerInfo", ".", "device_address", "]", ")", ";", "}", "async", ".", "series", "(", "arrQueries", ",", "function", "(", ")", "{", "console", ".", "log", "(", "'added new shared address '", "+", "address", ")", ";", "eventBus", ".", "emit", "(", "\"new_address-\"", "+", "address", ")", ";", "if", "(", "conf", ".", "bLight", ")", "network", ".", "addLightWatchedAddress", "(", "address", ")", ";", "if", "(", "!", "bForwarded", ")", "forwardNewSharedAddressToCosignersOfMyMemberAddresses", "(", "address", ",", "arrDefinition", ",", "assocSignersByPath", ")", ";", "if", "(", "onDone", ")", "onDone", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
called from network after the initiator collects approvals from all members of the address and then sends the completed address to all members member_signing_path is now deprecated and unused shared_address_signing_paths.signing_path is now path to member-address, not full path to a signing key
[ "called", "from", "network", "after", "the", "initiator", "collects", "approvals", "from", "all", "members", "of", "the", "address", "and", "then", "sends", "the", "completed", "address", "to", "all", "members", "member_signing_path", "is", "now", "deprecated", "and", "unused", "shared_address_signing_paths", ".", "signing_path", "is", "now", "path", "to", "member", "-", "address", "not", "full", "path", "to", "a", "signing", "key" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/wallet_defined_by_addresses.js#L239-L265
15,254
byteball/ocore
wallet_defined_by_addresses.js
readSharedAddressCosigners
function readSharedAddressCosigners(shared_address, handleCosigners){ db.query( "SELECT DISTINCT shared_address_signing_paths.device_address, name, "+db.getUnixTimestamp("shared_addresses.creation_date")+" AS creation_ts \n\ FROM shared_address_signing_paths \n\ JOIN shared_addresses USING(shared_address) \n\ LEFT JOIN correspondent_devices USING(device_address) \n\ WHERE shared_address=? AND device_address!=?", [shared_address, device.getMyDeviceAddress()], function(rows){ if (rows.length === 0) throw Error("no cosigners found for shared address "+shared_address); handleCosigners(rows); } ); }
javascript
function readSharedAddressCosigners(shared_address, handleCosigners){ db.query( "SELECT DISTINCT shared_address_signing_paths.device_address, name, "+db.getUnixTimestamp("shared_addresses.creation_date")+" AS creation_ts \n\ FROM shared_address_signing_paths \n\ JOIN shared_addresses USING(shared_address) \n\ LEFT JOIN correspondent_devices USING(device_address) \n\ WHERE shared_address=? AND device_address!=?", [shared_address, device.getMyDeviceAddress()], function(rows){ if (rows.length === 0) throw Error("no cosigners found for shared address "+shared_address); handleCosigners(rows); } ); }
[ "function", "readSharedAddressCosigners", "(", "shared_address", ",", "handleCosigners", ")", "{", "db", ".", "query", "(", "\"SELECT DISTINCT shared_address_signing_paths.device_address, name, \"", "+", "db", ".", "getUnixTimestamp", "(", "\"shared_addresses.creation_date\"", ")", "+", "\" AS creation_ts \\n\\\n\t\tFROM shared_address_signing_paths \\n\\\n\t\tJOIN shared_addresses USING(shared_address) \\n\\\n\t\tLEFT JOIN correspondent_devices USING(device_address) \\n\\\n\t\tWHERE shared_address=? AND device_address!=?\"", ",", "[", "shared_address", ",", "device", ".", "getMyDeviceAddress", "(", ")", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "===", "0", ")", "throw", "Error", "(", "\"no cosigners found for shared address \"", "+", "shared_address", ")", ";", "handleCosigners", "(", "rows", ")", ";", "}", ")", ";", "}" ]
returns information about cosigner devices
[ "returns", "information", "about", "cosigner", "devices" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/wallet_defined_by_addresses.js#L528-L542
15,255
byteball/ocore
wallet_defined_by_addresses.js
readSharedAddressPeerAddresses
function readSharedAddressPeerAddresses(shared_address, handlePeerAddresses){ readSharedAddressPeers(shared_address, function(assocNamesByAddress){ handlePeerAddresses(Object.keys(assocNamesByAddress)); }); }
javascript
function readSharedAddressPeerAddresses(shared_address, handlePeerAddresses){ readSharedAddressPeers(shared_address, function(assocNamesByAddress){ handlePeerAddresses(Object.keys(assocNamesByAddress)); }); }
[ "function", "readSharedAddressPeerAddresses", "(", "shared_address", ",", "handlePeerAddresses", ")", "{", "readSharedAddressPeers", "(", "shared_address", ",", "function", "(", "assocNamesByAddress", ")", "{", "handlePeerAddresses", "(", "Object", ".", "keys", "(", "assocNamesByAddress", ")", ")", ";", "}", ")", ";", "}" ]
returns list of payment addresses of peers
[ "returns", "list", "of", "payment", "addresses", "of", "peers" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/wallet_defined_by_addresses.js#L545-L549
15,256
byteball/ocore
device.js
readMessageInChunksFromOutbox
function readMessageInChunksFromOutbox(message_hash, len, handleMessage){ var CHUNK_LEN = 1000000; var start = 1; var message = ''; function readChunk(){ db.query("SELECT SUBSTR(message, ?, ?) AS chunk FROM outbox WHERE message_hash=?", [start, CHUNK_LEN, message_hash], function(rows){ if (rows.length === 0) return handleMessage(); if (rows.length > 1) throw Error(rows.length+' msgs by hash in outbox, start='+start+', length='+len); message += rows[0].chunk; start += CHUNK_LEN; (start > len) ? handleMessage(message) : readChunk(); }); } readChunk(); }
javascript
function readMessageInChunksFromOutbox(message_hash, len, handleMessage){ var CHUNK_LEN = 1000000; var start = 1; var message = ''; function readChunk(){ db.query("SELECT SUBSTR(message, ?, ?) AS chunk FROM outbox WHERE message_hash=?", [start, CHUNK_LEN, message_hash], function(rows){ if (rows.length === 0) return handleMessage(); if (rows.length > 1) throw Error(rows.length+' msgs by hash in outbox, start='+start+', length='+len); message += rows[0].chunk; start += CHUNK_LEN; (start > len) ? handleMessage(message) : readChunk(); }); } readChunk(); }
[ "function", "readMessageInChunksFromOutbox", "(", "message_hash", ",", "len", ",", "handleMessage", ")", "{", "var", "CHUNK_LEN", "=", "1000000", ";", "var", "start", "=", "1", ";", "var", "message", "=", "''", ";", "function", "readChunk", "(", ")", "{", "db", ".", "query", "(", "\"SELECT SUBSTR(message, ?, ?) AS chunk FROM outbox WHERE message_hash=?\"", ",", "[", "start", ",", "CHUNK_LEN", ",", "message_hash", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "===", "0", ")", "return", "handleMessage", "(", ")", ";", "if", "(", "rows", ".", "length", ">", "1", ")", "throw", "Error", "(", "rows", ".", "length", "+", "' msgs by hash in outbox, start='", "+", "start", "+", "', length='", "+", "len", ")", ";", "message", "+=", "rows", "[", "0", "]", ".", "chunk", ";", "start", "+=", "CHUNK_LEN", ";", "(", "start", ">", "len", ")", "?", "handleMessage", "(", "message", ")", ":", "readChunk", "(", ")", ";", "}", ")", ";", "}", "readChunk", "(", ")", ";", "}" ]
a hack to read large text from cordova sqlite
[ "a", "hack", "to", "read", "large", "text", "from", "cordova", "sqlite" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/device.js#L355-L371
15,257
byteball/ocore
device.js
sendPreparedMessageToConnectedHub
function sendPreparedMessageToConnectedHub(ws, recipient_device_pubkey, message_hash, json, callbacks){ network.sendRequest(ws, 'hub/get_temp_pubkey', recipient_device_pubkey, false, function(ws, request, response){ function handleError(error){ callbacks.ifError(error); db.query("UPDATE outbox SET last_error=? WHERE message_hash=?", [error, message_hash], function(){}); } if (response.error) return handleError(response.error); var objTempPubkey = response; if (!objTempPubkey.temp_pubkey || !objTempPubkey.pubkey || !objTempPubkey.signature) return handleError("missing fields in hub response"); if (objTempPubkey.pubkey !== recipient_device_pubkey) return handleError("temp pubkey signed by wrong permanent pubkey"); if (!ecdsaSig.verify(objectHash.getDeviceMessageHashToSign(objTempPubkey), objTempPubkey.signature, objTempPubkey.pubkey)) return handleError("wrong sig under temp pubkey"); var objEncryptedPackage = createEncryptedPackage(json, objTempPubkey.temp_pubkey); var recipient_device_address = objectHash.getDeviceAddress(recipient_device_pubkey); var objDeviceMessage = { encrypted_package: objEncryptedPackage, to: recipient_device_address, pubkey: objMyPermanentDeviceKey.pub_b64 // who signs. Essentially, the from again. }; objDeviceMessage.signature = ecdsaSig.sign(objectHash.getDeviceMessageHashToSign(objDeviceMessage), objMyPermanentDeviceKey.priv); network.sendRequest(ws, 'hub/deliver', objDeviceMessage, false, function(ws, request, response){ if (response === "accepted"){ db.query("DELETE FROM outbox WHERE message_hash=?", [message_hash], function(){ callbacks.ifOk(); }); } else handleError( response.error || ("unrecognized response: "+JSON.stringify(response)) ); }); }); }
javascript
function sendPreparedMessageToConnectedHub(ws, recipient_device_pubkey, message_hash, json, callbacks){ network.sendRequest(ws, 'hub/get_temp_pubkey', recipient_device_pubkey, false, function(ws, request, response){ function handleError(error){ callbacks.ifError(error); db.query("UPDATE outbox SET last_error=? WHERE message_hash=?", [error, message_hash], function(){}); } if (response.error) return handleError(response.error); var objTempPubkey = response; if (!objTempPubkey.temp_pubkey || !objTempPubkey.pubkey || !objTempPubkey.signature) return handleError("missing fields in hub response"); if (objTempPubkey.pubkey !== recipient_device_pubkey) return handleError("temp pubkey signed by wrong permanent pubkey"); if (!ecdsaSig.verify(objectHash.getDeviceMessageHashToSign(objTempPubkey), objTempPubkey.signature, objTempPubkey.pubkey)) return handleError("wrong sig under temp pubkey"); var objEncryptedPackage = createEncryptedPackage(json, objTempPubkey.temp_pubkey); var recipient_device_address = objectHash.getDeviceAddress(recipient_device_pubkey); var objDeviceMessage = { encrypted_package: objEncryptedPackage, to: recipient_device_address, pubkey: objMyPermanentDeviceKey.pub_b64 // who signs. Essentially, the from again. }; objDeviceMessage.signature = ecdsaSig.sign(objectHash.getDeviceMessageHashToSign(objDeviceMessage), objMyPermanentDeviceKey.priv); network.sendRequest(ws, 'hub/deliver', objDeviceMessage, false, function(ws, request, response){ if (response === "accepted"){ db.query("DELETE FROM outbox WHERE message_hash=?", [message_hash], function(){ callbacks.ifOk(); }); } else handleError( response.error || ("unrecognized response: "+JSON.stringify(response)) ); }); }); }
[ "function", "sendPreparedMessageToConnectedHub", "(", "ws", ",", "recipient_device_pubkey", ",", "message_hash", ",", "json", ",", "callbacks", ")", "{", "network", ".", "sendRequest", "(", "ws", ",", "'hub/get_temp_pubkey'", ",", "recipient_device_pubkey", ",", "false", ",", "function", "(", "ws", ",", "request", ",", "response", ")", "{", "function", "handleError", "(", "error", ")", "{", "callbacks", ".", "ifError", "(", "error", ")", ";", "db", ".", "query", "(", "\"UPDATE outbox SET last_error=? WHERE message_hash=?\"", ",", "[", "error", ",", "message_hash", "]", ",", "function", "(", ")", "{", "}", ")", ";", "}", "if", "(", "response", ".", "error", ")", "return", "handleError", "(", "response", ".", "error", ")", ";", "var", "objTempPubkey", "=", "response", ";", "if", "(", "!", "objTempPubkey", ".", "temp_pubkey", "||", "!", "objTempPubkey", ".", "pubkey", "||", "!", "objTempPubkey", ".", "signature", ")", "return", "handleError", "(", "\"missing fields in hub response\"", ")", ";", "if", "(", "objTempPubkey", ".", "pubkey", "!==", "recipient_device_pubkey", ")", "return", "handleError", "(", "\"temp pubkey signed by wrong permanent pubkey\"", ")", ";", "if", "(", "!", "ecdsaSig", ".", "verify", "(", "objectHash", ".", "getDeviceMessageHashToSign", "(", "objTempPubkey", ")", ",", "objTempPubkey", ".", "signature", ",", "objTempPubkey", ".", "pubkey", ")", ")", "return", "handleError", "(", "\"wrong sig under temp pubkey\"", ")", ";", "var", "objEncryptedPackage", "=", "createEncryptedPackage", "(", "json", ",", "objTempPubkey", ".", "temp_pubkey", ")", ";", "var", "recipient_device_address", "=", "objectHash", ".", "getDeviceAddress", "(", "recipient_device_pubkey", ")", ";", "var", "objDeviceMessage", "=", "{", "encrypted_package", ":", "objEncryptedPackage", ",", "to", ":", "recipient_device_address", ",", "pubkey", ":", "objMyPermanentDeviceKey", ".", "pub_b64", "// who signs. Essentially, the from again. ", "}", ";", "objDeviceMessage", ".", "signature", "=", "ecdsaSig", ".", "sign", "(", "objectHash", ".", "getDeviceMessageHashToSign", "(", "objDeviceMessage", ")", ",", "objMyPermanentDeviceKey", ".", "priv", ")", ";", "network", ".", "sendRequest", "(", "ws", ",", "'hub/deliver'", ",", "objDeviceMessage", ",", "false", ",", "function", "(", "ws", ",", "request", ",", "response", ")", "{", "if", "(", "response", "===", "\"accepted\"", ")", "{", "db", ".", "query", "(", "\"DELETE FROM outbox WHERE message_hash=?\"", ",", "[", "message_hash", "]", ",", "function", "(", ")", "{", "callbacks", ".", "ifOk", "(", ")", ";", "}", ")", ";", "}", "else", "handleError", "(", "response", ".", "error", "||", "(", "\"unrecognized response: \"", "+", "JSON", ".", "stringify", "(", "response", ")", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
first param is WebSocket only
[ "first", "param", "is", "WebSocket", "only" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/device.js#L462-L495
15,258
byteball/ocore
device.js
sendMessageToHub
function sendMessageToHub(ws, recipient_device_pubkey, subject, body, callbacks, conn){ // this content is hidden from the hub by encryption var json = { from: my_device_address, // presence of this field guarantees that you cannot strip off the signature and add your own signature instead device_hub: my_device_hub, subject: subject, body: body }; conn = conn || db; if (ws) return reliablySendPreparedMessageToHub(ws, recipient_device_pubkey, json, callbacks, conn); var recipient_device_address = objectHash.getDeviceAddress(recipient_device_pubkey); conn.query("SELECT hub FROM correspondent_devices WHERE device_address=?", [recipient_device_address], function(rows){ if (rows.length !== 1) throw Error("no hub in correspondents"); reliablySendPreparedMessageToHub(rows[0].hub, recipient_device_pubkey, json, callbacks, conn); }); }
javascript
function sendMessageToHub(ws, recipient_device_pubkey, subject, body, callbacks, conn){ // this content is hidden from the hub by encryption var json = { from: my_device_address, // presence of this field guarantees that you cannot strip off the signature and add your own signature instead device_hub: my_device_hub, subject: subject, body: body }; conn = conn || db; if (ws) return reliablySendPreparedMessageToHub(ws, recipient_device_pubkey, json, callbacks, conn); var recipient_device_address = objectHash.getDeviceAddress(recipient_device_pubkey); conn.query("SELECT hub FROM correspondent_devices WHERE device_address=?", [recipient_device_address], function(rows){ if (rows.length !== 1) throw Error("no hub in correspondents"); reliablySendPreparedMessageToHub(rows[0].hub, recipient_device_pubkey, json, callbacks, conn); }); }
[ "function", "sendMessageToHub", "(", "ws", ",", "recipient_device_pubkey", ",", "subject", ",", "body", ",", "callbacks", ",", "conn", ")", "{", "// this content is hidden from the hub by encryption", "var", "json", "=", "{", "from", ":", "my_device_address", ",", "// presence of this field guarantees that you cannot strip off the signature and add your own signature instead", "device_hub", ":", "my_device_hub", ",", "subject", ":", "subject", ",", "body", ":", "body", "}", ";", "conn", "=", "conn", "||", "db", ";", "if", "(", "ws", ")", "return", "reliablySendPreparedMessageToHub", "(", "ws", ",", "recipient_device_pubkey", ",", "json", ",", "callbacks", ",", "conn", ")", ";", "var", "recipient_device_address", "=", "objectHash", ".", "getDeviceAddress", "(", "recipient_device_pubkey", ")", ";", "conn", ".", "query", "(", "\"SELECT hub FROM correspondent_devices WHERE device_address=?\"", ",", "[", "recipient_device_address", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "!==", "1", ")", "throw", "Error", "(", "\"no hub in correspondents\"", ")", ";", "reliablySendPreparedMessageToHub", "(", "rows", "[", "0", "]", ".", "hub", ",", "recipient_device_pubkey", ",", "json", ",", "callbacks", ",", "conn", ")", ";", "}", ")", ";", "}" ]
first param is either WebSocket or hostname of the hub or null
[ "first", "param", "is", "either", "WebSocket", "or", "hostname", "of", "the", "hub", "or", "null" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/device.js#L536-L553
15,259
byteball/ocore
witness_proof.js
validateUnit
function validateUnit(objUnit, bRequireDefinitionOrChange, cb2){ var bFound = false; async.eachSeries( objUnit.authors, function(author, cb3){ var address = author.address; // if (arrWitnesses.indexOf(address) === -1) // not a witness - skip it // return cb3(); var definition_chash = assocDefinitionChashes[address]; if (!definition_chash && arrWitnesses.indexOf(address) === -1) // not a witness - skip it return cb3(); if (!definition_chash) throw Error("definition chash not known for address "+address+", unit "+objUnit.unit); if (author.definition){ try{ if (objectHash.getChash160(author.definition) !== definition_chash) return cb3("definition doesn't hash to the expected value"); } catch(e){ return cb3("failed to calc definition chash: " +e); } assocDefinitions[definition_chash] = author.definition; bFound = true; } function handleAuthor(){ // FIX validation.validateAuthorSignaturesWithoutReferences(author, objUnit, assocDefinitions[definition_chash], function(err){ if (err) return cb3(err); for (var i=0; i<objUnit.messages.length; i++){ var message = objUnit.messages[i]; if (message.app === 'address_definition_change' && (message.payload.address === address || objUnit.authors.length === 1 && objUnit.authors[0].address === address)){ assocDefinitionChashes[address] = message.payload.definition_chash; bFound = true; } } cb3(); }); } if (assocDefinitions[definition_chash]) return handleAuthor(); storage.readDefinition(db, definition_chash, { ifFound: function(arrDefinition){ assocDefinitions[definition_chash] = arrDefinition; handleAuthor(); }, ifDefinitionNotFound: function(d){ throw Error("definition "+definition_chash+" not found, address "+address+", my witnesses "+arrWitnesses.join(', ')+", unit "+objUnit.unit); } }); }, function(err){ if (err) return cb2(err); if (bRequireDefinitionOrChange && !bFound) return cb2("neither definition nor change"); cb2(); } ); // each authors }
javascript
function validateUnit(objUnit, bRequireDefinitionOrChange, cb2){ var bFound = false; async.eachSeries( objUnit.authors, function(author, cb3){ var address = author.address; // if (arrWitnesses.indexOf(address) === -1) // not a witness - skip it // return cb3(); var definition_chash = assocDefinitionChashes[address]; if (!definition_chash && arrWitnesses.indexOf(address) === -1) // not a witness - skip it return cb3(); if (!definition_chash) throw Error("definition chash not known for address "+address+", unit "+objUnit.unit); if (author.definition){ try{ if (objectHash.getChash160(author.definition) !== definition_chash) return cb3("definition doesn't hash to the expected value"); } catch(e){ return cb3("failed to calc definition chash: " +e); } assocDefinitions[definition_chash] = author.definition; bFound = true; } function handleAuthor(){ // FIX validation.validateAuthorSignaturesWithoutReferences(author, objUnit, assocDefinitions[definition_chash], function(err){ if (err) return cb3(err); for (var i=0; i<objUnit.messages.length; i++){ var message = objUnit.messages[i]; if (message.app === 'address_definition_change' && (message.payload.address === address || objUnit.authors.length === 1 && objUnit.authors[0].address === address)){ assocDefinitionChashes[address] = message.payload.definition_chash; bFound = true; } } cb3(); }); } if (assocDefinitions[definition_chash]) return handleAuthor(); storage.readDefinition(db, definition_chash, { ifFound: function(arrDefinition){ assocDefinitions[definition_chash] = arrDefinition; handleAuthor(); }, ifDefinitionNotFound: function(d){ throw Error("definition "+definition_chash+" not found, address "+address+", my witnesses "+arrWitnesses.join(', ')+", unit "+objUnit.unit); } }); }, function(err){ if (err) return cb2(err); if (bRequireDefinitionOrChange && !bFound) return cb2("neither definition nor change"); cb2(); } ); // each authors }
[ "function", "validateUnit", "(", "objUnit", ",", "bRequireDefinitionOrChange", ",", "cb2", ")", "{", "var", "bFound", "=", "false", ";", "async", ".", "eachSeries", "(", "objUnit", ".", "authors", ",", "function", "(", "author", ",", "cb3", ")", "{", "var", "address", "=", "author", ".", "address", ";", "//\tif (arrWitnesses.indexOf(address) === -1) // not a witness - skip it", "//\t\treturn cb3();", "var", "definition_chash", "=", "assocDefinitionChashes", "[", "address", "]", ";", "if", "(", "!", "definition_chash", "&&", "arrWitnesses", ".", "indexOf", "(", "address", ")", "===", "-", "1", ")", "// not a witness - skip it", "return", "cb3", "(", ")", ";", "if", "(", "!", "definition_chash", ")", "throw", "Error", "(", "\"definition chash not known for address \"", "+", "address", "+", "\", unit \"", "+", "objUnit", ".", "unit", ")", ";", "if", "(", "author", ".", "definition", ")", "{", "try", "{", "if", "(", "objectHash", ".", "getChash160", "(", "author", ".", "definition", ")", "!==", "definition_chash", ")", "return", "cb3", "(", "\"definition doesn't hash to the expected value\"", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "cb3", "(", "\"failed to calc definition chash: \"", "+", "e", ")", ";", "}", "assocDefinitions", "[", "definition_chash", "]", "=", "author", ".", "definition", ";", "bFound", "=", "true", ";", "}", "function", "handleAuthor", "(", ")", "{", "// FIX", "validation", ".", "validateAuthorSignaturesWithoutReferences", "(", "author", ",", "objUnit", ",", "assocDefinitions", "[", "definition_chash", "]", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "cb3", "(", "err", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "objUnit", ".", "messages", ".", "length", ";", "i", "++", ")", "{", "var", "message", "=", "objUnit", ".", "messages", "[", "i", "]", ";", "if", "(", "message", ".", "app", "===", "'address_definition_change'", "&&", "(", "message", ".", "payload", ".", "address", "===", "address", "||", "objUnit", ".", "authors", ".", "length", "===", "1", "&&", "objUnit", ".", "authors", "[", "0", "]", ".", "address", "===", "address", ")", ")", "{", "assocDefinitionChashes", "[", "address", "]", "=", "message", ".", "payload", ".", "definition_chash", ";", "bFound", "=", "true", ";", "}", "}", "cb3", "(", ")", ";", "}", ")", ";", "}", "if", "(", "assocDefinitions", "[", "definition_chash", "]", ")", "return", "handleAuthor", "(", ")", ";", "storage", ".", "readDefinition", "(", "db", ",", "definition_chash", ",", "{", "ifFound", ":", "function", "(", "arrDefinition", ")", "{", "assocDefinitions", "[", "definition_chash", "]", "=", "arrDefinition", ";", "handleAuthor", "(", ")", ";", "}", ",", "ifDefinitionNotFound", ":", "function", "(", "d", ")", "{", "throw", "Error", "(", "\"definition \"", "+", "definition_chash", "+", "\" not found, address \"", "+", "address", "+", "\", my witnesses \"", "+", "arrWitnesses", ".", "join", "(", "', '", ")", "+", "\", unit \"", "+", "objUnit", ".", "unit", ")", ";", "}", "}", ")", ";", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "cb2", "(", "err", ")", ";", "if", "(", "bRequireDefinitionOrChange", "&&", "!", "bFound", ")", "return", "cb2", "(", "\"neither definition nor change\"", ")", ";", "cb2", "(", ")", ";", "}", ")", ";", "// each authors", "}" ]
keyed by address checks signatures and updates definitions
[ "keyed", "by", "address", "checks", "signatures", "and", "updates", "definitions" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/witness_proof.js#L180-L242
15,260
byteball/ocore
joint_storage.js
readDependentJointsThatAreReady
function readDependentJointsThatAreReady(unit, handleDependentJoint){ //console.log("readDependentJointsThatAreReady "+unit); var t=Date.now(); var from = unit ? "FROM dependencies AS src_deps JOIN dependencies USING(unit)" : "FROM dependencies"; var where = unit ? "WHERE src_deps.depends_on_unit="+db.escape(unit) : ""; var lock = unit ? mutex.lock : mutex.lockOrSkip; lock(["dependencies"], function(unlock){ db.query( "SELECT dependencies.unit, unhandled_joints.unit AS unit_for_json, \n\ SUM(CASE WHEN units.unit IS NULL THEN 1 ELSE 0 END) AS count_missing_parents \n\ "+from+" \n\ JOIN unhandled_joints ON dependencies.unit=unhandled_joints.unit \n\ LEFT JOIN units ON dependencies.depends_on_unit=units.unit \n\ "+where+" \n\ GROUP BY dependencies.unit \n\ HAVING count_missing_parents=0 \n\ ORDER BY NULL", function(rows){ //console.log(rows.length+" joints are ready"); //console.log("deps: "+(Date.now()-t)); rows.forEach(function(row) { db.query("SELECT json, peer, "+db.getUnixTimestamp("creation_date")+" AS creation_ts FROM unhandled_joints WHERE unit=?", [row.unit_for_json], function(internal_rows){ internal_rows.forEach(function(internal_row) { handleDependentJoint(JSON.parse(internal_row.json), parseInt(internal_row.creation_ts), internal_row.peer); }); }); }); unlock(); } ); }); }
javascript
function readDependentJointsThatAreReady(unit, handleDependentJoint){ //console.log("readDependentJointsThatAreReady "+unit); var t=Date.now(); var from = unit ? "FROM dependencies AS src_deps JOIN dependencies USING(unit)" : "FROM dependencies"; var where = unit ? "WHERE src_deps.depends_on_unit="+db.escape(unit) : ""; var lock = unit ? mutex.lock : mutex.lockOrSkip; lock(["dependencies"], function(unlock){ db.query( "SELECT dependencies.unit, unhandled_joints.unit AS unit_for_json, \n\ SUM(CASE WHEN units.unit IS NULL THEN 1 ELSE 0 END) AS count_missing_parents \n\ "+from+" \n\ JOIN unhandled_joints ON dependencies.unit=unhandled_joints.unit \n\ LEFT JOIN units ON dependencies.depends_on_unit=units.unit \n\ "+where+" \n\ GROUP BY dependencies.unit \n\ HAVING count_missing_parents=0 \n\ ORDER BY NULL", function(rows){ //console.log(rows.length+" joints are ready"); //console.log("deps: "+(Date.now()-t)); rows.forEach(function(row) { db.query("SELECT json, peer, "+db.getUnixTimestamp("creation_date")+" AS creation_ts FROM unhandled_joints WHERE unit=?", [row.unit_for_json], function(internal_rows){ internal_rows.forEach(function(internal_row) { handleDependentJoint(JSON.parse(internal_row.json), parseInt(internal_row.creation_ts), internal_row.peer); }); }); }); unlock(); } ); }); }
[ "function", "readDependentJointsThatAreReady", "(", "unit", ",", "handleDependentJoint", ")", "{", "//console.log(\"readDependentJointsThatAreReady \"+unit);", "var", "t", "=", "Date", ".", "now", "(", ")", ";", "var", "from", "=", "unit", "?", "\"FROM dependencies AS src_deps JOIN dependencies USING(unit)\"", ":", "\"FROM dependencies\"", ";", "var", "where", "=", "unit", "?", "\"WHERE src_deps.depends_on_unit=\"", "+", "db", ".", "escape", "(", "unit", ")", ":", "\"\"", ";", "var", "lock", "=", "unit", "?", "mutex", ".", "lock", ":", "mutex", ".", "lockOrSkip", ";", "lock", "(", "[", "\"dependencies\"", "]", ",", "function", "(", "unlock", ")", "{", "db", ".", "query", "(", "\"SELECT dependencies.unit, unhandled_joints.unit AS unit_for_json, \\n\\\n\t\t\t\tSUM(CASE WHEN units.unit IS NULL THEN 1 ELSE 0 END) AS count_missing_parents \\n\\\n\t\t\t\"", "+", "from", "+", "\" \\n\\\n\t\t\tJOIN unhandled_joints ON dependencies.unit=unhandled_joints.unit \\n\\\n\t\t\tLEFT JOIN units ON dependencies.depends_on_unit=units.unit \\n\\\n\t\t\t\"", "+", "where", "+", "\" \\n\\\n\t\t\tGROUP BY dependencies.unit \\n\\\n\t\t\tHAVING count_missing_parents=0 \\n\\\n\t\t\tORDER BY NULL\"", ",", "function", "(", "rows", ")", "{", "//console.log(rows.length+\" joints are ready\");", "//console.log(\"deps: \"+(Date.now()-t));", "rows", ".", "forEach", "(", "function", "(", "row", ")", "{", "db", ".", "query", "(", "\"SELECT json, peer, \"", "+", "db", ".", "getUnixTimestamp", "(", "\"creation_date\"", ")", "+", "\" AS creation_ts FROM unhandled_joints WHERE unit=?\"", ",", "[", "row", ".", "unit_for_json", "]", ",", "function", "(", "internal_rows", ")", "{", "internal_rows", ".", "forEach", "(", "function", "(", "internal_row", ")", "{", "handleDependentJoint", "(", "JSON", ".", "parse", "(", "internal_row", ".", "json", ")", ",", "parseInt", "(", "internal_row", ".", "creation_ts", ")", ",", "internal_row", ".", "peer", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "unlock", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
handleDependentJoint called for each dependent unit
[ "handleDependentJoint", "called", "for", "each", "dependent", "unit" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/joint_storage.js#L88-L119
15,261
byteball/ocore
joint_storage.js
readJointsSinceMci
function readJointsSinceMci(mci, handleJoint, onDone){ db.query( "SELECT units.unit FROM units LEFT JOIN archived_joints USING(unit) \n\ WHERE (is_stable=0 AND main_chain_index>=? OR main_chain_index IS NULL OR is_free=1) AND archived_joints.unit IS NULL \n\ ORDER BY +level", [mci], function(rows){ async.eachSeries( rows, function(row, cb){ storage.readJoint(db, row.unit, { ifNotFound: function(){ // throw Error("unit "+row.unit+" not found"); breadcrumbs.add("unit "+row.unit+" not found"); cb(); }, ifFound: function(objJoint){ handleJoint(objJoint); cb(); } }); }, onDone ); } ); }
javascript
function readJointsSinceMci(mci, handleJoint, onDone){ db.query( "SELECT units.unit FROM units LEFT JOIN archived_joints USING(unit) \n\ WHERE (is_stable=0 AND main_chain_index>=? OR main_chain_index IS NULL OR is_free=1) AND archived_joints.unit IS NULL \n\ ORDER BY +level", [mci], function(rows){ async.eachSeries( rows, function(row, cb){ storage.readJoint(db, row.unit, { ifNotFound: function(){ // throw Error("unit "+row.unit+" not found"); breadcrumbs.add("unit "+row.unit+" not found"); cb(); }, ifFound: function(objJoint){ handleJoint(objJoint); cb(); } }); }, onDone ); } ); }
[ "function", "readJointsSinceMci", "(", "mci", ",", "handleJoint", ",", "onDone", ")", "{", "db", ".", "query", "(", "\"SELECT units.unit FROM units LEFT JOIN archived_joints USING(unit) \\n\\\n\t\tWHERE (is_stable=0 AND main_chain_index>=? OR main_chain_index IS NULL OR is_free=1) AND archived_joints.unit IS NULL \\n\\\n\t\tORDER BY +level\"", ",", "[", "mci", "]", ",", "function", "(", "rows", ")", "{", "async", ".", "eachSeries", "(", "rows", ",", "function", "(", "row", ",", "cb", ")", "{", "storage", ".", "readJoint", "(", "db", ",", "row", ".", "unit", ",", "{", "ifNotFound", ":", "function", "(", ")", "{", "//\tthrow Error(\"unit \"+row.unit+\" not found\");", "breadcrumbs", ".", "add", "(", "\"unit \"", "+", "row", ".", "unit", "+", "\" not found\"", ")", ";", "cb", "(", ")", ";", "}", ",", "ifFound", ":", "function", "(", "objJoint", ")", "{", "handleJoint", "(", "objJoint", ")", ";", "cb", "(", ")", ";", "}", "}", ")", ";", "}", ",", "onDone", ")", ";", "}", ")", ";", "}" ]
handleJoint is called for every joint younger than mci
[ "handleJoint", "is", "called", "for", "every", "joint", "younger", "than", "mci" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/joint_storage.js#L294-L320
15,262
byteball/ocore
validation_utils.js
hasFieldsExcept
function hasFieldsExcept(obj, arrFields){ for (var field in obj) if (arrFields.indexOf(field) === -1) return true; return false; }
javascript
function hasFieldsExcept(obj, arrFields){ for (var field in obj) if (arrFields.indexOf(field) === -1) return true; return false; }
[ "function", "hasFieldsExcept", "(", "obj", ",", "arrFields", ")", "{", "for", "(", "var", "field", "in", "obj", ")", "if", "(", "arrFields", ".", "indexOf", "(", "field", ")", "===", "-", "1", ")", "return", "true", ";", "return", "false", ";", "}" ]
True if there is at least one field in obj that is not in arrFields.
[ "True", "if", "there", "is", "at", "least", "one", "field", "in", "obj", "that", "is", "not", "in", "arrFields", "." ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/validation_utils.js#L8-L13
15,263
byteball/ocore
inputs.js
addInput
function addInput(input){ total_amount += input.amount; var objInputWithProof = {input: input}; if (objAsset && objAsset.is_private){ // for type=payment only var spend_proof = objectHash.getBase64Hash({ asset: asset, amount: input.amount, address: input.address, unit: input.unit, message_index: input.message_index, output_index: input.output_index, blinding: input.blinding }); var objSpendProof = {spend_proof: spend_proof}; if (bMultiAuthored) objSpendProof.address = input.address; objInputWithProof.spend_proof = objSpendProof; } if (!bMultiAuthored || !input.type) delete input.address; delete input.amount; delete input.blinding; arrInputsWithProofs.push(objInputWithProof); }
javascript
function addInput(input){ total_amount += input.amount; var objInputWithProof = {input: input}; if (objAsset && objAsset.is_private){ // for type=payment only var spend_proof = objectHash.getBase64Hash({ asset: asset, amount: input.amount, address: input.address, unit: input.unit, message_index: input.message_index, output_index: input.output_index, blinding: input.blinding }); var objSpendProof = {spend_proof: spend_proof}; if (bMultiAuthored) objSpendProof.address = input.address; objInputWithProof.spend_proof = objSpendProof; } if (!bMultiAuthored || !input.type) delete input.address; delete input.amount; delete input.blinding; arrInputsWithProofs.push(objInputWithProof); }
[ "function", "addInput", "(", "input", ")", "{", "total_amount", "+=", "input", ".", "amount", ";", "var", "objInputWithProof", "=", "{", "input", ":", "input", "}", ";", "if", "(", "objAsset", "&&", "objAsset", ".", "is_private", ")", "{", "// for type=payment only", "var", "spend_proof", "=", "objectHash", ".", "getBase64Hash", "(", "{", "asset", ":", "asset", ",", "amount", ":", "input", ".", "amount", ",", "address", ":", "input", ".", "address", ",", "unit", ":", "input", ".", "unit", ",", "message_index", ":", "input", ".", "message_index", ",", "output_index", ":", "input", ".", "output_index", ",", "blinding", ":", "input", ".", "blinding", "}", ")", ";", "var", "objSpendProof", "=", "{", "spend_proof", ":", "spend_proof", "}", ";", "if", "(", "bMultiAuthored", ")", "objSpendProof", ".", "address", "=", "input", ".", "address", ";", "objInputWithProof", ".", "spend_proof", "=", "objSpendProof", ";", "}", "if", "(", "!", "bMultiAuthored", "||", "!", "input", ".", "type", ")", "delete", "input", ".", "address", ";", "delete", "input", ".", "amount", ";", "delete", "input", ".", "blinding", ";", "arrInputsWithProofs", ".", "push", "(", "objInputWithProof", ")", ";", "}" ]
adds element to arrInputsWithProofs
[ "adds", "element", "to", "arrInputsWithProofs" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/inputs.js#L53-L76
15,264
byteball/ocore
inputs.js
pickOneCoinJustBiggerAndContinue
function pickOneCoinJustBiggerAndContinue(){ if (amount === Infinity) return pickMultipleCoinsAndContinue(); var more = is_base ? '>' : '>='; conn.query( "SELECT unit, message_index, output_index, amount, blinding, address \n\ FROM outputs \n\ CROSS JOIN units USING(unit) \n\ WHERE address IN(?) AND asset"+(asset ? "="+conn.escape(asset) : " IS NULL")+" AND is_spent=0 AND amount "+more+" ? \n\ AND sequence='good' "+confirmation_condition+" \n\ ORDER BY is_stable DESC, amount LIMIT 1", [arrSpendableAddresses, amount+is_base*TRANSFER_INPUT_SIZE], function(rows){ if (rows.length === 1){ var input = rows[0]; // default type is "transfer" addInput(input); onDone(arrInputsWithProofs, total_amount); } else pickMultipleCoinsAndContinue(); } ); }
javascript
function pickOneCoinJustBiggerAndContinue(){ if (amount === Infinity) return pickMultipleCoinsAndContinue(); var more = is_base ? '>' : '>='; conn.query( "SELECT unit, message_index, output_index, amount, blinding, address \n\ FROM outputs \n\ CROSS JOIN units USING(unit) \n\ WHERE address IN(?) AND asset"+(asset ? "="+conn.escape(asset) : " IS NULL")+" AND is_spent=0 AND amount "+more+" ? \n\ AND sequence='good' "+confirmation_condition+" \n\ ORDER BY is_stable DESC, amount LIMIT 1", [arrSpendableAddresses, amount+is_base*TRANSFER_INPUT_SIZE], function(rows){ if (rows.length === 1){ var input = rows[0]; // default type is "transfer" addInput(input); onDone(arrInputsWithProofs, total_amount); } else pickMultipleCoinsAndContinue(); } ); }
[ "function", "pickOneCoinJustBiggerAndContinue", "(", ")", "{", "if", "(", "amount", "===", "Infinity", ")", "return", "pickMultipleCoinsAndContinue", "(", ")", ";", "var", "more", "=", "is_base", "?", "'>'", ":", "'>='", ";", "conn", ".", "query", "(", "\"SELECT unit, message_index, output_index, amount, blinding, address \\n\\\n\t\t\tFROM outputs \\n\\\n\t\t\tCROSS JOIN units USING(unit) \\n\\\n\t\t\tWHERE address IN(?) AND asset\"", "+", "(", "asset", "?", "\"=\"", "+", "conn", ".", "escape", "(", "asset", ")", ":", "\" IS NULL\"", ")", "+", "\" AND is_spent=0 AND amount \"", "+", "more", "+", "\" ? \\n\\\n\t\t\t\tAND sequence='good' \"", "+", "confirmation_condition", "+", "\" \\n\\\n\t\t\tORDER BY is_stable DESC, amount LIMIT 1\"", ",", "[", "arrSpendableAddresses", ",", "amount", "+", "is_base", "*", "TRANSFER_INPUT_SIZE", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "===", "1", ")", "{", "var", "input", "=", "rows", "[", "0", "]", ";", "// default type is \"transfer\"", "addInput", "(", "input", ")", ";", "onDone", "(", "arrInputsWithProofs", ",", "total_amount", ")", ";", "}", "else", "pickMultipleCoinsAndContinue", "(", ")", ";", "}", ")", ";", "}" ]
first, try to find a coin just bigger than the required amount
[ "first", "try", "to", "find", "a", "coin", "just", "bigger", "than", "the", "required", "amount" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/inputs.js#L79-L102
15,265
byteball/ocore
inputs.js
pickMultipleCoinsAndContinue
function pickMultipleCoinsAndContinue(){ conn.query( "SELECT unit, message_index, output_index, amount, address, blinding \n\ FROM outputs \n\ CROSS JOIN units USING(unit) \n\ WHERE address IN(?) AND asset"+(asset ? "="+conn.escape(asset) : " IS NULL")+" AND is_spent=0 \n\ AND sequence='good' "+confirmation_condition+" \n\ ORDER BY amount DESC LIMIT ?", [arrSpendableAddresses, constants.MAX_INPUTS_PER_PAYMENT_MESSAGE-2], function(rows){ async.eachSeries( rows, function(row, cb){ var input = row; objectHash.cleanNulls(input); required_amount += is_base*TRANSFER_INPUT_SIZE; addInput(input); // if we allow equality, we might get 0 amount for change which is invalid var bFound = is_base ? (total_amount > required_amount) : (total_amount >= required_amount); bFound ? cb('found') : cb(); }, function(err){ if (err === 'found') onDone(arrInputsWithProofs, total_amount); else if (asset) issueAsset(); else addHeadersCommissionInputs(); } ); } ); }
javascript
function pickMultipleCoinsAndContinue(){ conn.query( "SELECT unit, message_index, output_index, amount, address, blinding \n\ FROM outputs \n\ CROSS JOIN units USING(unit) \n\ WHERE address IN(?) AND asset"+(asset ? "="+conn.escape(asset) : " IS NULL")+" AND is_spent=0 \n\ AND sequence='good' "+confirmation_condition+" \n\ ORDER BY amount DESC LIMIT ?", [arrSpendableAddresses, constants.MAX_INPUTS_PER_PAYMENT_MESSAGE-2], function(rows){ async.eachSeries( rows, function(row, cb){ var input = row; objectHash.cleanNulls(input); required_amount += is_base*TRANSFER_INPUT_SIZE; addInput(input); // if we allow equality, we might get 0 amount for change which is invalid var bFound = is_base ? (total_amount > required_amount) : (total_amount >= required_amount); bFound ? cb('found') : cb(); }, function(err){ if (err === 'found') onDone(arrInputsWithProofs, total_amount); else if (asset) issueAsset(); else addHeadersCommissionInputs(); } ); } ); }
[ "function", "pickMultipleCoinsAndContinue", "(", ")", "{", "conn", ".", "query", "(", "\"SELECT unit, message_index, output_index, amount, address, blinding \\n\\\n\t\t\tFROM outputs \\n\\\n\t\t\tCROSS JOIN units USING(unit) \\n\\\n\t\t\tWHERE address IN(?) AND asset\"", "+", "(", "asset", "?", "\"=\"", "+", "conn", ".", "escape", "(", "asset", ")", ":", "\" IS NULL\"", ")", "+", "\" AND is_spent=0 \\n\\\n\t\t\t\tAND sequence='good' \"", "+", "confirmation_condition", "+", "\" \\n\\\n\t\t\tORDER BY amount DESC LIMIT ?\"", ",", "[", "arrSpendableAddresses", ",", "constants", ".", "MAX_INPUTS_PER_PAYMENT_MESSAGE", "-", "2", "]", ",", "function", "(", "rows", ")", "{", "async", ".", "eachSeries", "(", "rows", ",", "function", "(", "row", ",", "cb", ")", "{", "var", "input", "=", "row", ";", "objectHash", ".", "cleanNulls", "(", "input", ")", ";", "required_amount", "+=", "is_base", "*", "TRANSFER_INPUT_SIZE", ";", "addInput", "(", "input", ")", ";", "// if we allow equality, we might get 0 amount for change which is invalid", "var", "bFound", "=", "is_base", "?", "(", "total_amount", ">", "required_amount", ")", ":", "(", "total_amount", ">=", "required_amount", ")", ";", "bFound", "?", "cb", "(", "'found'", ")", ":", "cb", "(", ")", ";", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", "===", "'found'", ")", "onDone", "(", "arrInputsWithProofs", ",", "total_amount", ")", ";", "else", "if", "(", "asset", ")", "issueAsset", "(", ")", ";", "else", "addHeadersCommissionInputs", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
then, try to add smaller coins until we accumulate the target amount
[ "then", "try", "to", "add", "smaller", "coins", "until", "we", "accumulate", "the", "target", "amount" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/inputs.js#L105-L137
15,266
byteball/ocore
inputs.js
addIssueInput
function addIssueInput(serial_number){ total_amount += issue_amount; var input = { type: "issue", amount: issue_amount, serial_number: serial_number }; if (bMultiAuthored) input.address = issuer_address; var objInputWithProof = {input: input}; if (objAsset && objAsset.is_private){ var spend_proof = objectHash.getBase64Hash({ asset: asset, amount: issue_amount, denomination: 1, address: issuer_address, serial_number: serial_number }); var objSpendProof = {spend_proof: spend_proof}; if (bMultiAuthored) objSpendProof.address = input.address; objInputWithProof.spend_proof = objSpendProof; } arrInputsWithProofs.push(objInputWithProof); var bFound = is_base ? (total_amount > required_amount) : (total_amount >= required_amount); bFound ? onDone(arrInputsWithProofs, total_amount) : finish(); }
javascript
function addIssueInput(serial_number){ total_amount += issue_amount; var input = { type: "issue", amount: issue_amount, serial_number: serial_number }; if (bMultiAuthored) input.address = issuer_address; var objInputWithProof = {input: input}; if (objAsset && objAsset.is_private){ var spend_proof = objectHash.getBase64Hash({ asset: asset, amount: issue_amount, denomination: 1, address: issuer_address, serial_number: serial_number }); var objSpendProof = {spend_proof: spend_proof}; if (bMultiAuthored) objSpendProof.address = input.address; objInputWithProof.spend_proof = objSpendProof; } arrInputsWithProofs.push(objInputWithProof); var bFound = is_base ? (total_amount > required_amount) : (total_amount >= required_amount); bFound ? onDone(arrInputsWithProofs, total_amount) : finish(); }
[ "function", "addIssueInput", "(", "serial_number", ")", "{", "total_amount", "+=", "issue_amount", ";", "var", "input", "=", "{", "type", ":", "\"issue\"", ",", "amount", ":", "issue_amount", ",", "serial_number", ":", "serial_number", "}", ";", "if", "(", "bMultiAuthored", ")", "input", ".", "address", "=", "issuer_address", ";", "var", "objInputWithProof", "=", "{", "input", ":", "input", "}", ";", "if", "(", "objAsset", "&&", "objAsset", ".", "is_private", ")", "{", "var", "spend_proof", "=", "objectHash", ".", "getBase64Hash", "(", "{", "asset", ":", "asset", ",", "amount", ":", "issue_amount", ",", "denomination", ":", "1", ",", "address", ":", "issuer_address", ",", "serial_number", ":", "serial_number", "}", ")", ";", "var", "objSpendProof", "=", "{", "spend_proof", ":", "spend_proof", "}", ";", "if", "(", "bMultiAuthored", ")", "objSpendProof", ".", "address", "=", "input", ".", "address", ";", "objInputWithProof", ".", "spend_proof", "=", "objSpendProof", ";", "}", "arrInputsWithProofs", ".", "push", "(", "objInputWithProof", ")", ";", "var", "bFound", "=", "is_base", "?", "(", "total_amount", ">", "required_amount", ")", ":", "(", "total_amount", ">=", "required_amount", ")", ";", "bFound", "?", "onDone", "(", "arrInputsWithProofs", ",", "total_amount", ")", ":", "finish", "(", ")", ";", "}" ]
1 currency unit in case required_amount = total_amount
[ "1", "currency", "unit", "in", "case", "required_amount", "=", "total_amount" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/inputs.js#L199-L225
15,267
byteball/ocore
graph.js
goDown
function goDown(arrStartUnits){ conn.query( "SELECT unit, level, latest_included_mc_index, main_chain_index, is_on_main_chain \n\ FROM parenthoods JOIN units ON child_unit=unit \n\ WHERE parent_unit IN(?) AND latest_included_mc_index<? AND level<=?", [arrStartUnits, objEarlierUnitProps.main_chain_index, max_later_level], function(rows){ var arrNewStartUnits = []; for (var i=0; i<rows.length; i++){ var objUnitProps = rows[i]; //if (objUnitProps.latest_included_mc_index >= objEarlierUnitProps.main_chain_index) // continue; //if (objUnitProps.level > max_later_level) // continue; arrNewStartUnits.push(objUnitProps.unit); if (objUnitProps.main_chain_index !== null && objUnitProps.main_chain_index <= max_later_limci) // exclude free balls! arrLandedUnits.push(objUnitProps.unit); else arrUnlandedUnits.push(objUnitProps.unit); } (arrNewStartUnits.length > 0) ? goDown(arrNewStartUnits) : handleUnits(arrLandedUnits, arrUnlandedUnits); } ); }
javascript
function goDown(arrStartUnits){ conn.query( "SELECT unit, level, latest_included_mc_index, main_chain_index, is_on_main_chain \n\ FROM parenthoods JOIN units ON child_unit=unit \n\ WHERE parent_unit IN(?) AND latest_included_mc_index<? AND level<=?", [arrStartUnits, objEarlierUnitProps.main_chain_index, max_later_level], function(rows){ var arrNewStartUnits = []; for (var i=0; i<rows.length; i++){ var objUnitProps = rows[i]; //if (objUnitProps.latest_included_mc_index >= objEarlierUnitProps.main_chain_index) // continue; //if (objUnitProps.level > max_later_level) // continue; arrNewStartUnits.push(objUnitProps.unit); if (objUnitProps.main_chain_index !== null && objUnitProps.main_chain_index <= max_later_limci) // exclude free balls! arrLandedUnits.push(objUnitProps.unit); else arrUnlandedUnits.push(objUnitProps.unit); } (arrNewStartUnits.length > 0) ? goDown(arrNewStartUnits) : handleUnits(arrLandedUnits, arrUnlandedUnits); } ); }
[ "function", "goDown", "(", "arrStartUnits", ")", "{", "conn", ".", "query", "(", "\"SELECT unit, level, latest_included_mc_index, main_chain_index, is_on_main_chain \\n\\\n\t\t\tFROM parenthoods JOIN units ON child_unit=unit \\n\\\n\t\t\tWHERE parent_unit IN(?) AND latest_included_mc_index<? AND level<=?\"", ",", "[", "arrStartUnits", ",", "objEarlierUnitProps", ".", "main_chain_index", ",", "max_later_level", "]", ",", "function", "(", "rows", ")", "{", "var", "arrNewStartUnits", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "rows", ".", "length", ";", "i", "++", ")", "{", "var", "objUnitProps", "=", "rows", "[", "i", "]", ";", "//if (objUnitProps.latest_included_mc_index >= objEarlierUnitProps.main_chain_index)", "// continue;", "//if (objUnitProps.level > max_later_level)", "// continue;", "arrNewStartUnits", ".", "push", "(", "objUnitProps", ".", "unit", ")", ";", "if", "(", "objUnitProps", ".", "main_chain_index", "!==", "null", "&&", "objUnitProps", ".", "main_chain_index", "<=", "max_later_limci", ")", "// exclude free balls!", "arrLandedUnits", ".", "push", "(", "objUnitProps", ".", "unit", ")", ";", "else", "arrUnlandedUnits", ".", "push", "(", "objUnitProps", ".", "unit", ")", ";", "}", "(", "arrNewStartUnits", ".", "length", ">", "0", ")", "?", "goDown", "(", "arrNewStartUnits", ")", ":", "handleUnits", "(", "arrLandedUnits", ",", "arrUnlandedUnits", ")", ";", "}", ")", ";", "}" ]
direct shoots to later units, without touching the MC
[ "direct", "shoots", "to", "later", "units", "without", "touching", "the", "MC" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/graph.js#L312-L335
15,268
byteball/ocore
graph.js
readAscendantUnitsAfterTakingOffMc
function readAscendantUnitsAfterTakingOffMc(conn, objEarlierUnitProps, arrLaterUnitProps, handleUnits){ var arrLaterUnits = arrLaterUnitProps.map(function(objLaterUnitProps){ return objLaterUnitProps.unit; }); var max_later_limci = Math.max.apply(null, arrLaterUnitProps.map(function(objLaterUnitProps){ return objLaterUnitProps.latest_included_mc_index; })); var arrLandedUnits = []; // units that took off MC after earlier unit's MCI, they already include the earlier unit var arrUnlandedUnits = []; // direct shoots from earlier units, without touching the MC arrLaterUnitProps.forEach(function(objUnitProps){ if (objUnitProps.latest_included_mc_index >= objEarlierUnitProps.main_chain_index) arrLandedUnits.push(objUnitProps.unit); else arrUnlandedUnits.push(objUnitProps.unit); }); function goUp(arrStartUnits){ conn.query( "SELECT unit, level, latest_included_mc_index, main_chain_index, is_on_main_chain \n\ FROM parenthoods JOIN units ON parent_unit=unit \n\ WHERE child_unit IN(?) AND (main_chain_index>? OR main_chain_index IS NULL) AND level>=?", [arrStartUnits, max_later_limci, objEarlierUnitProps.level], function(rows){ var arrNewStartUnits = []; for (var i=0; i<rows.length; i++){ var objUnitProps = rows[i]; //if (objUnitProps.main_chain_index <= max_later_limci) // continue; //if (objUnitProps.level < objEarlierUnitProps.level) // continue; arrNewStartUnits.push(objUnitProps.unit); if (objUnitProps.latest_included_mc_index >= objEarlierUnitProps.main_chain_index) arrLandedUnits.push(objUnitProps.unit); else arrUnlandedUnits.push(objUnitProps.unit); } (arrNewStartUnits.length > 0) ? goUp(arrNewStartUnits) : handleUnits(arrLandedUnits, arrUnlandedUnits); } ); } goUp(arrLaterUnits); }
javascript
function readAscendantUnitsAfterTakingOffMc(conn, objEarlierUnitProps, arrLaterUnitProps, handleUnits){ var arrLaterUnits = arrLaterUnitProps.map(function(objLaterUnitProps){ return objLaterUnitProps.unit; }); var max_later_limci = Math.max.apply(null, arrLaterUnitProps.map(function(objLaterUnitProps){ return objLaterUnitProps.latest_included_mc_index; })); var arrLandedUnits = []; // units that took off MC after earlier unit's MCI, they already include the earlier unit var arrUnlandedUnits = []; // direct shoots from earlier units, without touching the MC arrLaterUnitProps.forEach(function(objUnitProps){ if (objUnitProps.latest_included_mc_index >= objEarlierUnitProps.main_chain_index) arrLandedUnits.push(objUnitProps.unit); else arrUnlandedUnits.push(objUnitProps.unit); }); function goUp(arrStartUnits){ conn.query( "SELECT unit, level, latest_included_mc_index, main_chain_index, is_on_main_chain \n\ FROM parenthoods JOIN units ON parent_unit=unit \n\ WHERE child_unit IN(?) AND (main_chain_index>? OR main_chain_index IS NULL) AND level>=?", [arrStartUnits, max_later_limci, objEarlierUnitProps.level], function(rows){ var arrNewStartUnits = []; for (var i=0; i<rows.length; i++){ var objUnitProps = rows[i]; //if (objUnitProps.main_chain_index <= max_later_limci) // continue; //if (objUnitProps.level < objEarlierUnitProps.level) // continue; arrNewStartUnits.push(objUnitProps.unit); if (objUnitProps.latest_included_mc_index >= objEarlierUnitProps.main_chain_index) arrLandedUnits.push(objUnitProps.unit); else arrUnlandedUnits.push(objUnitProps.unit); } (arrNewStartUnits.length > 0) ? goUp(arrNewStartUnits) : handleUnits(arrLandedUnits, arrUnlandedUnits); } ); } goUp(arrLaterUnits); }
[ "function", "readAscendantUnitsAfterTakingOffMc", "(", "conn", ",", "objEarlierUnitProps", ",", "arrLaterUnitProps", ",", "handleUnits", ")", "{", "var", "arrLaterUnits", "=", "arrLaterUnitProps", ".", "map", "(", "function", "(", "objLaterUnitProps", ")", "{", "return", "objLaterUnitProps", ".", "unit", ";", "}", ")", ";", "var", "max_later_limci", "=", "Math", ".", "max", ".", "apply", "(", "null", ",", "arrLaterUnitProps", ".", "map", "(", "function", "(", "objLaterUnitProps", ")", "{", "return", "objLaterUnitProps", ".", "latest_included_mc_index", ";", "}", ")", ")", ";", "var", "arrLandedUnits", "=", "[", "]", ";", "// units that took off MC after earlier unit's MCI, they already include the earlier unit", "var", "arrUnlandedUnits", "=", "[", "]", ";", "// direct shoots from earlier units, without touching the MC", "arrLaterUnitProps", ".", "forEach", "(", "function", "(", "objUnitProps", ")", "{", "if", "(", "objUnitProps", ".", "latest_included_mc_index", ">=", "objEarlierUnitProps", ".", "main_chain_index", ")", "arrLandedUnits", ".", "push", "(", "objUnitProps", ".", "unit", ")", ";", "else", "arrUnlandedUnits", ".", "push", "(", "objUnitProps", ".", "unit", ")", ";", "}", ")", ";", "function", "goUp", "(", "arrStartUnits", ")", "{", "conn", ".", "query", "(", "\"SELECT unit, level, latest_included_mc_index, main_chain_index, is_on_main_chain \\n\\\n\t\t\tFROM parenthoods JOIN units ON parent_unit=unit \\n\\\n\t\t\tWHERE child_unit IN(?) AND (main_chain_index>? OR main_chain_index IS NULL) AND level>=?\"", ",", "[", "arrStartUnits", ",", "max_later_limci", ",", "objEarlierUnitProps", ".", "level", "]", ",", "function", "(", "rows", ")", "{", "var", "arrNewStartUnits", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "rows", ".", "length", ";", "i", "++", ")", "{", "var", "objUnitProps", "=", "rows", "[", "i", "]", ";", "//if (objUnitProps.main_chain_index <= max_later_limci)", "// continue;", "//if (objUnitProps.level < objEarlierUnitProps.level)", "// continue;", "arrNewStartUnits", ".", "push", "(", "objUnitProps", ".", "unit", ")", ";", "if", "(", "objUnitProps", ".", "latest_included_mc_index", ">=", "objEarlierUnitProps", ".", "main_chain_index", ")", "arrLandedUnits", ".", "push", "(", "objUnitProps", ".", "unit", ")", ";", "else", "arrUnlandedUnits", ".", "push", "(", "objUnitProps", ".", "unit", ")", ";", "}", "(", "arrNewStartUnits", ".", "length", ">", "0", ")", "?", "goUp", "(", "arrNewStartUnits", ")", ":", "handleUnits", "(", "arrLandedUnits", ",", "arrUnlandedUnits", ")", ";", "}", ")", ";", "}", "goUp", "(", "arrLaterUnits", ")", ";", "}" ]
includes later units
[ "includes", "later", "units" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/graph.js#L341-L380
15,269
byteball/ocore
validation.js
validateSkiplist
function validateSkiplist(conn, arrSkiplistUnits, callback){ var prev = ""; async.eachSeries( arrSkiplistUnits, function(skiplist_unit, cb){ //if (skiplist_unit.charAt(0) !== "0") // return cb("skiplist unit doesn't start with 0"); if (skiplist_unit <= prev) return cb(createJointError("skiplist units not ordered")); conn.query("SELECT unit, is_stable, is_on_main_chain, main_chain_index FROM units WHERE unit=?", [skiplist_unit], function(rows){ if (rows.length === 0) return cb("skiplist unit "+skiplist_unit+" not found"); var objSkiplistUnitProps = rows[0]; // if not stable, can't check that it is on MC as MC is not stable in its area yet if (objSkiplistUnitProps.is_stable === 1){ if (objSkiplistUnitProps.is_on_main_chain !== 1) return cb("skiplist unit "+skiplist_unit+" is not on MC"); if (objSkiplistUnitProps.main_chain_index % 10 !== 0) return cb("skiplist unit "+skiplist_unit+" MCI is not divisible by 10"); } // we can't verify the choice of skiplist unit. // If we try to find a skiplist unit now, we might find something matching on unstable part of MC. // Again, we have another check when we reach stability cb(); }); }, callback ); }
javascript
function validateSkiplist(conn, arrSkiplistUnits, callback){ var prev = ""; async.eachSeries( arrSkiplistUnits, function(skiplist_unit, cb){ //if (skiplist_unit.charAt(0) !== "0") // return cb("skiplist unit doesn't start with 0"); if (skiplist_unit <= prev) return cb(createJointError("skiplist units not ordered")); conn.query("SELECT unit, is_stable, is_on_main_chain, main_chain_index FROM units WHERE unit=?", [skiplist_unit], function(rows){ if (rows.length === 0) return cb("skiplist unit "+skiplist_unit+" not found"); var objSkiplistUnitProps = rows[0]; // if not stable, can't check that it is on MC as MC is not stable in its area yet if (objSkiplistUnitProps.is_stable === 1){ if (objSkiplistUnitProps.is_on_main_chain !== 1) return cb("skiplist unit "+skiplist_unit+" is not on MC"); if (objSkiplistUnitProps.main_chain_index % 10 !== 0) return cb("skiplist unit "+skiplist_unit+" MCI is not divisible by 10"); } // we can't verify the choice of skiplist unit. // If we try to find a skiplist unit now, we might find something matching on unstable part of MC. // Again, we have another check when we reach stability cb(); }); }, callback ); }
[ "function", "validateSkiplist", "(", "conn", ",", "arrSkiplistUnits", ",", "callback", ")", "{", "var", "prev", "=", "\"\"", ";", "async", ".", "eachSeries", "(", "arrSkiplistUnits", ",", "function", "(", "skiplist_unit", ",", "cb", ")", "{", "//if (skiplist_unit.charAt(0) !== \"0\")", "// return cb(\"skiplist unit doesn't start with 0\");", "if", "(", "skiplist_unit", "<=", "prev", ")", "return", "cb", "(", "createJointError", "(", "\"skiplist units not ordered\"", ")", ")", ";", "conn", ".", "query", "(", "\"SELECT unit, is_stable, is_on_main_chain, main_chain_index FROM units WHERE unit=?\"", ",", "[", "skiplist_unit", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "===", "0", ")", "return", "cb", "(", "\"skiplist unit \"", "+", "skiplist_unit", "+", "\" not found\"", ")", ";", "var", "objSkiplistUnitProps", "=", "rows", "[", "0", "]", ";", "// if not stable, can't check that it is on MC as MC is not stable in its area yet", "if", "(", "objSkiplistUnitProps", ".", "is_stable", "===", "1", ")", "{", "if", "(", "objSkiplistUnitProps", ".", "is_on_main_chain", "!==", "1", ")", "return", "cb", "(", "\"skiplist unit \"", "+", "skiplist_unit", "+", "\" is not on MC\"", ")", ";", "if", "(", "objSkiplistUnitProps", ".", "main_chain_index", "%", "10", "!==", "0", ")", "return", "cb", "(", "\"skiplist unit \"", "+", "skiplist_unit", "+", "\" MCI is not divisible by 10\"", ")", ";", "}", "// we can't verify the choice of skiplist unit.", "// If we try to find a skiplist unit now, we might find something matching on unstable part of MC.", "// Again, we have another check when we reach stability", "cb", "(", ")", ";", "}", ")", ";", "}", ",", "callback", ")", ";", "}" ]
we cannot verify that skiplist units lie on MC if they are unstable yet, but if they don't, we'll get unmatching ball hash when the current unit reaches stability
[ "we", "cannot", "verify", "that", "skiplist", "units", "lie", "on", "MC", "if", "they", "are", "unstable", "yet", "but", "if", "they", "don", "t", "we", "ll", "get", "unmatching", "ball", "hash", "when", "the", "current", "unit", "reaches", "stability" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/validation.js#L372-L400
15,270
byteball/ocore
validation.js
checkNoSameAddressInDifferentParents
function checkNoSameAddressInDifferentParents(){ if (objUnit.parent_units.length === 1) return callback(); var assocAuthors = {}; var found_address; async.eachSeries( objUnit.parent_units, function(parent_unit, cb){ storage.readUnitAuthors(conn, parent_unit, function(arrAuthors){ arrAuthors.forEach(function(address){ if (assocAuthors[address]) found_address = address; assocAuthors[address] = true; }); cb(found_address); }); }, function(){ if (found_address) return callback("some addresses found more than once in parents, e.g. "+found_address); return callback(); } ); }
javascript
function checkNoSameAddressInDifferentParents(){ if (objUnit.parent_units.length === 1) return callback(); var assocAuthors = {}; var found_address; async.eachSeries( objUnit.parent_units, function(parent_unit, cb){ storage.readUnitAuthors(conn, parent_unit, function(arrAuthors){ arrAuthors.forEach(function(address){ if (assocAuthors[address]) found_address = address; assocAuthors[address] = true; }); cb(found_address); }); }, function(){ if (found_address) return callback("some addresses found more than once in parents, e.g. "+found_address); return callback(); } ); }
[ "function", "checkNoSameAddressInDifferentParents", "(", ")", "{", "if", "(", "objUnit", ".", "parent_units", ".", "length", "===", "1", ")", "return", "callback", "(", ")", ";", "var", "assocAuthors", "=", "{", "}", ";", "var", "found_address", ";", "async", ".", "eachSeries", "(", "objUnit", ".", "parent_units", ",", "function", "(", "parent_unit", ",", "cb", ")", "{", "storage", ".", "readUnitAuthors", "(", "conn", ",", "parent_unit", ",", "function", "(", "arrAuthors", ")", "{", "arrAuthors", ".", "forEach", "(", "function", "(", "address", ")", "{", "if", "(", "assocAuthors", "[", "address", "]", ")", "found_address", "=", "address", ";", "assocAuthors", "[", "address", "]", "=", "true", ";", "}", ")", ";", "cb", "(", "found_address", ")", ";", "}", ")", ";", "}", ",", "function", "(", ")", "{", "if", "(", "found_address", ")", "return", "callback", "(", "\"some addresses found more than once in parents, e.g. \"", "+", "found_address", ")", ";", "return", "callback", "(", ")", ";", "}", ")", ";", "}" ]
avoid merging the obvious nonserials
[ "avoid", "merging", "the", "obvious", "nonserials" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/validation.js#L440-L463
15,271
byteball/ocore
validation.js
checkNoPendingDefinition
function checkNoPendingDefinition(){ //var next = checkNoPendingOrRetrievableNonserialIncluded; var next = validateDefinition; //var filter = bNonserial ? "AND sequence='good'" : ""; // var cross = (objValidationState.max_known_mci - objValidationState.last_ball_mci < 1000) ? 'CROSS' : ''; conn.query( // _left_ join forces use of indexes in units // "SELECT unit FROM units "+cross+" JOIN unit_authors USING(unit) \n\ // WHERE address=? AND definition_chash IS NOT NULL AND ( /* is_stable=0 OR */ main_chain_index>? OR main_chain_index IS NULL)", // [objAuthor.address, objValidationState.last_ball_mci], "SELECT unit FROM unit_authors WHERE address=? AND definition_chash IS NOT NULL AND _mci>? \n\ UNION \n\ SELECT unit FROM unit_authors WHERE address=? AND definition_chash IS NOT NULL AND _mci IS NULL", [objAuthor.address, objValidationState.last_ball_mci, objAuthor.address], function(rows){ if (rows.length === 0) return next(); if (!bNonserial || objValidationState.arrAddressesWithForkedPath.indexOf(objAuthor.address) === -1) return callback("you can't send anything before your last definition is stable and before last ball"); // from this point, our unit is nonserial async.eachSeries( rows, function(row, cb){ graph.determineIfIncludedOrEqual(conn, row.unit, objUnit.parent_units, function(bIncluded){ if (bIncluded) console.log("checkNoPendingDefinition: unit "+row.unit+" is included"); bIncluded ? cb("found") : cb(); }); }, function(err){ (err === "found") ? callback("you can't send anything before your last included definition is stable and before last ball (self is nonserial)") : next(); } ); } ); }
javascript
function checkNoPendingDefinition(){ //var next = checkNoPendingOrRetrievableNonserialIncluded; var next = validateDefinition; //var filter = bNonserial ? "AND sequence='good'" : ""; // var cross = (objValidationState.max_known_mci - objValidationState.last_ball_mci < 1000) ? 'CROSS' : ''; conn.query( // _left_ join forces use of indexes in units // "SELECT unit FROM units "+cross+" JOIN unit_authors USING(unit) \n\ // WHERE address=? AND definition_chash IS NOT NULL AND ( /* is_stable=0 OR */ main_chain_index>? OR main_chain_index IS NULL)", // [objAuthor.address, objValidationState.last_ball_mci], "SELECT unit FROM unit_authors WHERE address=? AND definition_chash IS NOT NULL AND _mci>? \n\ UNION \n\ SELECT unit FROM unit_authors WHERE address=? AND definition_chash IS NOT NULL AND _mci IS NULL", [objAuthor.address, objValidationState.last_ball_mci, objAuthor.address], function(rows){ if (rows.length === 0) return next(); if (!bNonserial || objValidationState.arrAddressesWithForkedPath.indexOf(objAuthor.address) === -1) return callback("you can't send anything before your last definition is stable and before last ball"); // from this point, our unit is nonserial async.eachSeries( rows, function(row, cb){ graph.determineIfIncludedOrEqual(conn, row.unit, objUnit.parent_units, function(bIncluded){ if (bIncluded) console.log("checkNoPendingDefinition: unit "+row.unit+" is included"); bIncluded ? cb("found") : cb(); }); }, function(err){ (err === "found") ? callback("you can't send anything before your last included definition is stable and before last ball (self is nonserial)") : next(); } ); } ); }
[ "function", "checkNoPendingDefinition", "(", ")", "{", "//var next = checkNoPendingOrRetrievableNonserialIncluded;", "var", "next", "=", "validateDefinition", ";", "//var filter = bNonserial ? \"AND sequence='good'\" : \"\";", "//\tvar cross = (objValidationState.max_known_mci - objValidationState.last_ball_mci < 1000) ? 'CROSS' : '';", "conn", ".", "query", "(", "// _left_ join forces use of indexes in units", "//\t\"SELECT unit FROM units \"+cross+\" JOIN unit_authors USING(unit) \\n\\", "//\tWHERE address=? AND definition_chash IS NOT NULL AND ( /* is_stable=0 OR */ main_chain_index>? OR main_chain_index IS NULL)\", ", "//\t[objAuthor.address, objValidationState.last_ball_mci], ", "\"SELECT unit FROM unit_authors WHERE address=? AND definition_chash IS NOT NULL AND _mci>? \\n\\\n\t\t\tUNION \\n\\\n\t\t\tSELECT unit FROM unit_authors WHERE address=? AND definition_chash IS NOT NULL AND _mci IS NULL\"", ",", "[", "objAuthor", ".", "address", ",", "objValidationState", ".", "last_ball_mci", ",", "objAuthor", ".", "address", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "===", "0", ")", "return", "next", "(", ")", ";", "if", "(", "!", "bNonserial", "||", "objValidationState", ".", "arrAddressesWithForkedPath", ".", "indexOf", "(", "objAuthor", ".", "address", ")", "===", "-", "1", ")", "return", "callback", "(", "\"you can't send anything before your last definition is stable and before last ball\"", ")", ";", "// from this point, our unit is nonserial", "async", ".", "eachSeries", "(", "rows", ",", "function", "(", "row", ",", "cb", ")", "{", "graph", ".", "determineIfIncludedOrEqual", "(", "conn", ",", "row", ".", "unit", ",", "objUnit", ".", "parent_units", ",", "function", "(", "bIncluded", ")", "{", "if", "(", "bIncluded", ")", "console", ".", "log", "(", "\"checkNoPendingDefinition: unit \"", "+", "row", ".", "unit", "+", "\" is included\"", ")", ";", "bIncluded", "?", "cb", "(", "\"found\"", ")", ":", "cb", "(", ")", ";", "}", ")", ";", "}", ",", "function", "(", "err", ")", "{", "(", "err", "===", "\"found\"", ")", "?", "callback", "(", "\"you can't send anything before your last included definition is stable and before last ball (self is nonserial)\"", ")", ":", "next", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
We don't trust pending definitions even when they are serial, as another unit may arrive and make them nonserial, then the definition will be removed
[ "We", "don", "t", "trust", "pending", "definitions", "even", "when", "they", "are", "serial", "as", "another", "unit", "may", "arrive", "and", "make", "them", "nonserial", "then", "the", "definition", "will", "be", "removed" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/validation.js#L924-L960
15,272
byteball/ocore
validation.js
validateIndivisibleIssue
function validateIndivisibleIssue(input, cb){ // if (objAsset) // profiler2.start(); conn.query( "SELECT count_coins FROM asset_denominations WHERE asset=? AND denomination=?", [payload.asset, denomination], function(rows){ if (rows.length === 0) return cb("invalid denomination: "+denomination); if (rows.length > 1) throw Error("more than one record per denomination?"); var denomInfo = rows[0]; if (denomInfo.count_coins === null){ // uncapped if (input.amount % denomination !== 0) return cb("issue amount must be multiple of denomination"); } else{ if (input.amount !== denomination * denomInfo.count_coins) return cb("wrong size of issue of denomination "+denomination); } // if (objAsset) // profiler2.stop('validateIndivisibleIssue'); cb(); } ); }
javascript
function validateIndivisibleIssue(input, cb){ // if (objAsset) // profiler2.start(); conn.query( "SELECT count_coins FROM asset_denominations WHERE asset=? AND denomination=?", [payload.asset, denomination], function(rows){ if (rows.length === 0) return cb("invalid denomination: "+denomination); if (rows.length > 1) throw Error("more than one record per denomination?"); var denomInfo = rows[0]; if (denomInfo.count_coins === null){ // uncapped if (input.amount % denomination !== 0) return cb("issue amount must be multiple of denomination"); } else{ if (input.amount !== denomination * denomInfo.count_coins) return cb("wrong size of issue of denomination "+denomination); } // if (objAsset) // profiler2.stop('validateIndivisibleIssue'); cb(); } ); }
[ "function", "validateIndivisibleIssue", "(", "input", ",", "cb", ")", "{", "//\tif (objAsset)", "//\t\tprofiler2.start();", "conn", ".", "query", "(", "\"SELECT count_coins FROM asset_denominations WHERE asset=? AND denomination=?\"", ",", "[", "payload", ".", "asset", ",", "denomination", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "===", "0", ")", "return", "cb", "(", "\"invalid denomination: \"", "+", "denomination", ")", ";", "if", "(", "rows", ".", "length", ">", "1", ")", "throw", "Error", "(", "\"more than one record per denomination?\"", ")", ";", "var", "denomInfo", "=", "rows", "[", "0", "]", ";", "if", "(", "denomInfo", ".", "count_coins", "===", "null", ")", "{", "// uncapped", "if", "(", "input", ".", "amount", "%", "denomination", "!==", "0", ")", "return", "cb", "(", "\"issue amount must be multiple of denomination\"", ")", ";", "}", "else", "{", "if", "(", "input", ".", "amount", "!==", "denomination", "*", "denomInfo", ".", "count_coins", ")", "return", "cb", "(", "\"wrong size of issue of denomination \"", "+", "denomination", ")", ";", "}", "//\tif (objAsset)", "//\t\tprofiler2.stop('validateIndivisibleIssue');", "cb", "(", ")", ";", "}", ")", ";", "}" ]
same for both public and private
[ "same", "for", "both", "public", "and", "private" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/validation.js#L1534-L1559
15,273
byteball/ocore
validation.js
validateSignedMessageSync
function validateSignedMessageSync(objSignedMessage){ var err; var bCalledBack = false; validateSignedMessage(objSignedMessage, function(_err){ err = _err; bCalledBack = true; }); if (!bCalledBack) throw Error("validateSignedMessage is not sync"); return err; }
javascript
function validateSignedMessageSync(objSignedMessage){ var err; var bCalledBack = false; validateSignedMessage(objSignedMessage, function(_err){ err = _err; bCalledBack = true; }); if (!bCalledBack) throw Error("validateSignedMessage is not sync"); return err; }
[ "function", "validateSignedMessageSync", "(", "objSignedMessage", ")", "{", "var", "err", ";", "var", "bCalledBack", "=", "false", ";", "validateSignedMessage", "(", "objSignedMessage", ",", "function", "(", "_err", ")", "{", "err", "=", "_err", ";", "bCalledBack", "=", "true", ";", "}", ")", ";", "if", "(", "!", "bCalledBack", ")", "throw", "Error", "(", "\"validateSignedMessage is not sync\"", ")", ";", "return", "err", ";", "}" ]
inconsistent for multisig addresses
[ "inconsistent", "for", "multisig", "addresses" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/validation.js#L2223-L2233
15,274
byteball/ocore
main_chain.js
createListOfBestChildren
function createListOfBestChildren(arrParentUnits, handleBestChildrenList){ if (arrParentUnits.length === 0) return handleBestChildrenList([]); var arrBestChildren = arrParentUnits.slice(); function goDownAndCollectBestChildren(arrStartUnits, cb){ conn.query("SELECT unit, is_free FROM units WHERE best_parent_unit IN(?)", [arrStartUnits], function(rows){ if (rows.length === 0) return cb(); //console.log("unit", arrStartUnits, "best children:", rows.map(function(row){ return row.unit; }), "free units:", rows.reduce(function(sum, row){ return sum+row.is_free; }, 0)); async.eachSeries( rows, function(row, cb2){ arrBestChildren.push(row.unit); if (row.is_free === 1) cb2(); else goDownAndCollectBestChildren([row.unit], cb2); }, cb ); }); } goDownAndCollectBestChildren(arrParentUnits, function(){ handleBestChildrenList(arrBestChildren); }); }
javascript
function createListOfBestChildren(arrParentUnits, handleBestChildrenList){ if (arrParentUnits.length === 0) return handleBestChildrenList([]); var arrBestChildren = arrParentUnits.slice(); function goDownAndCollectBestChildren(arrStartUnits, cb){ conn.query("SELECT unit, is_free FROM units WHERE best_parent_unit IN(?)", [arrStartUnits], function(rows){ if (rows.length === 0) return cb(); //console.log("unit", arrStartUnits, "best children:", rows.map(function(row){ return row.unit; }), "free units:", rows.reduce(function(sum, row){ return sum+row.is_free; }, 0)); async.eachSeries( rows, function(row, cb2){ arrBestChildren.push(row.unit); if (row.is_free === 1) cb2(); else goDownAndCollectBestChildren([row.unit], cb2); }, cb ); }); } goDownAndCollectBestChildren(arrParentUnits, function(){ handleBestChildrenList(arrBestChildren); }); }
[ "function", "createListOfBestChildren", "(", "arrParentUnits", ",", "handleBestChildrenList", ")", "{", "if", "(", "arrParentUnits", ".", "length", "===", "0", ")", "return", "handleBestChildrenList", "(", "[", "]", ")", ";", "var", "arrBestChildren", "=", "arrParentUnits", ".", "slice", "(", ")", ";", "function", "goDownAndCollectBestChildren", "(", "arrStartUnits", ",", "cb", ")", "{", "conn", ".", "query", "(", "\"SELECT unit, is_free FROM units WHERE best_parent_unit IN(?)\"", ",", "[", "arrStartUnits", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "===", "0", ")", "return", "cb", "(", ")", ";", "//console.log(\"unit\", arrStartUnits, \"best children:\", rows.map(function(row){ return row.unit; }), \"free units:\", rows.reduce(function(sum, row){ return sum+row.is_free; }, 0));", "async", ".", "eachSeries", "(", "rows", ",", "function", "(", "row", ",", "cb2", ")", "{", "arrBestChildren", ".", "push", "(", "row", ".", "unit", ")", ";", "if", "(", "row", ".", "is_free", "===", "1", ")", "cb2", "(", ")", ";", "else", "goDownAndCollectBestChildren", "(", "[", "row", ".", "unit", "]", ",", "cb2", ")", ";", "}", ",", "cb", ")", ";", "}", ")", ";", "}", "goDownAndCollectBestChildren", "(", "arrParentUnits", ",", "function", "(", ")", "{", "handleBestChildrenList", "(", "arrBestChildren", ")", ";", "}", ")", ";", "}" ]
also includes arrParentUnits
[ "also", "includes", "arrParentUnits" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/main_chain.js#L540-L567
15,275
byteball/ocore
main_chain.js
filterAltBranchRootUnits
function filterAltBranchRootUnits(cb){ //console.log('===== before filtering:', arrAltBranchRootUnits); var arrFilteredAltBranchRootUnits = []; conn.query("SELECT unit, is_free, main_chain_index FROM units WHERE unit IN(?)", [arrAltBranchRootUnits], function(rows){ if (rows.length === 0) throw Error("no alt branch root units?"); async.eachSeries( rows, function(row, cb2){ function addUnit(){ arrBestChildren.push(row.unit); // if (row.is_free === 0) // seems no reason to exclude arrFilteredAltBranchRootUnits.push(row.unit); cb2(); } if (row.main_chain_index !== null && row.main_chain_index <= max_later_limci) addUnit(); else graph.determineIfIncludedOrEqual(conn, row.unit, arrLaterUnits, function(bIncluded){ bIncluded ? addUnit() : cb2(); }); }, function(){ //console.log('filtered:', arrFilteredAltBranchRootUnits); if (arrFilteredAltBranchRootUnits.length === 0) return handleBestChildrenList([]); var arrInitialBestChildren = _.clone(arrBestChildren); var start_time = Date.now(); if (conf.bFaster) return collectBestChildren(arrFilteredAltBranchRootUnits, function(){ console.log("collectBestChildren took "+(Date.now()-start_time)+"ms"); cb(); }); goDownAndCollectBestChildrenOld(arrFilteredAltBranchRootUnits, function(){ console.log("goDownAndCollectBestChildrenOld took "+(Date.now()-start_time)+"ms"); var arrBestChildren1 = _.clone(arrBestChildren.sort()); arrBestChildren = arrInitialBestChildren; start_time = Date.now(); collectBestChildren(arrFilteredAltBranchRootUnits, function(){ console.log("collectBestChildren took "+(Date.now()-start_time)+"ms"); arrBestChildren.sort(); if (!_.isEqual(arrBestChildren, arrBestChildren1)){ throwError("different best children, old "+arrBestChildren1.join(', ')+'; new '+arrBestChildren.join(', ')+', later '+arrLaterUnits.join(', ')+', earlier '+earlier_unit+", global db? = "+(conn === db)); arrBestChildren = arrBestChildren1; } cb(); }); }); } ); }); }
javascript
function filterAltBranchRootUnits(cb){ //console.log('===== before filtering:', arrAltBranchRootUnits); var arrFilteredAltBranchRootUnits = []; conn.query("SELECT unit, is_free, main_chain_index FROM units WHERE unit IN(?)", [arrAltBranchRootUnits], function(rows){ if (rows.length === 0) throw Error("no alt branch root units?"); async.eachSeries( rows, function(row, cb2){ function addUnit(){ arrBestChildren.push(row.unit); // if (row.is_free === 0) // seems no reason to exclude arrFilteredAltBranchRootUnits.push(row.unit); cb2(); } if (row.main_chain_index !== null && row.main_chain_index <= max_later_limci) addUnit(); else graph.determineIfIncludedOrEqual(conn, row.unit, arrLaterUnits, function(bIncluded){ bIncluded ? addUnit() : cb2(); }); }, function(){ //console.log('filtered:', arrFilteredAltBranchRootUnits); if (arrFilteredAltBranchRootUnits.length === 0) return handleBestChildrenList([]); var arrInitialBestChildren = _.clone(arrBestChildren); var start_time = Date.now(); if (conf.bFaster) return collectBestChildren(arrFilteredAltBranchRootUnits, function(){ console.log("collectBestChildren took "+(Date.now()-start_time)+"ms"); cb(); }); goDownAndCollectBestChildrenOld(arrFilteredAltBranchRootUnits, function(){ console.log("goDownAndCollectBestChildrenOld took "+(Date.now()-start_time)+"ms"); var arrBestChildren1 = _.clone(arrBestChildren.sort()); arrBestChildren = arrInitialBestChildren; start_time = Date.now(); collectBestChildren(arrFilteredAltBranchRootUnits, function(){ console.log("collectBestChildren took "+(Date.now()-start_time)+"ms"); arrBestChildren.sort(); if (!_.isEqual(arrBestChildren, arrBestChildren1)){ throwError("different best children, old "+arrBestChildren1.join(', ')+'; new '+arrBestChildren.join(', ')+', later '+arrLaterUnits.join(', ')+', earlier '+earlier_unit+", global db? = "+(conn === db)); arrBestChildren = arrBestChildren1; } cb(); }); }); } ); }); }
[ "function", "filterAltBranchRootUnits", "(", "cb", ")", "{", "//console.log('===== before filtering:', arrAltBranchRootUnits);", "var", "arrFilteredAltBranchRootUnits", "=", "[", "]", ";", "conn", ".", "query", "(", "\"SELECT unit, is_free, main_chain_index FROM units WHERE unit IN(?)\"", ",", "[", "arrAltBranchRootUnits", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "===", "0", ")", "throw", "Error", "(", "\"no alt branch root units?\"", ")", ";", "async", ".", "eachSeries", "(", "rows", ",", "function", "(", "row", ",", "cb2", ")", "{", "function", "addUnit", "(", ")", "{", "arrBestChildren", ".", "push", "(", "row", ".", "unit", ")", ";", "//\tif (row.is_free === 0) // seems no reason to exclude", "arrFilteredAltBranchRootUnits", ".", "push", "(", "row", ".", "unit", ")", ";", "cb2", "(", ")", ";", "}", "if", "(", "row", ".", "main_chain_index", "!==", "null", "&&", "row", ".", "main_chain_index", "<=", "max_later_limci", ")", "addUnit", "(", ")", ";", "else", "graph", ".", "determineIfIncludedOrEqual", "(", "conn", ",", "row", ".", "unit", ",", "arrLaterUnits", ",", "function", "(", "bIncluded", ")", "{", "bIncluded", "?", "addUnit", "(", ")", ":", "cb2", "(", ")", ";", "}", ")", ";", "}", ",", "function", "(", ")", "{", "//console.log('filtered:', arrFilteredAltBranchRootUnits);", "if", "(", "arrFilteredAltBranchRootUnits", ".", "length", "===", "0", ")", "return", "handleBestChildrenList", "(", "[", "]", ")", ";", "var", "arrInitialBestChildren", "=", "_", ".", "clone", "(", "arrBestChildren", ")", ";", "var", "start_time", "=", "Date", ".", "now", "(", ")", ";", "if", "(", "conf", ".", "bFaster", ")", "return", "collectBestChildren", "(", "arrFilteredAltBranchRootUnits", ",", "function", "(", ")", "{", "console", ".", "log", "(", "\"collectBestChildren took \"", "+", "(", "Date", ".", "now", "(", ")", "-", "start_time", ")", "+", "\"ms\"", ")", ";", "cb", "(", ")", ";", "}", ")", ";", "goDownAndCollectBestChildrenOld", "(", "arrFilteredAltBranchRootUnits", ",", "function", "(", ")", "{", "console", ".", "log", "(", "\"goDownAndCollectBestChildrenOld took \"", "+", "(", "Date", ".", "now", "(", ")", "-", "start_time", ")", "+", "\"ms\"", ")", ";", "var", "arrBestChildren1", "=", "_", ".", "clone", "(", "arrBestChildren", ".", "sort", "(", ")", ")", ";", "arrBestChildren", "=", "arrInitialBestChildren", ";", "start_time", "=", "Date", ".", "now", "(", ")", ";", "collectBestChildren", "(", "arrFilteredAltBranchRootUnits", ",", "function", "(", ")", "{", "console", ".", "log", "(", "\"collectBestChildren took \"", "+", "(", "Date", ".", "now", "(", ")", "-", "start_time", ")", "+", "\"ms\"", ")", ";", "arrBestChildren", ".", "sort", "(", ")", ";", "if", "(", "!", "_", ".", "isEqual", "(", "arrBestChildren", ",", "arrBestChildren1", ")", ")", "{", "throwError", "(", "\"different best children, old \"", "+", "arrBestChildren1", ".", "join", "(", "', '", ")", "+", "'; new '", "+", "arrBestChildren", ".", "join", "(", "', '", ")", "+", "', later '", "+", "arrLaterUnits", ".", "join", "(", "', '", ")", "+", "', earlier '", "+", "earlier_unit", "+", "\", global db? = \"", "+", "(", "conn", "===", "db", ")", ")", ";", "arrBestChildren", "=", "arrBestChildren1", ";", "}", "cb", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
leaves only those roots that are included by later units
[ "leaves", "only", "those", "roots", "that", "are", "included", "by", "later", "units" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/main_chain.js#L962-L1015
15,276
byteball/ocore
main_chain.js
determineIfStableInLaterUnitsAndUpdateStableMcFlag
function determineIfStableInLaterUnitsAndUpdateStableMcFlag(conn, earlier_unit, arrLaterUnits, bStableInDb, handleResult){ determineIfStableInLaterUnits(conn, earlier_unit, arrLaterUnits, function(bStable){ console.log("determineIfStableInLaterUnits", earlier_unit, arrLaterUnits, bStable); if (!bStable) return handleResult(bStable); if (bStable && bStableInDb) return handleResult(bStable); breadcrumbs.add('stable in parents, will wait for write lock'); mutex.lock(["write"], function(unlock){ breadcrumbs.add('stable in parents, got write lock'); storage.readLastStableMcIndex(conn, function(last_stable_mci){ storage.readUnitProps(conn, earlier_unit, function(objEarlierUnitProps){ var new_last_stable_mci = objEarlierUnitProps.main_chain_index; if (new_last_stable_mci <= last_stable_mci) // fix: it could've been changed by parallel tasks - No, our SQL transaction doesn't see the changes throw Error("new last stable mci expected to be higher than existing"); var mci = last_stable_mci; advanceLastStableMcUnitAndStepForward(); function advanceLastStableMcUnitAndStepForward(){ mci++; if (mci <= new_last_stable_mci) markMcIndexStable(conn, mci, advanceLastStableMcUnitAndStepForward); else{ unlock(); handleResult(bStable, true); } } }); }); }); }); }
javascript
function determineIfStableInLaterUnitsAndUpdateStableMcFlag(conn, earlier_unit, arrLaterUnits, bStableInDb, handleResult){ determineIfStableInLaterUnits(conn, earlier_unit, arrLaterUnits, function(bStable){ console.log("determineIfStableInLaterUnits", earlier_unit, arrLaterUnits, bStable); if (!bStable) return handleResult(bStable); if (bStable && bStableInDb) return handleResult(bStable); breadcrumbs.add('stable in parents, will wait for write lock'); mutex.lock(["write"], function(unlock){ breadcrumbs.add('stable in parents, got write lock'); storage.readLastStableMcIndex(conn, function(last_stable_mci){ storage.readUnitProps(conn, earlier_unit, function(objEarlierUnitProps){ var new_last_stable_mci = objEarlierUnitProps.main_chain_index; if (new_last_stable_mci <= last_stable_mci) // fix: it could've been changed by parallel tasks - No, our SQL transaction doesn't see the changes throw Error("new last stable mci expected to be higher than existing"); var mci = last_stable_mci; advanceLastStableMcUnitAndStepForward(); function advanceLastStableMcUnitAndStepForward(){ mci++; if (mci <= new_last_stable_mci) markMcIndexStable(conn, mci, advanceLastStableMcUnitAndStepForward); else{ unlock(); handleResult(bStable, true); } } }); }); }); }); }
[ "function", "determineIfStableInLaterUnitsAndUpdateStableMcFlag", "(", "conn", ",", "earlier_unit", ",", "arrLaterUnits", ",", "bStableInDb", ",", "handleResult", ")", "{", "determineIfStableInLaterUnits", "(", "conn", ",", "earlier_unit", ",", "arrLaterUnits", ",", "function", "(", "bStable", ")", "{", "console", ".", "log", "(", "\"determineIfStableInLaterUnits\"", ",", "earlier_unit", ",", "arrLaterUnits", ",", "bStable", ")", ";", "if", "(", "!", "bStable", ")", "return", "handleResult", "(", "bStable", ")", ";", "if", "(", "bStable", "&&", "bStableInDb", ")", "return", "handleResult", "(", "bStable", ")", ";", "breadcrumbs", ".", "add", "(", "'stable in parents, will wait for write lock'", ")", ";", "mutex", ".", "lock", "(", "[", "\"write\"", "]", ",", "function", "(", "unlock", ")", "{", "breadcrumbs", ".", "add", "(", "'stable in parents, got write lock'", ")", ";", "storage", ".", "readLastStableMcIndex", "(", "conn", ",", "function", "(", "last_stable_mci", ")", "{", "storage", ".", "readUnitProps", "(", "conn", ",", "earlier_unit", ",", "function", "(", "objEarlierUnitProps", ")", "{", "var", "new_last_stable_mci", "=", "objEarlierUnitProps", ".", "main_chain_index", ";", "if", "(", "new_last_stable_mci", "<=", "last_stable_mci", ")", "// fix: it could've been changed by parallel tasks - No, our SQL transaction doesn't see the changes", "throw", "Error", "(", "\"new last stable mci expected to be higher than existing\"", ")", ";", "var", "mci", "=", "last_stable_mci", ";", "advanceLastStableMcUnitAndStepForward", "(", ")", ";", "function", "advanceLastStableMcUnitAndStepForward", "(", ")", "{", "mci", "++", ";", "if", "(", "mci", "<=", "new_last_stable_mci", ")", "markMcIndexStable", "(", "conn", ",", "mci", ",", "advanceLastStableMcUnitAndStepForward", ")", ";", "else", "{", "unlock", "(", ")", ";", "handleResult", "(", "bStable", ",", "true", ")", ";", "}", "}", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
It is assumed earlier_unit is not marked as stable yet If it appears to be stable, its MC index will be marked as stable, as well as all preceeding MC indexes
[ "It", "is", "assumed", "earlier_unit", "is", "not", "marked", "as", "stable", "yet", "If", "it", "appears", "to", "be", "stable", "its", "MC", "index", "will", "be", "marked", "as", "stable", "as", "well", "as", "all", "preceeding", "MC", "indexes" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/main_chain.js#L1075-L1106
15,277
byteball/ocore
main_chain.js
propagateFinalBad
function propagateFinalBad(arrFinalBadUnits, onPropagated){ if (arrFinalBadUnits.length === 0) return onPropagated(); conn.query("SELECT DISTINCT unit FROM inputs WHERE src_unit IN(?)", [arrFinalBadUnits], function(rows){ if (rows.length === 0) return onPropagated(); var arrSpendingUnits = rows.map(function(row){ return row.unit; }); conn.query("UPDATE units SET sequence='final-bad' WHERE unit IN(?)", [arrSpendingUnits], function(){ arrSpendingUnits.forEach(function(unit){ storage.assocUnstableUnits[unit].sequence = 'final-bad'; }); propagateFinalBad(arrSpendingUnits, onPropagated); }); }); }
javascript
function propagateFinalBad(arrFinalBadUnits, onPropagated){ if (arrFinalBadUnits.length === 0) return onPropagated(); conn.query("SELECT DISTINCT unit FROM inputs WHERE src_unit IN(?)", [arrFinalBadUnits], function(rows){ if (rows.length === 0) return onPropagated(); var arrSpendingUnits = rows.map(function(row){ return row.unit; }); conn.query("UPDATE units SET sequence='final-bad' WHERE unit IN(?)", [arrSpendingUnits], function(){ arrSpendingUnits.forEach(function(unit){ storage.assocUnstableUnits[unit].sequence = 'final-bad'; }); propagateFinalBad(arrSpendingUnits, onPropagated); }); }); }
[ "function", "propagateFinalBad", "(", "arrFinalBadUnits", ",", "onPropagated", ")", "{", "if", "(", "arrFinalBadUnits", ".", "length", "===", "0", ")", "return", "onPropagated", "(", ")", ";", "conn", ".", "query", "(", "\"SELECT DISTINCT unit FROM inputs WHERE src_unit IN(?)\"", ",", "[", "arrFinalBadUnits", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "===", "0", ")", "return", "onPropagated", "(", ")", ";", "var", "arrSpendingUnits", "=", "rows", ".", "map", "(", "function", "(", "row", ")", "{", "return", "row", ".", "unit", ";", "}", ")", ";", "conn", ".", "query", "(", "\"UPDATE units SET sequence='final-bad' WHERE unit IN(?)\"", ",", "[", "arrSpendingUnits", "]", ",", "function", "(", ")", "{", "arrSpendingUnits", ".", "forEach", "(", "function", "(", "unit", ")", "{", "storage", ".", "assocUnstableUnits", "[", "unit", "]", ".", "sequence", "=", "'final-bad'", ";", "}", ")", ";", "propagateFinalBad", "(", "arrSpendingUnits", ",", "onPropagated", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
all future units that spent these unconfirmed units become final-bad too
[ "all", "future", "units", "that", "spent", "these", "unconfirmed", "units", "become", "final", "-", "bad", "too" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/main_chain.js#L1206-L1220
15,278
byteball/ocore
main_chain.js
getSimilarMcis
function getSimilarMcis(mci){ var arrSimilarMcis = []; var divisor = 10; while (true){ if (mci % divisor === 0){ arrSimilarMcis.push(mci - divisor); divisor *= 10; } else return arrSimilarMcis; } }
javascript
function getSimilarMcis(mci){ var arrSimilarMcis = []; var divisor = 10; while (true){ if (mci % divisor === 0){ arrSimilarMcis.push(mci - divisor); divisor *= 10; } else return arrSimilarMcis; } }
[ "function", "getSimilarMcis", "(", "mci", ")", "{", "var", "arrSimilarMcis", "=", "[", "]", ";", "var", "divisor", "=", "10", ";", "while", "(", "true", ")", "{", "if", "(", "mci", "%", "divisor", "===", "0", ")", "{", "arrSimilarMcis", ".", "push", "(", "mci", "-", "divisor", ")", ";", "divisor", "*=", "10", ";", "}", "else", "return", "arrSimilarMcis", ";", "}", "}" ]
returns list of past MC indices for skiplist
[ "returns", "list", "of", "past", "MC", "indices", "for", "skiplist" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/main_chain.js#L1377-L1388
15,279
byteball/ocore
indivisible_asset.js
parsePrivatePaymentChain
function parsePrivatePaymentChain(conn, arrPrivateElements, callbacks){ var bAllStable = true; var issuePrivateElement = arrPrivateElements[arrPrivateElements.length-1]; if (!issuePrivateElement.payload || !issuePrivateElement.payload.inputs || !issuePrivateElement.payload.inputs[0]) return callbacks.ifError("invalid issue private element"); var asset = issuePrivateElement.payload.asset; if (!asset) return callbacks.ifError("no asset in issue private element"); var denomination = issuePrivateElement.payload.denomination; if (!denomination) return callbacks.ifError("no denomination in issue private element"); async.forEachOfSeries( arrPrivateElements, function(objPrivateElement, i, cb){ if (!objPrivateElement.payload || !objPrivateElement.payload.inputs || !objPrivateElement.payload.inputs[0]) return cb("invalid payload"); if (!objPrivateElement.output) return cb("no output in private element"); if (objPrivateElement.payload.asset !== asset) return cb("private element has a different asset"); if (objPrivateElement.payload.denomination !== denomination) return cb("private element has a different denomination"); var prevElement = null; if (i+1 < arrPrivateElements.length){ // excluding issue transaction var prevElement = arrPrivateElements[i+1]; if (prevElement.unit !== objPrivateElement.payload.inputs[0].unit) return cb("not referencing previous element unit"); if (prevElement.message_index !== objPrivateElement.payload.inputs[0].message_index) return cb("not referencing previous element message index"); if (prevElement.output_index !== objPrivateElement.payload.inputs[0].output_index) return cb("not referencing previous element output index"); } validatePrivatePayment(conn, objPrivateElement, prevElement, { ifError: cb, ifOk: function(bStable, input_address){ objPrivateElement.bStable = bStable; objPrivateElement.input_address = input_address; if (!bStable) bAllStable = false; cb(); } }); }, function(err){ if (err) return callbacks.ifError(err); callbacks.ifOk(bAllStable); } ); }
javascript
function parsePrivatePaymentChain(conn, arrPrivateElements, callbacks){ var bAllStable = true; var issuePrivateElement = arrPrivateElements[arrPrivateElements.length-1]; if (!issuePrivateElement.payload || !issuePrivateElement.payload.inputs || !issuePrivateElement.payload.inputs[0]) return callbacks.ifError("invalid issue private element"); var asset = issuePrivateElement.payload.asset; if (!asset) return callbacks.ifError("no asset in issue private element"); var denomination = issuePrivateElement.payload.denomination; if (!denomination) return callbacks.ifError("no denomination in issue private element"); async.forEachOfSeries( arrPrivateElements, function(objPrivateElement, i, cb){ if (!objPrivateElement.payload || !objPrivateElement.payload.inputs || !objPrivateElement.payload.inputs[0]) return cb("invalid payload"); if (!objPrivateElement.output) return cb("no output in private element"); if (objPrivateElement.payload.asset !== asset) return cb("private element has a different asset"); if (objPrivateElement.payload.denomination !== denomination) return cb("private element has a different denomination"); var prevElement = null; if (i+1 < arrPrivateElements.length){ // excluding issue transaction var prevElement = arrPrivateElements[i+1]; if (prevElement.unit !== objPrivateElement.payload.inputs[0].unit) return cb("not referencing previous element unit"); if (prevElement.message_index !== objPrivateElement.payload.inputs[0].message_index) return cb("not referencing previous element message index"); if (prevElement.output_index !== objPrivateElement.payload.inputs[0].output_index) return cb("not referencing previous element output index"); } validatePrivatePayment(conn, objPrivateElement, prevElement, { ifError: cb, ifOk: function(bStable, input_address){ objPrivateElement.bStable = bStable; objPrivateElement.input_address = input_address; if (!bStable) bAllStable = false; cb(); } }); }, function(err){ if (err) return callbacks.ifError(err); callbacks.ifOk(bAllStable); } ); }
[ "function", "parsePrivatePaymentChain", "(", "conn", ",", "arrPrivateElements", ",", "callbacks", ")", "{", "var", "bAllStable", "=", "true", ";", "var", "issuePrivateElement", "=", "arrPrivateElements", "[", "arrPrivateElements", ".", "length", "-", "1", "]", ";", "if", "(", "!", "issuePrivateElement", ".", "payload", "||", "!", "issuePrivateElement", ".", "payload", ".", "inputs", "||", "!", "issuePrivateElement", ".", "payload", ".", "inputs", "[", "0", "]", ")", "return", "callbacks", ".", "ifError", "(", "\"invalid issue private element\"", ")", ";", "var", "asset", "=", "issuePrivateElement", ".", "payload", ".", "asset", ";", "if", "(", "!", "asset", ")", "return", "callbacks", ".", "ifError", "(", "\"no asset in issue private element\"", ")", ";", "var", "denomination", "=", "issuePrivateElement", ".", "payload", ".", "denomination", ";", "if", "(", "!", "denomination", ")", "return", "callbacks", ".", "ifError", "(", "\"no denomination in issue private element\"", ")", ";", "async", ".", "forEachOfSeries", "(", "arrPrivateElements", ",", "function", "(", "objPrivateElement", ",", "i", ",", "cb", ")", "{", "if", "(", "!", "objPrivateElement", ".", "payload", "||", "!", "objPrivateElement", ".", "payload", ".", "inputs", "||", "!", "objPrivateElement", ".", "payload", ".", "inputs", "[", "0", "]", ")", "return", "cb", "(", "\"invalid payload\"", ")", ";", "if", "(", "!", "objPrivateElement", ".", "output", ")", "return", "cb", "(", "\"no output in private element\"", ")", ";", "if", "(", "objPrivateElement", ".", "payload", ".", "asset", "!==", "asset", ")", "return", "cb", "(", "\"private element has a different asset\"", ")", ";", "if", "(", "objPrivateElement", ".", "payload", ".", "denomination", "!==", "denomination", ")", "return", "cb", "(", "\"private element has a different denomination\"", ")", ";", "var", "prevElement", "=", "null", ";", "if", "(", "i", "+", "1", "<", "arrPrivateElements", ".", "length", ")", "{", "// excluding issue transaction", "var", "prevElement", "=", "arrPrivateElements", "[", "i", "+", "1", "]", ";", "if", "(", "prevElement", ".", "unit", "!==", "objPrivateElement", ".", "payload", ".", "inputs", "[", "0", "]", ".", "unit", ")", "return", "cb", "(", "\"not referencing previous element unit\"", ")", ";", "if", "(", "prevElement", ".", "message_index", "!==", "objPrivateElement", ".", "payload", ".", "inputs", "[", "0", "]", ".", "message_index", ")", "return", "cb", "(", "\"not referencing previous element message index\"", ")", ";", "if", "(", "prevElement", ".", "output_index", "!==", "objPrivateElement", ".", "payload", ".", "inputs", "[", "0", "]", ".", "output_index", ")", "return", "cb", "(", "\"not referencing previous element output index\"", ")", ";", "}", "validatePrivatePayment", "(", "conn", ",", "objPrivateElement", ",", "prevElement", ",", "{", "ifError", ":", "cb", ",", "ifOk", ":", "function", "(", "bStable", ",", "input_address", ")", "{", "objPrivateElement", ".", "bStable", "=", "bStable", ";", "objPrivateElement", ".", "input_address", "=", "input_address", ";", "if", "(", "!", "bStable", ")", "bAllStable", "=", "false", ";", "cb", "(", ")", ";", "}", "}", ")", ";", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "callbacks", ".", "ifError", "(", "err", ")", ";", "callbacks", ".", "ifOk", "(", "bAllStable", ")", ";", "}", ")", ";", "}" ]
arrPrivateElements is ordered in reverse chronological order
[ "arrPrivateElements", "is", "ordered", "in", "reverse", "chronological", "order" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/indivisible_asset.js#L170-L219
15,280
byteball/ocore
indivisible_asset.js
updateIndivisibleOutputsThatWereReceivedUnstable
function updateIndivisibleOutputsThatWereReceivedUnstable(conn, onDone){ function updateOutputProps(unit, is_serial, onUpdated){ // may update several outputs conn.query( "UPDATE outputs SET is_serial=? WHERE unit=?", [is_serial, unit], function(){ is_serial ? updateInputUniqueness(unit, onUpdated) : onUpdated(); } ); } function updateInputUniqueness(unit, onUpdated){ // may update several inputs conn.query("UPDATE inputs SET is_unique=1 WHERE unit=?", [unit], function(){ onUpdated(); }); } console.log("updatePrivateIndivisibleOutputsThatWereReceivedUnstable starting"); conn.query( "SELECT unit, message_index, sequence FROM outputs "+(conf.storage === 'sqlite' ? "INDEXED BY outputsIsSerial" : "")+" \n\ JOIN units USING(unit) \n\ WHERE outputs.is_serial IS NULL AND units.is_stable=1 AND is_spent=0", // is_spent=0 selects the final output in the chain function(rows){ if (rows.length === 0) return onDone(); async.eachSeries( rows, function(row, cb){ function updateFinalOutputProps(is_serial){ updateOutputProps(row.unit, is_serial, cb); } function goUp(unit, message_index){ // we must have exactly 1 input per message conn.query( "SELECT src_unit, src_message_index, src_output_index \n\ FROM inputs \n\ WHERE unit=? AND message_index=?", [unit, message_index], function(src_rows){ if (src_rows.length === 0) throw Error("updating unstable: blackbyte input not found"); if (src_rows.length > 1) throw Error("updating unstable: more than one input found"); var src_row = src_rows[0]; if (src_row.src_unit === null) // reached root of the chain (issue) return cb(); conn.query( "SELECT sequence, is_stable, is_serial FROM outputs JOIN units USING(unit) \n\ WHERE unit=? AND message_index=? AND output_index=?", [src_row.src_unit, src_row.src_message_index, src_row.src_output_index], function(prev_rows){ if (prev_rows.length === 0) throw Error("src unit not found"); var prev_output = prev_rows[0]; if (prev_output.is_serial === 0) throw Error("prev is already nonserial"); if (prev_output.is_stable === 0) throw Error("prev is not stable"); if (prev_output.is_serial === 1 && prev_output.sequence !== 'good') throw Error("prev is_serial=1 but seq!=good"); if (prev_output.is_serial === 1) // already was stable when initially received return cb(); var is_serial = (prev_output.sequence === 'good') ? 1 : 0; updateOutputProps(src_row.src_unit, is_serial, function(){ if (!is_serial) // overwrite the tip of the chain return updateFinalOutputProps(0); goUp(src_row.src_unit, src_row.src_message_index); }); } ); } ); } var is_serial = (row.sequence === 'good') ? 1 : 0; updateOutputProps(row.unit, is_serial, function(){ goUp(row.unit, row.message_index); }); }, onDone ); } ); }
javascript
function updateIndivisibleOutputsThatWereReceivedUnstable(conn, onDone){ function updateOutputProps(unit, is_serial, onUpdated){ // may update several outputs conn.query( "UPDATE outputs SET is_serial=? WHERE unit=?", [is_serial, unit], function(){ is_serial ? updateInputUniqueness(unit, onUpdated) : onUpdated(); } ); } function updateInputUniqueness(unit, onUpdated){ // may update several inputs conn.query("UPDATE inputs SET is_unique=1 WHERE unit=?", [unit], function(){ onUpdated(); }); } console.log("updatePrivateIndivisibleOutputsThatWereReceivedUnstable starting"); conn.query( "SELECT unit, message_index, sequence FROM outputs "+(conf.storage === 'sqlite' ? "INDEXED BY outputsIsSerial" : "")+" \n\ JOIN units USING(unit) \n\ WHERE outputs.is_serial IS NULL AND units.is_stable=1 AND is_spent=0", // is_spent=0 selects the final output in the chain function(rows){ if (rows.length === 0) return onDone(); async.eachSeries( rows, function(row, cb){ function updateFinalOutputProps(is_serial){ updateOutputProps(row.unit, is_serial, cb); } function goUp(unit, message_index){ // we must have exactly 1 input per message conn.query( "SELECT src_unit, src_message_index, src_output_index \n\ FROM inputs \n\ WHERE unit=? AND message_index=?", [unit, message_index], function(src_rows){ if (src_rows.length === 0) throw Error("updating unstable: blackbyte input not found"); if (src_rows.length > 1) throw Error("updating unstable: more than one input found"); var src_row = src_rows[0]; if (src_row.src_unit === null) // reached root of the chain (issue) return cb(); conn.query( "SELECT sequence, is_stable, is_serial FROM outputs JOIN units USING(unit) \n\ WHERE unit=? AND message_index=? AND output_index=?", [src_row.src_unit, src_row.src_message_index, src_row.src_output_index], function(prev_rows){ if (prev_rows.length === 0) throw Error("src unit not found"); var prev_output = prev_rows[0]; if (prev_output.is_serial === 0) throw Error("prev is already nonserial"); if (prev_output.is_stable === 0) throw Error("prev is not stable"); if (prev_output.is_serial === 1 && prev_output.sequence !== 'good') throw Error("prev is_serial=1 but seq!=good"); if (prev_output.is_serial === 1) // already was stable when initially received return cb(); var is_serial = (prev_output.sequence === 'good') ? 1 : 0; updateOutputProps(src_row.src_unit, is_serial, function(){ if (!is_serial) // overwrite the tip of the chain return updateFinalOutputProps(0); goUp(src_row.src_unit, src_row.src_message_index); }); } ); } ); } var is_serial = (row.sequence === 'good') ? 1 : 0; updateOutputProps(row.unit, is_serial, function(){ goUp(row.unit, row.message_index); }); }, onDone ); } ); }
[ "function", "updateIndivisibleOutputsThatWereReceivedUnstable", "(", "conn", ",", "onDone", ")", "{", "function", "updateOutputProps", "(", "unit", ",", "is_serial", ",", "onUpdated", ")", "{", "// may update several outputs", "conn", ".", "query", "(", "\"UPDATE outputs SET is_serial=? WHERE unit=?\"", ",", "[", "is_serial", ",", "unit", "]", ",", "function", "(", ")", "{", "is_serial", "?", "updateInputUniqueness", "(", "unit", ",", "onUpdated", ")", ":", "onUpdated", "(", ")", ";", "}", ")", ";", "}", "function", "updateInputUniqueness", "(", "unit", ",", "onUpdated", ")", "{", "// may update several inputs", "conn", ".", "query", "(", "\"UPDATE inputs SET is_unique=1 WHERE unit=?\"", ",", "[", "unit", "]", ",", "function", "(", ")", "{", "onUpdated", "(", ")", ";", "}", ")", ";", "}", "console", ".", "log", "(", "\"updatePrivateIndivisibleOutputsThatWereReceivedUnstable starting\"", ")", ";", "conn", ".", "query", "(", "\"SELECT unit, message_index, sequence FROM outputs \"", "+", "(", "conf", ".", "storage", "===", "'sqlite'", "?", "\"INDEXED BY outputsIsSerial\"", ":", "\"\"", ")", "+", "\" \\n\\\n\t\tJOIN units USING(unit) \\n\\\n\t\tWHERE outputs.is_serial IS NULL AND units.is_stable=1 AND is_spent=0\"", ",", "// is_spent=0 selects the final output in the chain", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "===", "0", ")", "return", "onDone", "(", ")", ";", "async", ".", "eachSeries", "(", "rows", ",", "function", "(", "row", ",", "cb", ")", "{", "function", "updateFinalOutputProps", "(", "is_serial", ")", "{", "updateOutputProps", "(", "row", ".", "unit", ",", "is_serial", ",", "cb", ")", ";", "}", "function", "goUp", "(", "unit", ",", "message_index", ")", "{", "// we must have exactly 1 input per message", "conn", ".", "query", "(", "\"SELECT src_unit, src_message_index, src_output_index \\n\\\n\t\t\t\t\t\t\tFROM inputs \\n\\\n\t\t\t\t\t\t\tWHERE unit=? AND message_index=?\"", ",", "[", "unit", ",", "message_index", "]", ",", "function", "(", "src_rows", ")", "{", "if", "(", "src_rows", ".", "length", "===", "0", ")", "throw", "Error", "(", "\"updating unstable: blackbyte input not found\"", ")", ";", "if", "(", "src_rows", ".", "length", ">", "1", ")", "throw", "Error", "(", "\"updating unstable: more than one input found\"", ")", ";", "var", "src_row", "=", "src_rows", "[", "0", "]", ";", "if", "(", "src_row", ".", "src_unit", "===", "null", ")", "// reached root of the chain (issue)", "return", "cb", "(", ")", ";", "conn", ".", "query", "(", "\"SELECT sequence, is_stable, is_serial FROM outputs JOIN units USING(unit) \\n\\\n\t\t\t\t\t\t\t\t\tWHERE unit=? AND message_index=? AND output_index=?\"", ",", "[", "src_row", ".", "src_unit", ",", "src_row", ".", "src_message_index", ",", "src_row", ".", "src_output_index", "]", ",", "function", "(", "prev_rows", ")", "{", "if", "(", "prev_rows", ".", "length", "===", "0", ")", "throw", "Error", "(", "\"src unit not found\"", ")", ";", "var", "prev_output", "=", "prev_rows", "[", "0", "]", ";", "if", "(", "prev_output", ".", "is_serial", "===", "0", ")", "throw", "Error", "(", "\"prev is already nonserial\"", ")", ";", "if", "(", "prev_output", ".", "is_stable", "===", "0", ")", "throw", "Error", "(", "\"prev is not stable\"", ")", ";", "if", "(", "prev_output", ".", "is_serial", "===", "1", "&&", "prev_output", ".", "sequence", "!==", "'good'", ")", "throw", "Error", "(", "\"prev is_serial=1 but seq!=good\"", ")", ";", "if", "(", "prev_output", ".", "is_serial", "===", "1", ")", "// already was stable when initially received", "return", "cb", "(", ")", ";", "var", "is_serial", "=", "(", "prev_output", ".", "sequence", "===", "'good'", ")", "?", "1", ":", "0", ";", "updateOutputProps", "(", "src_row", ".", "src_unit", ",", "is_serial", ",", "function", "(", ")", "{", "if", "(", "!", "is_serial", ")", "// overwrite the tip of the chain", "return", "updateFinalOutputProps", "(", "0", ")", ";", "goUp", "(", "src_row", ".", "src_unit", ",", "src_row", ".", "src_message_index", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}", "var", "is_serial", "=", "(", "row", ".", "sequence", "===", "'good'", ")", "?", "1", ":", "0", ";", "updateOutputProps", "(", "row", ".", "unit", ",", "is_serial", ",", "function", "(", ")", "{", "goUp", "(", "row", ".", "unit", ",", "row", ".", "message_index", ")", ";", "}", ")", ";", "}", ",", "onDone", ")", ";", "}", ")", ";", "}" ]
must be executed within transaction
[ "must", "be", "executed", "within", "transaction" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/indivisible_asset.js#L284-L372
15,281
byteball/ocore
indivisible_asset.js
buildPrivateElementsChain
function buildPrivateElementsChain(conn, unit, message_index, output_index, payload, handlePrivateElements){ var asset = payload.asset; var denomination = payload.denomination; var output = payload.outputs[output_index]; var hidden_payload = _.cloneDeep(payload); hidden_payload.outputs.forEach(function(o){ delete o.address; delete o.blinding; // output_hash was already added }); var arrPrivateElements = [{ unit: unit, message_index: message_index, payload: hidden_payload, output_index: output_index, output: { address: output.address, blinding: output.blinding } }]; function readPayloadAndGoUp(_unit, _message_index, _output_index){ conn.query( "SELECT src_unit, src_message_index, src_output_index, serial_number, denomination, amount, address, asset, \n\ (SELECT COUNT(*) FROM unit_authors WHERE unit=?) AS count_authors \n\ FROM inputs WHERE unit=? AND message_index=?", [_unit, _unit, _message_index], function(in_rows){ if (in_rows.length === 0) throw Error("building chain: blackbyte input not found"); if (in_rows.length > 1) throw Error("building chain: more than 1 input found"); var in_row = in_rows[0]; if (!in_row.address) throw Error("readPayloadAndGoUp: input address is NULL"); if (in_row.asset !== asset) throw Error("building chain: asset mismatch"); if (in_row.denomination !== denomination) throw Error("building chain: denomination mismatch"); var input = {}; if (in_row.src_unit){ // transfer input.unit = in_row.src_unit; input.message_index = in_row.src_message_index; input.output_index = in_row.src_output_index; } else{ input.type = 'issue'; input.serial_number = in_row.serial_number; input.amount = in_row.amount; if (in_row.count_authors > 1) input.address = in_row.address; } conn.query( "SELECT address, blinding, output_hash, amount, output_index, asset, denomination FROM outputs \n\ WHERE unit=? AND message_index=? ORDER BY output_index", [_unit, _message_index], function(out_rows){ if (out_rows.length === 0) throw Error("blackbyte output not found"); var output = {}; var outputs = out_rows.map(function(o){ if (o.asset !== asset) throw Error("outputs asset mismatch"); if (o.denomination !== denomination) throw Error("outputs denomination mismatch"); if (o.output_index === _output_index){ output.address = o.address; output.blinding = o.blinding; } return { amount: o.amount, output_hash: o.output_hash }; }); if (!output.address) throw Error("output not filled"); var objPrivateElement = { unit: _unit, message_index: _message_index, payload: { asset: asset, denomination: denomination, inputs: [input], outputs: outputs }, output_index: _output_index, output: output }; arrPrivateElements.push(objPrivateElement); (input.type === 'issue') ? handlePrivateElements(arrPrivateElements) : readPayloadAndGoUp(input.unit, input.message_index, input.output_index); } ); } ); } var input = payload.inputs[0]; (input.type === 'issue') ? handlePrivateElements(arrPrivateElements) : readPayloadAndGoUp(input.unit, input.message_index, input.output_index); }
javascript
function buildPrivateElementsChain(conn, unit, message_index, output_index, payload, handlePrivateElements){ var asset = payload.asset; var denomination = payload.denomination; var output = payload.outputs[output_index]; var hidden_payload = _.cloneDeep(payload); hidden_payload.outputs.forEach(function(o){ delete o.address; delete o.blinding; // output_hash was already added }); var arrPrivateElements = [{ unit: unit, message_index: message_index, payload: hidden_payload, output_index: output_index, output: { address: output.address, blinding: output.blinding } }]; function readPayloadAndGoUp(_unit, _message_index, _output_index){ conn.query( "SELECT src_unit, src_message_index, src_output_index, serial_number, denomination, amount, address, asset, \n\ (SELECT COUNT(*) FROM unit_authors WHERE unit=?) AS count_authors \n\ FROM inputs WHERE unit=? AND message_index=?", [_unit, _unit, _message_index], function(in_rows){ if (in_rows.length === 0) throw Error("building chain: blackbyte input not found"); if (in_rows.length > 1) throw Error("building chain: more than 1 input found"); var in_row = in_rows[0]; if (!in_row.address) throw Error("readPayloadAndGoUp: input address is NULL"); if (in_row.asset !== asset) throw Error("building chain: asset mismatch"); if (in_row.denomination !== denomination) throw Error("building chain: denomination mismatch"); var input = {}; if (in_row.src_unit){ // transfer input.unit = in_row.src_unit; input.message_index = in_row.src_message_index; input.output_index = in_row.src_output_index; } else{ input.type = 'issue'; input.serial_number = in_row.serial_number; input.amount = in_row.amount; if (in_row.count_authors > 1) input.address = in_row.address; } conn.query( "SELECT address, blinding, output_hash, amount, output_index, asset, denomination FROM outputs \n\ WHERE unit=? AND message_index=? ORDER BY output_index", [_unit, _message_index], function(out_rows){ if (out_rows.length === 0) throw Error("blackbyte output not found"); var output = {}; var outputs = out_rows.map(function(o){ if (o.asset !== asset) throw Error("outputs asset mismatch"); if (o.denomination !== denomination) throw Error("outputs denomination mismatch"); if (o.output_index === _output_index){ output.address = o.address; output.blinding = o.blinding; } return { amount: o.amount, output_hash: o.output_hash }; }); if (!output.address) throw Error("output not filled"); var objPrivateElement = { unit: _unit, message_index: _message_index, payload: { asset: asset, denomination: denomination, inputs: [input], outputs: outputs }, output_index: _output_index, output: output }; arrPrivateElements.push(objPrivateElement); (input.type === 'issue') ? handlePrivateElements(arrPrivateElements) : readPayloadAndGoUp(input.unit, input.message_index, input.output_index); } ); } ); } var input = payload.inputs[0]; (input.type === 'issue') ? handlePrivateElements(arrPrivateElements) : readPayloadAndGoUp(input.unit, input.message_index, input.output_index); }
[ "function", "buildPrivateElementsChain", "(", "conn", ",", "unit", ",", "message_index", ",", "output_index", ",", "payload", ",", "handlePrivateElements", ")", "{", "var", "asset", "=", "payload", ".", "asset", ";", "var", "denomination", "=", "payload", ".", "denomination", ";", "var", "output", "=", "payload", ".", "outputs", "[", "output_index", "]", ";", "var", "hidden_payload", "=", "_", ".", "cloneDeep", "(", "payload", ")", ";", "hidden_payload", ".", "outputs", ".", "forEach", "(", "function", "(", "o", ")", "{", "delete", "o", ".", "address", ";", "delete", "o", ".", "blinding", ";", "// output_hash was already added", "}", ")", ";", "var", "arrPrivateElements", "=", "[", "{", "unit", ":", "unit", ",", "message_index", ":", "message_index", ",", "payload", ":", "hidden_payload", ",", "output_index", ":", "output_index", ",", "output", ":", "{", "address", ":", "output", ".", "address", ",", "blinding", ":", "output", ".", "blinding", "}", "}", "]", ";", "function", "readPayloadAndGoUp", "(", "_unit", ",", "_message_index", ",", "_output_index", ")", "{", "conn", ".", "query", "(", "\"SELECT src_unit, src_message_index, src_output_index, serial_number, denomination, amount, address, asset, \\n\\\n\t\t\t\t(SELECT COUNT(*) FROM unit_authors WHERE unit=?) AS count_authors \\n\\\n\t\t\tFROM inputs WHERE unit=? AND message_index=?\"", ",", "[", "_unit", ",", "_unit", ",", "_message_index", "]", ",", "function", "(", "in_rows", ")", "{", "if", "(", "in_rows", ".", "length", "===", "0", ")", "throw", "Error", "(", "\"building chain: blackbyte input not found\"", ")", ";", "if", "(", "in_rows", ".", "length", ">", "1", ")", "throw", "Error", "(", "\"building chain: more than 1 input found\"", ")", ";", "var", "in_row", "=", "in_rows", "[", "0", "]", ";", "if", "(", "!", "in_row", ".", "address", ")", "throw", "Error", "(", "\"readPayloadAndGoUp: input address is NULL\"", ")", ";", "if", "(", "in_row", ".", "asset", "!==", "asset", ")", "throw", "Error", "(", "\"building chain: asset mismatch\"", ")", ";", "if", "(", "in_row", ".", "denomination", "!==", "denomination", ")", "throw", "Error", "(", "\"building chain: denomination mismatch\"", ")", ";", "var", "input", "=", "{", "}", ";", "if", "(", "in_row", ".", "src_unit", ")", "{", "// transfer", "input", ".", "unit", "=", "in_row", ".", "src_unit", ";", "input", ".", "message_index", "=", "in_row", ".", "src_message_index", ";", "input", ".", "output_index", "=", "in_row", ".", "src_output_index", ";", "}", "else", "{", "input", ".", "type", "=", "'issue'", ";", "input", ".", "serial_number", "=", "in_row", ".", "serial_number", ";", "input", ".", "amount", "=", "in_row", ".", "amount", ";", "if", "(", "in_row", ".", "count_authors", ">", "1", ")", "input", ".", "address", "=", "in_row", ".", "address", ";", "}", "conn", ".", "query", "(", "\"SELECT address, blinding, output_hash, amount, output_index, asset, denomination FROM outputs \\n\\\n\t\t\t\t\tWHERE unit=? AND message_index=? ORDER BY output_index\"", ",", "[", "_unit", ",", "_message_index", "]", ",", "function", "(", "out_rows", ")", "{", "if", "(", "out_rows", ".", "length", "===", "0", ")", "throw", "Error", "(", "\"blackbyte output not found\"", ")", ";", "var", "output", "=", "{", "}", ";", "var", "outputs", "=", "out_rows", ".", "map", "(", "function", "(", "o", ")", "{", "if", "(", "o", ".", "asset", "!==", "asset", ")", "throw", "Error", "(", "\"outputs asset mismatch\"", ")", ";", "if", "(", "o", ".", "denomination", "!==", "denomination", ")", "throw", "Error", "(", "\"outputs denomination mismatch\"", ")", ";", "if", "(", "o", ".", "output_index", "===", "_output_index", ")", "{", "output", ".", "address", "=", "o", ".", "address", ";", "output", ".", "blinding", "=", "o", ".", "blinding", ";", "}", "return", "{", "amount", ":", "o", ".", "amount", ",", "output_hash", ":", "o", ".", "output_hash", "}", ";", "}", ")", ";", "if", "(", "!", "output", ".", "address", ")", "throw", "Error", "(", "\"output not filled\"", ")", ";", "var", "objPrivateElement", "=", "{", "unit", ":", "_unit", ",", "message_index", ":", "_message_index", ",", "payload", ":", "{", "asset", ":", "asset", ",", "denomination", ":", "denomination", ",", "inputs", ":", "[", "input", "]", ",", "outputs", ":", "outputs", "}", ",", "output_index", ":", "_output_index", ",", "output", ":", "output", "}", ";", "arrPrivateElements", ".", "push", "(", "objPrivateElement", ")", ";", "(", "input", ".", "type", "===", "'issue'", ")", "?", "handlePrivateElements", "(", "arrPrivateElements", ")", ":", "readPayloadAndGoUp", "(", "input", ".", "unit", ",", "input", ".", "message_index", ",", "input", ".", "output_index", ")", ";", "}", ")", ";", "}", ")", ";", "}", "var", "input", "=", "payload", ".", "inputs", "[", "0", "]", ";", "(", "input", ".", "type", "===", "'issue'", ")", "?", "handlePrivateElements", "(", "arrPrivateElements", ")", ":", "readPayloadAndGoUp", "(", "input", ".", "unit", ",", "input", ".", "message_index", ",", "input", ".", "output_index", ")", ";", "}" ]
this function receives fully open payload
[ "this", "function", "receives", "fully", "open", "payload" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/indivisible_asset.js#L602-L704
15,282
byteball/ocore
sqlite_pool.js
query
function query(){ //console.log(arguments[0]); var self = this; var args = arguments; var last_arg = args[args.length - 1]; var bHasCallback = (typeof last_arg === 'function'); if (!bHasCallback) // no callback last_arg = function(){}; var count_arguments_without_callback = bHasCallback ? (args.length-1) : args.length; var new_args = []; for (var i=0; i<count_arguments_without_callback; i++) // except callback new_args.push(args[i]); if (!bHasCallback && !bCordova) return new Promise(function(resolve){ new_args.push(resolve); self.query.apply(self, new_args); }); takeConnectionFromPool(function(connection){ // add callback that releases the connection before calling the supplied callback new_args.push(function(rows){ connection.release(); last_arg(rows); }); connection.query.apply(connection, new_args); }); }
javascript
function query(){ //console.log(arguments[0]); var self = this; var args = arguments; var last_arg = args[args.length - 1]; var bHasCallback = (typeof last_arg === 'function'); if (!bHasCallback) // no callback last_arg = function(){}; var count_arguments_without_callback = bHasCallback ? (args.length-1) : args.length; var new_args = []; for (var i=0; i<count_arguments_without_callback; i++) // except callback new_args.push(args[i]); if (!bHasCallback && !bCordova) return new Promise(function(resolve){ new_args.push(resolve); self.query.apply(self, new_args); }); takeConnectionFromPool(function(connection){ // add callback that releases the connection before calling the supplied callback new_args.push(function(rows){ connection.release(); last_arg(rows); }); connection.query.apply(connection, new_args); }); }
[ "function", "query", "(", ")", "{", "//console.log(arguments[0]);", "var", "self", "=", "this", ";", "var", "args", "=", "arguments", ";", "var", "last_arg", "=", "args", "[", "args", ".", "length", "-", "1", "]", ";", "var", "bHasCallback", "=", "(", "typeof", "last_arg", "===", "'function'", ")", ";", "if", "(", "!", "bHasCallback", ")", "// no callback", "last_arg", "=", "function", "(", ")", "{", "}", ";", "var", "count_arguments_without_callback", "=", "bHasCallback", "?", "(", "args", ".", "length", "-", "1", ")", ":", "args", ".", "length", ";", "var", "new_args", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "count_arguments_without_callback", ";", "i", "++", ")", "// except callback", "new_args", ".", "push", "(", "args", "[", "i", "]", ")", ";", "if", "(", "!", "bHasCallback", "&&", "!", "bCordova", ")", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "new_args", ".", "push", "(", "resolve", ")", ";", "self", ".", "query", ".", "apply", "(", "self", ",", "new_args", ")", ";", "}", ")", ";", "takeConnectionFromPool", "(", "function", "(", "connection", ")", "{", "// add callback that releases the connection before calling the supplied callback", "new_args", ".", "push", "(", "function", "(", "rows", ")", "{", "connection", ".", "release", "(", ")", ";", "last_arg", "(", "rows", ")", ";", "}", ")", ";", "connection", ".", "query", ".", "apply", "(", "connection", ",", "new_args", ")", ";", "}", ")", ";", "}" ]
takes a connection from the pool, executes the single query on this connection, and immediately releases the connection
[ "takes", "a", "connection", "from", "the", "pool", "executes", "the", "single", "query", "on", "this", "connection", "and", "immediately", "releases", "the", "connection" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/sqlite_pool.js#L223-L250
15,283
byteball/ocore
network.js
sendJoint
function sendJoint(ws, objJoint, tag) { console.log('sending joint identified by unit ' + objJoint.unit.unit + ' to', ws.peer); tag ? sendResponse(ws, tag, {joint: objJoint}) : sendJustsaying(ws, 'joint', objJoint); }
javascript
function sendJoint(ws, objJoint, tag) { console.log('sending joint identified by unit ' + objJoint.unit.unit + ' to', ws.peer); tag ? sendResponse(ws, tag, {joint: objJoint}) : sendJustsaying(ws, 'joint', objJoint); }
[ "function", "sendJoint", "(", "ws", ",", "objJoint", ",", "tag", ")", "{", "console", ".", "log", "(", "'sending joint identified by unit '", "+", "objJoint", ".", "unit", ".", "unit", "+", "' to'", ",", "ws", ".", "peer", ")", ";", "tag", "?", "sendResponse", "(", "ws", ",", "tag", ",", "{", "joint", ":", "objJoint", "}", ")", ":", "sendJustsaying", "(", "ws", ",", "'joint'", ",", "objJoint", ")", ";", "}" ]
joints sent as justsaying or as response to a request
[ "joints", "sent", "as", "justsaying", "or", "as", "response", "to", "a", "request" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/network.js#L714-L717
15,284
byteball/ocore
network.js
postJointToLightVendor
function postJointToLightVendor(objJoint, handleResponse) { console.log('posting joint identified by unit ' + objJoint.unit.unit + ' to light vendor'); requestFromLightVendor('post_joint', objJoint, function(ws, request, response){ handleResponse(response); }); }
javascript
function postJointToLightVendor(objJoint, handleResponse) { console.log('posting joint identified by unit ' + objJoint.unit.unit + ' to light vendor'); requestFromLightVendor('post_joint', objJoint, function(ws, request, response){ handleResponse(response); }); }
[ "function", "postJointToLightVendor", "(", "objJoint", ",", "handleResponse", ")", "{", "console", ".", "log", "(", "'posting joint identified by unit '", "+", "objJoint", ".", "unit", ".", "unit", "+", "' to light vendor'", ")", ";", "requestFromLightVendor", "(", "'post_joint'", ",", "objJoint", ",", "function", "(", "ws", ",", "request", ",", "response", ")", "{", "handleResponse", "(", "response", ")", ";", "}", ")", ";", "}" ]
sent by light clients to their vendors
[ "sent", "by", "light", "clients", "to", "their", "vendors" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/network.js#L720-L725
15,285
byteball/ocore
network.js
function(purged_unit, peer){ var ws = getPeerWebSocket(peer); if (ws) sendErrorResult(ws, purged_unit, "error on (indirect) parent unit "+objJoint.unit.unit+": "+error); }
javascript
function(purged_unit, peer){ var ws = getPeerWebSocket(peer); if (ws) sendErrorResult(ws, purged_unit, "error on (indirect) parent unit "+objJoint.unit.unit+": "+error); }
[ "function", "(", "purged_unit", ",", "peer", ")", "{", "var", "ws", "=", "getPeerWebSocket", "(", "peer", ")", ";", "if", "(", "ws", ")", "sendErrorResult", "(", "ws", ",", "purged_unit", ",", "\"error on (indirect) parent unit \"", "+", "objJoint", ".", "unit", ".", "unit", "+", "\": \"", "+", "error", ")", ";", "}" ]
this callback is called for each dependent unit
[ "this", "callback", "is", "called", "for", "each", "dependent", "unit" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/network.js#L906-L910
15,286
byteball/ocore
network.js
handlePostedJoint
function handlePostedJoint(ws, objJoint, onDone){ if (!objJoint || !objJoint.unit || !objJoint.unit.unit) return onDone('no unit'); var unit = objJoint.unit.unit; delete objJoint.unit.main_chain_index; handleJoint(ws, objJoint, false, { ifUnitInWork: function(){ onDone("already handling this unit"); }, ifUnitError: function(error){ onDone(error); }, ifJointError: function(error){ onDone(error); }, ifNeedHashTree: function(){ onDone("need hash tree"); }, ifNeedParentUnits: function(arrMissingUnits){ onDone("unknown parents"); }, ifOk: function(){ onDone(); // forward to other peers if (!bCatchingUp && !conf.bLight) forwardJoint(ws, objJoint); delete assocUnitsInWork[unit]; }, ifOkUnsigned: function(){ delete assocUnitsInWork[unit]; onDone("you can't send unsigned units"); }, ifKnown: function(){ if (objJoint.unsigned) return onDone("you can't send unsigned units"); onDone("known"); writeEvent('known_good', ws.host); }, ifKnownBad: function(){ onDone("known bad"); writeEvent('known_bad', ws.host); }, ifKnownUnverified: function(){ // impossible unless the peer also sends this joint by 'joint' justsaying onDone("known unverified"); delete assocUnitsInWork[unit]; } }); }
javascript
function handlePostedJoint(ws, objJoint, onDone){ if (!objJoint || !objJoint.unit || !objJoint.unit.unit) return onDone('no unit'); var unit = objJoint.unit.unit; delete objJoint.unit.main_chain_index; handleJoint(ws, objJoint, false, { ifUnitInWork: function(){ onDone("already handling this unit"); }, ifUnitError: function(error){ onDone(error); }, ifJointError: function(error){ onDone(error); }, ifNeedHashTree: function(){ onDone("need hash tree"); }, ifNeedParentUnits: function(arrMissingUnits){ onDone("unknown parents"); }, ifOk: function(){ onDone(); // forward to other peers if (!bCatchingUp && !conf.bLight) forwardJoint(ws, objJoint); delete assocUnitsInWork[unit]; }, ifOkUnsigned: function(){ delete assocUnitsInWork[unit]; onDone("you can't send unsigned units"); }, ifKnown: function(){ if (objJoint.unsigned) return onDone("you can't send unsigned units"); onDone("known"); writeEvent('known_good', ws.host); }, ifKnownBad: function(){ onDone("known bad"); writeEvent('known_bad', ws.host); }, ifKnownUnverified: function(){ // impossible unless the peer also sends this joint by 'joint' justsaying onDone("known unverified"); delete assocUnitsInWork[unit]; } }); }
[ "function", "handlePostedJoint", "(", "ws", ",", "objJoint", ",", "onDone", ")", "{", "if", "(", "!", "objJoint", "||", "!", "objJoint", ".", "unit", "||", "!", "objJoint", ".", "unit", ".", "unit", ")", "return", "onDone", "(", "'no unit'", ")", ";", "var", "unit", "=", "objJoint", ".", "unit", ".", "unit", ";", "delete", "objJoint", ".", "unit", ".", "main_chain_index", ";", "handleJoint", "(", "ws", ",", "objJoint", ",", "false", ",", "{", "ifUnitInWork", ":", "function", "(", ")", "{", "onDone", "(", "\"already handling this unit\"", ")", ";", "}", ",", "ifUnitError", ":", "function", "(", "error", ")", "{", "onDone", "(", "error", ")", ";", "}", ",", "ifJointError", ":", "function", "(", "error", ")", "{", "onDone", "(", "error", ")", ";", "}", ",", "ifNeedHashTree", ":", "function", "(", ")", "{", "onDone", "(", "\"need hash tree\"", ")", ";", "}", ",", "ifNeedParentUnits", ":", "function", "(", "arrMissingUnits", ")", "{", "onDone", "(", "\"unknown parents\"", ")", ";", "}", ",", "ifOk", ":", "function", "(", ")", "{", "onDone", "(", ")", ";", "// forward to other peers", "if", "(", "!", "bCatchingUp", "&&", "!", "conf", ".", "bLight", ")", "forwardJoint", "(", "ws", ",", "objJoint", ")", ";", "delete", "assocUnitsInWork", "[", "unit", "]", ";", "}", ",", "ifOkUnsigned", ":", "function", "(", ")", "{", "delete", "assocUnitsInWork", "[", "unit", "]", ";", "onDone", "(", "\"you can't send unsigned units\"", ")", ";", "}", ",", "ifKnown", ":", "function", "(", ")", "{", "if", "(", "objJoint", ".", "unsigned", ")", "return", "onDone", "(", "\"you can't send unsigned units\"", ")", ";", "onDone", "(", "\"known\"", ")", ";", "writeEvent", "(", "'known_good'", ",", "ws", ".", "host", ")", ";", "}", ",", "ifKnownBad", ":", "function", "(", ")", "{", "onDone", "(", "\"known bad\"", ")", ";", "writeEvent", "(", "'known_bad'", ",", "ws", ".", "host", ")", ";", "}", ",", "ifKnownUnverified", ":", "function", "(", ")", "{", "// impossible unless the peer also sends this joint by 'joint' justsaying", "onDone", "(", "\"known unverified\"", ")", ";", "delete", "assocUnitsInWork", "[", "unit", "]", ";", "}", "}", ")", ";", "}" ]
handle joint posted to me by a light client
[ "handle", "joint", "posted", "to", "me", "by", "a", "light", "client" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/network.js#L1033-L1085
15,287
byteball/ocore
network.js
handleOnlinePrivatePayment
function handleOnlinePrivatePayment(ws, arrPrivateElements, bViaHub, callbacks){ if (!ValidationUtils.isNonemptyArray(arrPrivateElements)) return callbacks.ifError("private_payment content must be non-empty array"); var unit = arrPrivateElements[0].unit; var message_index = arrPrivateElements[0].message_index; var output_index = arrPrivateElements[0].payload.denomination ? arrPrivateElements[0].output_index : -1; var savePrivatePayment = function(cb){ // we may receive the same unit and message index but different output indexes if recipient and cosigner are on the same device. // in this case, we also receive the same (unit, message_index, output_index) twice - as cosigner and as recipient. That's why IGNORE. db.query( "INSERT "+db.getIgnore()+" INTO unhandled_private_payments (unit, message_index, output_index, json, peer) VALUES (?,?,?,?,?)", [unit, message_index, output_index, JSON.stringify(arrPrivateElements), bViaHub ? '' : ws.peer], // forget peer if received via hub function(){ callbacks.ifQueued(); if (cb) cb(); } ); }; if (conf.bLight && arrPrivateElements.length > 1){ savePrivatePayment(function(){ updateLinkProofsOfPrivateChain(arrPrivateElements, unit, message_index, output_index); rerequestLostJointsOfPrivatePayments(); // will request the head element }); return; } joint_storage.checkIfNewUnit(unit, { ifKnown: function(){ //assocUnitsInWork[unit] = true; privatePayment.validateAndSavePrivatePaymentChain(arrPrivateElements, { ifOk: function(){ //delete assocUnitsInWork[unit]; callbacks.ifAccepted(unit); eventBus.emit("new_my_transactions", [unit]); }, ifError: function(error){ //delete assocUnitsInWork[unit]; callbacks.ifValidationError(unit, error); }, ifWaitingForChain: function(){ savePrivatePayment(); } }); }, ifNew: function(){ savePrivatePayment(); // if received via hub, I'm requesting from the same hub, thus telling the hub that this unit contains a private payment for me. // It would be better to request missing joints from somebody else requestNewMissingJoints(ws, [unit]); }, ifKnownUnverified: savePrivatePayment, ifKnownBad: function(){ callbacks.ifValidationError(unit, "known bad"); } }); }
javascript
function handleOnlinePrivatePayment(ws, arrPrivateElements, bViaHub, callbacks){ if (!ValidationUtils.isNonemptyArray(arrPrivateElements)) return callbacks.ifError("private_payment content must be non-empty array"); var unit = arrPrivateElements[0].unit; var message_index = arrPrivateElements[0].message_index; var output_index = arrPrivateElements[0].payload.denomination ? arrPrivateElements[0].output_index : -1; var savePrivatePayment = function(cb){ // we may receive the same unit and message index but different output indexes if recipient and cosigner are on the same device. // in this case, we also receive the same (unit, message_index, output_index) twice - as cosigner and as recipient. That's why IGNORE. db.query( "INSERT "+db.getIgnore()+" INTO unhandled_private_payments (unit, message_index, output_index, json, peer) VALUES (?,?,?,?,?)", [unit, message_index, output_index, JSON.stringify(arrPrivateElements), bViaHub ? '' : ws.peer], // forget peer if received via hub function(){ callbacks.ifQueued(); if (cb) cb(); } ); }; if (conf.bLight && arrPrivateElements.length > 1){ savePrivatePayment(function(){ updateLinkProofsOfPrivateChain(arrPrivateElements, unit, message_index, output_index); rerequestLostJointsOfPrivatePayments(); // will request the head element }); return; } joint_storage.checkIfNewUnit(unit, { ifKnown: function(){ //assocUnitsInWork[unit] = true; privatePayment.validateAndSavePrivatePaymentChain(arrPrivateElements, { ifOk: function(){ //delete assocUnitsInWork[unit]; callbacks.ifAccepted(unit); eventBus.emit("new_my_transactions", [unit]); }, ifError: function(error){ //delete assocUnitsInWork[unit]; callbacks.ifValidationError(unit, error); }, ifWaitingForChain: function(){ savePrivatePayment(); } }); }, ifNew: function(){ savePrivatePayment(); // if received via hub, I'm requesting from the same hub, thus telling the hub that this unit contains a private payment for me. // It would be better to request missing joints from somebody else requestNewMissingJoints(ws, [unit]); }, ifKnownUnverified: savePrivatePayment, ifKnownBad: function(){ callbacks.ifValidationError(unit, "known bad"); } }); }
[ "function", "handleOnlinePrivatePayment", "(", "ws", ",", "arrPrivateElements", ",", "bViaHub", ",", "callbacks", ")", "{", "if", "(", "!", "ValidationUtils", ".", "isNonemptyArray", "(", "arrPrivateElements", ")", ")", "return", "callbacks", ".", "ifError", "(", "\"private_payment content must be non-empty array\"", ")", ";", "var", "unit", "=", "arrPrivateElements", "[", "0", "]", ".", "unit", ";", "var", "message_index", "=", "arrPrivateElements", "[", "0", "]", ".", "message_index", ";", "var", "output_index", "=", "arrPrivateElements", "[", "0", "]", ".", "payload", ".", "denomination", "?", "arrPrivateElements", "[", "0", "]", ".", "output_index", ":", "-", "1", ";", "var", "savePrivatePayment", "=", "function", "(", "cb", ")", "{", "// we may receive the same unit and message index but different output indexes if recipient and cosigner are on the same device.", "// in this case, we also receive the same (unit, message_index, output_index) twice - as cosigner and as recipient. That's why IGNORE.", "db", ".", "query", "(", "\"INSERT \"", "+", "db", ".", "getIgnore", "(", ")", "+", "\" INTO unhandled_private_payments (unit, message_index, output_index, json, peer) VALUES (?,?,?,?,?)\"", ",", "[", "unit", ",", "message_index", ",", "output_index", ",", "JSON", ".", "stringify", "(", "arrPrivateElements", ")", ",", "bViaHub", "?", "''", ":", "ws", ".", "peer", "]", ",", "// forget peer if received via hub", "function", "(", ")", "{", "callbacks", ".", "ifQueued", "(", ")", ";", "if", "(", "cb", ")", "cb", "(", ")", ";", "}", ")", ";", "}", ";", "if", "(", "conf", ".", "bLight", "&&", "arrPrivateElements", ".", "length", ">", "1", ")", "{", "savePrivatePayment", "(", "function", "(", ")", "{", "updateLinkProofsOfPrivateChain", "(", "arrPrivateElements", ",", "unit", ",", "message_index", ",", "output_index", ")", ";", "rerequestLostJointsOfPrivatePayments", "(", ")", ";", "// will request the head element", "}", ")", ";", "return", ";", "}", "joint_storage", ".", "checkIfNewUnit", "(", "unit", ",", "{", "ifKnown", ":", "function", "(", ")", "{", "//assocUnitsInWork[unit] = true;", "privatePayment", ".", "validateAndSavePrivatePaymentChain", "(", "arrPrivateElements", ",", "{", "ifOk", ":", "function", "(", ")", "{", "//delete assocUnitsInWork[unit];", "callbacks", ".", "ifAccepted", "(", "unit", ")", ";", "eventBus", ".", "emit", "(", "\"new_my_transactions\"", ",", "[", "unit", "]", ")", ";", "}", ",", "ifError", ":", "function", "(", "error", ")", "{", "//delete assocUnitsInWork[unit];", "callbacks", ".", "ifValidationError", "(", "unit", ",", "error", ")", ";", "}", ",", "ifWaitingForChain", ":", "function", "(", ")", "{", "savePrivatePayment", "(", ")", ";", "}", "}", ")", ";", "}", ",", "ifNew", ":", "function", "(", ")", "{", "savePrivatePayment", "(", ")", ";", "// if received via hub, I'm requesting from the same hub, thus telling the hub that this unit contains a private payment for me.", "// It would be better to request missing joints from somebody else", "requestNewMissingJoints", "(", "ws", ",", "[", "unit", "]", ")", ";", "}", ",", "ifKnownUnverified", ":", "savePrivatePayment", ",", "ifKnownBad", ":", "function", "(", ")", "{", "callbacks", ".", "ifValidationError", "(", "unit", ",", "\"known bad\"", ")", ";", "}", "}", ")", ";", "}" ]
handles one private payload and its chain
[ "handles", "one", "private", "payload", "and", "its", "chain" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/network.js#L1703-L1762
15,288
byteball/ocore
network.js
checkThatEachChainElementIncludesThePrevious
function checkThatEachChainElementIncludesThePrevious(arrPrivateElements, handleResult){ if (arrPrivateElements.length === 1) // an issue return handleResult(true); var arrUnits = arrPrivateElements.map(function(objPrivateElement){ return objPrivateElement.unit; }); requestFromLightVendor('light/get_link_proofs', arrUnits, function(ws, request, response){ if (response.error) return handleResult(null); // undefined result var arrChain = response; if (!ValidationUtils.isNonemptyArray(arrChain)) return handleResult(null); // undefined result light.processLinkProofs(arrUnits, arrChain, { ifError: function(err){ console.log("linkproof validation failed: "+err); throw Error(err); handleResult(false); }, ifOk: function(){ console.log("linkproof validated ok"); handleResult(true); } }); }); }
javascript
function checkThatEachChainElementIncludesThePrevious(arrPrivateElements, handleResult){ if (arrPrivateElements.length === 1) // an issue return handleResult(true); var arrUnits = arrPrivateElements.map(function(objPrivateElement){ return objPrivateElement.unit; }); requestFromLightVendor('light/get_link_proofs', arrUnits, function(ws, request, response){ if (response.error) return handleResult(null); // undefined result var arrChain = response; if (!ValidationUtils.isNonemptyArray(arrChain)) return handleResult(null); // undefined result light.processLinkProofs(arrUnits, arrChain, { ifError: function(err){ console.log("linkproof validation failed: "+err); throw Error(err); handleResult(false); }, ifOk: function(){ console.log("linkproof validated ok"); handleResult(true); } }); }); }
[ "function", "checkThatEachChainElementIncludesThePrevious", "(", "arrPrivateElements", ",", "handleResult", ")", "{", "if", "(", "arrPrivateElements", ".", "length", "===", "1", ")", "// an issue", "return", "handleResult", "(", "true", ")", ";", "var", "arrUnits", "=", "arrPrivateElements", ".", "map", "(", "function", "(", "objPrivateElement", ")", "{", "return", "objPrivateElement", ".", "unit", ";", "}", ")", ";", "requestFromLightVendor", "(", "'light/get_link_proofs'", ",", "arrUnits", ",", "function", "(", "ws", ",", "request", ",", "response", ")", "{", "if", "(", "response", ".", "error", ")", "return", "handleResult", "(", "null", ")", ";", "// undefined result", "var", "arrChain", "=", "response", ";", "if", "(", "!", "ValidationUtils", ".", "isNonemptyArray", "(", "arrChain", ")", ")", "return", "handleResult", "(", "null", ")", ";", "// undefined result", "light", ".", "processLinkProofs", "(", "arrUnits", ",", "arrChain", ",", "{", "ifError", ":", "function", "(", "err", ")", "{", "console", ".", "log", "(", "\"linkproof validation failed: \"", "+", "err", ")", ";", "throw", "Error", "(", "err", ")", ";", "handleResult", "(", "false", ")", ";", "}", ",", "ifOk", ":", "function", "(", ")", "{", "console", ".", "log", "(", "\"linkproof validated ok\"", ")", ";", "handleResult", "(", "true", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
light only Note that we are leaking to light vendor information about the full chain. If the light vendor was a party to any previous transaction in this chain, he'll know how much we received.
[ "light", "only", "Note", "that", "we", "are", "leaking", "to", "light", "vendor", "information", "about", "the", "full", "chain", ".", "If", "the", "light", "vendor", "was", "a", "party", "to", "any", "previous", "transaction", "in", "this", "chain", "he", "ll", "know", "how", "much", "we", "received", "." ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/network.js#L1960-L1982
15,289
byteball/ocore
wallet_defined_by_keys.js
checkAndFinalizeWallet
function checkAndFinalizeWallet(wallet, onDone){ db.query("SELECT member_ready_date FROM wallets LEFT JOIN extended_pubkeys USING(wallet) WHERE wallets.wallet=?", [wallet], function(rows){ if (rows.length === 0){ // wallet not created yet or already deleted // throw Error("no wallet in checkAndFinalizeWallet"); console.log("no wallet in checkAndFinalizeWallet"); return onDone ? onDone() : null; } if (rows.some(function(row){ return !row.member_ready_date; })) return onDone ? onDone() : null; db.query("UPDATE wallets SET ready_date="+db.getNow()+" WHERE wallet=? AND ready_date IS NULL", [wallet], function(){ if (onDone) onDone(); eventBus.emit('wallet_completed', wallet); }); }); }
javascript
function checkAndFinalizeWallet(wallet, onDone){ db.query("SELECT member_ready_date FROM wallets LEFT JOIN extended_pubkeys USING(wallet) WHERE wallets.wallet=?", [wallet], function(rows){ if (rows.length === 0){ // wallet not created yet or already deleted // throw Error("no wallet in checkAndFinalizeWallet"); console.log("no wallet in checkAndFinalizeWallet"); return onDone ? onDone() : null; } if (rows.some(function(row){ return !row.member_ready_date; })) return onDone ? onDone() : null; db.query("UPDATE wallets SET ready_date="+db.getNow()+" WHERE wallet=? AND ready_date IS NULL", [wallet], function(){ if (onDone) onDone(); eventBus.emit('wallet_completed', wallet); }); }); }
[ "function", "checkAndFinalizeWallet", "(", "wallet", ",", "onDone", ")", "{", "db", ".", "query", "(", "\"SELECT member_ready_date FROM wallets LEFT JOIN extended_pubkeys USING(wallet) WHERE wallets.wallet=?\"", ",", "[", "wallet", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "===", "0", ")", "{", "// wallet not created yet or already deleted", "//\tthrow Error(\"no wallet in checkAndFinalizeWallet\");", "console", ".", "log", "(", "\"no wallet in checkAndFinalizeWallet\"", ")", ";", "return", "onDone", "?", "onDone", "(", ")", ":", "null", ";", "}", "if", "(", "rows", ".", "some", "(", "function", "(", "row", ")", "{", "return", "!", "row", ".", "member_ready_date", ";", "}", ")", ")", "return", "onDone", "?", "onDone", "(", ")", ":", "null", ";", "db", ".", "query", "(", "\"UPDATE wallets SET ready_date=\"", "+", "db", ".", "getNow", "(", ")", "+", "\" WHERE wallet=? AND ready_date IS NULL\"", ",", "[", "wallet", "]", ",", "function", "(", ")", "{", "if", "(", "onDone", ")", "onDone", "(", ")", ";", "eventBus", ".", "emit", "(", "'wallet_completed'", ",", "wallet", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
check that all members agree that the wallet is fully approved now
[ "check", "that", "all", "members", "agree", "that", "the", "wallet", "is", "fully", "approved", "now" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/wallet_defined_by_keys.js#L120-L135
15,290
byteball/ocore
wallet_defined_by_keys.js
createWallet
function createWallet(xPubKey, account, arrWalletDefinitionTemplate, walletName, isSingleAddress, handleWallet){ var wallet = crypto.createHash("sha256").update(xPubKey, "utf8").digest("base64"); console.log('will create wallet '+wallet); var arrDeviceAddresses = getDeviceAddresses(arrWalletDefinitionTemplate); addWallet(wallet, xPubKey, account, arrWalletDefinitionTemplate, function(){ handleWallet(wallet); if (arrDeviceAddresses.length === 1) // single sig return; console.log("will send offers"); // this continues in parallel while the callback handleWallet was already called // We need arrOtherCosigners to make sure all cosigners know the pubkeys of all other cosigners, even when they were not paired. // For example, there are 3 cosigners: A (me), B, and C. A is paired with B, A is paired with C, but B is not paired with C. device.readCorrespondentsByDeviceAddresses(arrDeviceAddresses, function(arrOtherCosigners){ if (arrOtherCosigners.length !== arrDeviceAddresses.length - 1) throw Error("incorrect length of other cosigners"); arrDeviceAddresses.forEach(function(device_address){ if (device_address === device.getMyDeviceAddress()) return; console.log("sending offer to "+device_address); sendOfferToCreateNewWallet(device_address, wallet, arrWalletDefinitionTemplate, walletName, arrOtherCosigners, isSingleAddress, null); sendMyXPubKey(device_address, wallet, xPubKey); }); }); }); }
javascript
function createWallet(xPubKey, account, arrWalletDefinitionTemplate, walletName, isSingleAddress, handleWallet){ var wallet = crypto.createHash("sha256").update(xPubKey, "utf8").digest("base64"); console.log('will create wallet '+wallet); var arrDeviceAddresses = getDeviceAddresses(arrWalletDefinitionTemplate); addWallet(wallet, xPubKey, account, arrWalletDefinitionTemplate, function(){ handleWallet(wallet); if (arrDeviceAddresses.length === 1) // single sig return; console.log("will send offers"); // this continues in parallel while the callback handleWallet was already called // We need arrOtherCosigners to make sure all cosigners know the pubkeys of all other cosigners, even when they were not paired. // For example, there are 3 cosigners: A (me), B, and C. A is paired with B, A is paired with C, but B is not paired with C. device.readCorrespondentsByDeviceAddresses(arrDeviceAddresses, function(arrOtherCosigners){ if (arrOtherCosigners.length !== arrDeviceAddresses.length - 1) throw Error("incorrect length of other cosigners"); arrDeviceAddresses.forEach(function(device_address){ if (device_address === device.getMyDeviceAddress()) return; console.log("sending offer to "+device_address); sendOfferToCreateNewWallet(device_address, wallet, arrWalletDefinitionTemplate, walletName, arrOtherCosigners, isSingleAddress, null); sendMyXPubKey(device_address, wallet, xPubKey); }); }); }); }
[ "function", "createWallet", "(", "xPubKey", ",", "account", ",", "arrWalletDefinitionTemplate", ",", "walletName", ",", "isSingleAddress", ",", "handleWallet", ")", "{", "var", "wallet", "=", "crypto", ".", "createHash", "(", "\"sha256\"", ")", ".", "update", "(", "xPubKey", ",", "\"utf8\"", ")", ".", "digest", "(", "\"base64\"", ")", ";", "console", ".", "log", "(", "'will create wallet '", "+", "wallet", ")", ";", "var", "arrDeviceAddresses", "=", "getDeviceAddresses", "(", "arrWalletDefinitionTemplate", ")", ";", "addWallet", "(", "wallet", ",", "xPubKey", ",", "account", ",", "arrWalletDefinitionTemplate", ",", "function", "(", ")", "{", "handleWallet", "(", "wallet", ")", ";", "if", "(", "arrDeviceAddresses", ".", "length", "===", "1", ")", "// single sig", "return", ";", "console", ".", "log", "(", "\"will send offers\"", ")", ";", "// this continues in parallel while the callback handleWallet was already called", "// We need arrOtherCosigners to make sure all cosigners know the pubkeys of all other cosigners, even when they were not paired.", "// For example, there are 3 cosigners: A (me), B, and C. A is paired with B, A is paired with C, but B is not paired with C.", "device", ".", "readCorrespondentsByDeviceAddresses", "(", "arrDeviceAddresses", ",", "function", "(", "arrOtherCosigners", ")", "{", "if", "(", "arrOtherCosigners", ".", "length", "!==", "arrDeviceAddresses", ".", "length", "-", "1", ")", "throw", "Error", "(", "\"incorrect length of other cosigners\"", ")", ";", "arrDeviceAddresses", ".", "forEach", "(", "function", "(", "device_address", ")", "{", "if", "(", "device_address", "===", "device", ".", "getMyDeviceAddress", "(", ")", ")", "return", ";", "console", ".", "log", "(", "\"sending offer to \"", "+", "device_address", ")", ";", "sendOfferToCreateNewWallet", "(", "device_address", ",", "wallet", ",", "arrWalletDefinitionTemplate", ",", "walletName", ",", "arrOtherCosigners", ",", "isSingleAddress", ",", "null", ")", ";", "sendMyXPubKey", "(", "device_address", ",", "wallet", ",", "xPubKey", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
initiator of the new wallet creates records about itself and sends requests to other devices
[ "initiator", "of", "the", "new", "wallet", "creates", "records", "about", "itself", "and", "sends", "requests", "to", "other", "devices" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/wallet_defined_by_keys.js#L231-L255
15,291
byteball/ocore
wallet_defined_by_keys.js
approveWallet
function approveWallet(wallet, xPubKey, account, arrWalletDefinitionTemplate, arrOtherCosigners, onDone){ var arrDeviceAddresses = getDeviceAddresses(arrWalletDefinitionTemplate); device.addIndirectCorrespondents(arrOtherCosigners, function(){ addWallet(wallet, xPubKey, account, arrWalletDefinitionTemplate, function(){ arrDeviceAddresses.forEach(function(device_address){ if (device_address !== device.getMyDeviceAddress()) sendMyXPubKey(device_address, wallet, xPubKey); }); if (onDone) onDone(); }); }); }
javascript
function approveWallet(wallet, xPubKey, account, arrWalletDefinitionTemplate, arrOtherCosigners, onDone){ var arrDeviceAddresses = getDeviceAddresses(arrWalletDefinitionTemplate); device.addIndirectCorrespondents(arrOtherCosigners, function(){ addWallet(wallet, xPubKey, account, arrWalletDefinitionTemplate, function(){ arrDeviceAddresses.forEach(function(device_address){ if (device_address !== device.getMyDeviceAddress()) sendMyXPubKey(device_address, wallet, xPubKey); }); if (onDone) onDone(); }); }); }
[ "function", "approveWallet", "(", "wallet", ",", "xPubKey", ",", "account", ",", "arrWalletDefinitionTemplate", ",", "arrOtherCosigners", ",", "onDone", ")", "{", "var", "arrDeviceAddresses", "=", "getDeviceAddresses", "(", "arrWalletDefinitionTemplate", ")", ";", "device", ".", "addIndirectCorrespondents", "(", "arrOtherCosigners", ",", "function", "(", ")", "{", "addWallet", "(", "wallet", ",", "xPubKey", ",", "account", ",", "arrWalletDefinitionTemplate", ",", "function", "(", ")", "{", "arrDeviceAddresses", ".", "forEach", "(", "function", "(", "device_address", ")", "{", "if", "(", "device_address", "!==", "device", ".", "getMyDeviceAddress", "(", ")", ")", "sendMyXPubKey", "(", "device_address", ",", "wallet", ",", "xPubKey", ")", ";", "}", ")", ";", "if", "(", "onDone", ")", "onDone", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
called from UI after user confirms creation of wallet initiated by another device
[ "called", "from", "UI", "after", "user", "confirms", "creation", "of", "wallet", "initiated", "by", "another", "device" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/wallet_defined_by_keys.js#L287-L299
15,292
byteball/ocore
wallet_defined_by_keys.js
deleteWallet
function deleteWallet(wallet, rejector_device_address, onDone){ db.query("SELECT approval_date FROM extended_pubkeys WHERE wallet=? AND device_address=?", [wallet, rejector_device_address], function(rows){ if (rows.length === 0) // you are not a member device return onDone(); if (rows[0].approval_date) // you've already approved this wallet, you can't change your mind return onDone(); db.query("SELECT device_address FROM extended_pubkeys WHERE wallet=?", [wallet], function(rows){ var arrMemberAddresses = rows.map(function(row){ return row.device_address; }); var arrQueries = []; db.addQuery(arrQueries, "DELETE FROM extended_pubkeys WHERE wallet=?", [wallet]); db.addQuery(arrQueries, "DELETE FROM wallet_signing_paths WHERE wallet=?", [wallet]); db.addQuery(arrQueries, "DELETE FROM wallets WHERE wallet=?", [wallet]); // delete unused indirect correspondents db.addQuery( arrQueries, "DELETE FROM correspondent_devices WHERE is_indirect=1 AND device_address IN(?) AND NOT EXISTS ( \n\ SELECT * FROM extended_pubkeys WHERE extended_pubkeys.device_address=correspondent_devices.device_address \n\ )", [arrMemberAddresses] ); async.series(arrQueries, function(){ eventBus.emit('wallet_declined', wallet, rejector_device_address); onDone(); }); }); }); }
javascript
function deleteWallet(wallet, rejector_device_address, onDone){ db.query("SELECT approval_date FROM extended_pubkeys WHERE wallet=? AND device_address=?", [wallet, rejector_device_address], function(rows){ if (rows.length === 0) // you are not a member device return onDone(); if (rows[0].approval_date) // you've already approved this wallet, you can't change your mind return onDone(); db.query("SELECT device_address FROM extended_pubkeys WHERE wallet=?", [wallet], function(rows){ var arrMemberAddresses = rows.map(function(row){ return row.device_address; }); var arrQueries = []; db.addQuery(arrQueries, "DELETE FROM extended_pubkeys WHERE wallet=?", [wallet]); db.addQuery(arrQueries, "DELETE FROM wallet_signing_paths WHERE wallet=?", [wallet]); db.addQuery(arrQueries, "DELETE FROM wallets WHERE wallet=?", [wallet]); // delete unused indirect correspondents db.addQuery( arrQueries, "DELETE FROM correspondent_devices WHERE is_indirect=1 AND device_address IN(?) AND NOT EXISTS ( \n\ SELECT * FROM extended_pubkeys WHERE extended_pubkeys.device_address=correspondent_devices.device_address \n\ )", [arrMemberAddresses] ); async.series(arrQueries, function(){ eventBus.emit('wallet_declined', wallet, rejector_device_address); onDone(); }); }); }); }
[ "function", "deleteWallet", "(", "wallet", ",", "rejector_device_address", ",", "onDone", ")", "{", "db", ".", "query", "(", "\"SELECT approval_date FROM extended_pubkeys WHERE wallet=? AND device_address=?\"", ",", "[", "wallet", ",", "rejector_device_address", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "===", "0", ")", "// you are not a member device", "return", "onDone", "(", ")", ";", "if", "(", "rows", "[", "0", "]", ".", "approval_date", ")", "// you've already approved this wallet, you can't change your mind", "return", "onDone", "(", ")", ";", "db", ".", "query", "(", "\"SELECT device_address FROM extended_pubkeys WHERE wallet=?\"", ",", "[", "wallet", "]", ",", "function", "(", "rows", ")", "{", "var", "arrMemberAddresses", "=", "rows", ".", "map", "(", "function", "(", "row", ")", "{", "return", "row", ".", "device_address", ";", "}", ")", ";", "var", "arrQueries", "=", "[", "]", ";", "db", ".", "addQuery", "(", "arrQueries", ",", "\"DELETE FROM extended_pubkeys WHERE wallet=?\"", ",", "[", "wallet", "]", ")", ";", "db", ".", "addQuery", "(", "arrQueries", ",", "\"DELETE FROM wallet_signing_paths WHERE wallet=?\"", ",", "[", "wallet", "]", ")", ";", "db", ".", "addQuery", "(", "arrQueries", ",", "\"DELETE FROM wallets WHERE wallet=?\"", ",", "[", "wallet", "]", ")", ";", "// delete unused indirect correspondents", "db", ".", "addQuery", "(", "arrQueries", ",", "\"DELETE FROM correspondent_devices WHERE is_indirect=1 AND device_address IN(?) AND NOT EXISTS ( \\n\\\n\t\t\t\t\tSELECT * FROM extended_pubkeys WHERE extended_pubkeys.device_address=correspondent_devices.device_address \\n\\\n\t\t\t\t)\"", ",", "[", "arrMemberAddresses", "]", ")", ";", "async", ".", "series", "(", "arrQueries", ",", "function", "(", ")", "{", "eventBus", ".", "emit", "(", "'wallet_declined'", ",", "wallet", ",", "rejector_device_address", ")", ";", "onDone", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
called from network, without user interaction One of the proposed cosigners declined wallet creation
[ "called", "from", "network", "without", "user", "interaction", "One", "of", "the", "proposed", "cosigners", "declined", "wallet", "creation" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/wallet_defined_by_keys.js#L329-L355
15,293
byteball/ocore
wallet_defined_by_keys.js
addNewAddress
function addNewAddress(wallet, is_change, address_index, address, handleError){ breadcrumbs.add('addNewAddress is_change='+is_change+', index='+address_index+', address='+address); db.query("SELECT 1 FROM wallets WHERE wallet=?", [wallet], function(rows){ if (rows.length === 0) return handleError("wallet "+wallet+" does not exist"); deriveAddress(wallet, is_change, address_index, function(new_address, arrDefinition){ if (new_address !== address) return handleError("I derived address "+new_address+", your address "+address); recordAddress(wallet, is_change, address_index, address, arrDefinition, function(){ eventBus.emit("new_wallet_address", address); handleError(); }); }); }); }
javascript
function addNewAddress(wallet, is_change, address_index, address, handleError){ breadcrumbs.add('addNewAddress is_change='+is_change+', index='+address_index+', address='+address); db.query("SELECT 1 FROM wallets WHERE wallet=?", [wallet], function(rows){ if (rows.length === 0) return handleError("wallet "+wallet+" does not exist"); deriveAddress(wallet, is_change, address_index, function(new_address, arrDefinition){ if (new_address !== address) return handleError("I derived address "+new_address+", your address "+address); recordAddress(wallet, is_change, address_index, address, arrDefinition, function(){ eventBus.emit("new_wallet_address", address); handleError(); }); }); }); }
[ "function", "addNewAddress", "(", "wallet", ",", "is_change", ",", "address_index", ",", "address", ",", "handleError", ")", "{", "breadcrumbs", ".", "add", "(", "'addNewAddress is_change='", "+", "is_change", "+", "', index='", "+", "address_index", "+", "', address='", "+", "address", ")", ";", "db", ".", "query", "(", "\"SELECT 1 FROM wallets WHERE wallet=?\"", ",", "[", "wallet", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "===", "0", ")", "return", "handleError", "(", "\"wallet \"", "+", "wallet", "+", "\" does not exist\"", ")", ";", "deriveAddress", "(", "wallet", ",", "is_change", ",", "address_index", ",", "function", "(", "new_address", ",", "arrDefinition", ")", "{", "if", "(", "new_address", "!==", "address", ")", "return", "handleError", "(", "\"I derived address \"", "+", "new_address", "+", "\", your address \"", "+", "address", ")", ";", "recordAddress", "(", "wallet", ",", "is_change", ",", "address_index", ",", "address", ",", "arrDefinition", ",", "function", "(", ")", "{", "eventBus", ".", "emit", "(", "\"new_wallet_address\"", ",", "address", ")", ";", "handleError", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
silently adds new address upon receiving a network message
[ "silently", "adds", "new", "address", "upon", "receiving", "a", "network", "message" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/wallet_defined_by_keys.js#L413-L427
15,294
byteball/ocore
wallet_defined_by_keys.js
issueOrSelectNextAddress
function issueOrSelectNextAddress(wallet, is_change, handleAddress){ readNextAddressIndex(wallet, is_change, function(next_index){ if (next_index < MAX_BIP44_GAP) return issueAddress(wallet, is_change, next_index, handleAddress); readLastUsedAddressIndex(wallet, is_change, function(last_used_index){ if (last_used_index === null || next_index - last_used_index >= MAX_BIP44_GAP) selectRandomAddress(wallet, is_change, last_used_index, handleAddress); else issueAddress(wallet, is_change, next_index, handleAddress); }); }); }
javascript
function issueOrSelectNextAddress(wallet, is_change, handleAddress){ readNextAddressIndex(wallet, is_change, function(next_index){ if (next_index < MAX_BIP44_GAP) return issueAddress(wallet, is_change, next_index, handleAddress); readLastUsedAddressIndex(wallet, is_change, function(last_used_index){ if (last_used_index === null || next_index - last_used_index >= MAX_BIP44_GAP) selectRandomAddress(wallet, is_change, last_used_index, handleAddress); else issueAddress(wallet, is_change, next_index, handleAddress); }); }); }
[ "function", "issueOrSelectNextAddress", "(", "wallet", ",", "is_change", ",", "handleAddress", ")", "{", "readNextAddressIndex", "(", "wallet", ",", "is_change", ",", "function", "(", "next_index", ")", "{", "if", "(", "next_index", "<", "MAX_BIP44_GAP", ")", "return", "issueAddress", "(", "wallet", ",", "is_change", ",", "next_index", ",", "handleAddress", ")", ";", "readLastUsedAddressIndex", "(", "wallet", ",", "is_change", ",", "function", "(", "last_used_index", ")", "{", "if", "(", "last_used_index", "===", "null", "||", "next_index", "-", "last_used_index", ">=", "MAX_BIP44_GAP", ")", "selectRandomAddress", "(", "wallet", ",", "is_change", ",", "last_used_index", ",", "handleAddress", ")", ";", "else", "issueAddress", "(", "wallet", ",", "is_change", ",", "next_index", ",", "handleAddress", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
selects one of recent addresses if the gap is too large, otherwise issues a new address
[ "selects", "one", "of", "recent", "addresses", "if", "the", "gap", "is", "too", "large", "otherwise", "issues", "a", "new", "address" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/wallet_defined_by_keys.js#L643-L654
15,295
byteball/ocore
wallet_defined_by_keys.js
readAddressInfo
function readAddressInfo(address, handleAddress){ db.query("SELECT address_index, is_change FROM my_addresses WHERE address=?", [address], function(rows){ if (rows.length === 0) return handleAddress("address "+address+" not found"); handleAddress(null, rows[0]); }); }
javascript
function readAddressInfo(address, handleAddress){ db.query("SELECT address_index, is_change FROM my_addresses WHERE address=?", [address], function(rows){ if (rows.length === 0) return handleAddress("address "+address+" not found"); handleAddress(null, rows[0]); }); }
[ "function", "readAddressInfo", "(", "address", ",", "handleAddress", ")", "{", "db", ".", "query", "(", "\"SELECT address_index, is_change FROM my_addresses WHERE address=?\"", ",", "[", "address", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "===", "0", ")", "return", "handleAddress", "(", "\"address \"", "+", "address", "+", "\" not found\"", ")", ";", "handleAddress", "(", "null", ",", "rows", "[", "0", "]", ")", ";", "}", ")", ";", "}" ]
unused so far
[ "unused", "so", "far" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/wallet_defined_by_keys.js#L788-L794
15,296
byteball/ocore
wallet_general.js
sendPrivatePayments
function sendPrivatePayments(device_address, arrChains, bForwarded, conn, onSaved){ var body = {chains: arrChains}; if (bForwarded) body.forwarded = true; device.sendMessageToDevice(device_address, "private_payments", body, { ifOk: function(){}, ifError: function(){}, onSaved: onSaved }, conn); }
javascript
function sendPrivatePayments(device_address, arrChains, bForwarded, conn, onSaved){ var body = {chains: arrChains}; if (bForwarded) body.forwarded = true; device.sendMessageToDevice(device_address, "private_payments", body, { ifOk: function(){}, ifError: function(){}, onSaved: onSaved }, conn); }
[ "function", "sendPrivatePayments", "(", "device_address", ",", "arrChains", ",", "bForwarded", ",", "conn", ",", "onSaved", ")", "{", "var", "body", "=", "{", "chains", ":", "arrChains", "}", ";", "if", "(", "bForwarded", ")", "body", ".", "forwarded", "=", "true", ";", "device", ".", "sendMessageToDevice", "(", "device_address", ",", "\"private_payments\"", ",", "body", ",", "{", "ifOk", ":", "function", "(", ")", "{", "}", ",", "ifError", ":", "function", "(", ")", "{", "}", ",", "onSaved", ":", "onSaved", "}", ",", "conn", ")", ";", "}" ]
unlike similar function in network, this function sends multiple chains in a single package
[ "unlike", "similar", "function", "in", "network", "this", "function", "sends", "multiple", "chains", "in", "a", "single", "package" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/wallet_general.js#L17-L26
15,297
byteball/ocore
light.js
fixIsSpentFlag
function fixIsSpentFlag(onDone){ db.query( "SELECT outputs.unit, outputs.message_index, outputs.output_index \n\ FROM outputs \n\ CROSS JOIN inputs ON outputs.unit=inputs.src_unit AND outputs.message_index=inputs.src_message_index AND outputs.output_index=inputs.src_output_index \n\ WHERE is_spent=0 AND type='transfer'", function(rows){ console.log(rows.length+" previous outputs appear to be spent"); if (rows.length === 0) return onDone(); var arrQueries = []; rows.forEach(function(row){ console.log('fixing is_spent for output', row); db.addQuery(arrQueries, "UPDATE outputs SET is_spent=1 WHERE unit=? AND message_index=? AND output_index=?", [row.unit, row.message_index, row.output_index]); }); async.series(arrQueries, onDone); } ); }
javascript
function fixIsSpentFlag(onDone){ db.query( "SELECT outputs.unit, outputs.message_index, outputs.output_index \n\ FROM outputs \n\ CROSS JOIN inputs ON outputs.unit=inputs.src_unit AND outputs.message_index=inputs.src_message_index AND outputs.output_index=inputs.src_output_index \n\ WHERE is_spent=0 AND type='transfer'", function(rows){ console.log(rows.length+" previous outputs appear to be spent"); if (rows.length === 0) return onDone(); var arrQueries = []; rows.forEach(function(row){ console.log('fixing is_spent for output', row); db.addQuery(arrQueries, "UPDATE outputs SET is_spent=1 WHERE unit=? AND message_index=? AND output_index=?", [row.unit, row.message_index, row.output_index]); }); async.series(arrQueries, onDone); } ); }
[ "function", "fixIsSpentFlag", "(", "onDone", ")", "{", "db", ".", "query", "(", "\"SELECT outputs.unit, outputs.message_index, outputs.output_index \\n\\\n\t\tFROM outputs \\n\\\n\t\tCROSS JOIN inputs ON outputs.unit=inputs.src_unit AND outputs.message_index=inputs.src_message_index AND outputs.output_index=inputs.src_output_index \\n\\\n\t\tWHERE is_spent=0 AND type='transfer'\"", ",", "function", "(", "rows", ")", "{", "console", ".", "log", "(", "rows", ".", "length", "+", "\" previous outputs appear to be spent\"", ")", ";", "if", "(", "rows", ".", "length", "===", "0", ")", "return", "onDone", "(", ")", ";", "var", "arrQueries", "=", "[", "]", ";", "rows", ".", "forEach", "(", "function", "(", "row", ")", "{", "console", ".", "log", "(", "'fixing is_spent for output'", ",", "row", ")", ";", "db", ".", "addQuery", "(", "arrQueries", ",", "\"UPDATE outputs SET is_spent=1 WHERE unit=? AND message_index=? AND output_index=?\"", ",", "[", "row", ".", "unit", ",", "row", ".", "message_index", ",", "row", ".", "output_index", "]", ")", ";", "}", ")", ";", "async", ".", "series", "(", "arrQueries", ",", "onDone", ")", ";", "}", ")", ";", "}" ]
fixes is_spent in case units were received out of order
[ "fixes", "is_spent", "in", "case", "units", "were", "received", "out", "of", "order" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/light.js#L273-L292
15,298
byteball/ocore
light.js
createLinkProof
function createLinkProof(later_unit, earlier_unit, arrChain, cb){ storage.readJoint(db, later_unit, { ifNotFound: function(){ cb("later unit not found"); }, ifFound: function(objLaterJoint){ var later_mci = objLaterJoint.unit.main_chain_index; arrChain.push(objLaterJoint); storage.readUnitProps(db, objLaterJoint.unit.last_ball_unit, function(objLaterLastBallUnitProps){ var later_lb_mci = objLaterLastBallUnitProps.main_chain_index; storage.readJoint(db, earlier_unit, { ifNotFound: function(){ cb("earlier unit not found"); }, ifFound: function(objEarlierJoint){ var earlier_mci = objEarlierJoint.unit.main_chain_index; var earlier_unit = objEarlierJoint.unit.unit; if (later_mci < earlier_mci && later_mci !== null && earlier_mci !== null) return cb("not included"); if (later_lb_mci >= earlier_mci && earlier_mci !== null){ // was spent when confirmed // includes the ball of earlier unit proofChain.buildProofChain(later_lb_mci + 1, earlier_mci, earlier_unit, arrChain, function(){ cb(); }); } else{ // the output was unconfirmed when spent graph.determineIfIncluded(db, earlier_unit, [later_unit], function(bIncluded){ if (!bIncluded) return cb("not included"); buildPath(objLaterJoint, objEarlierJoint, arrChain, function(){ cb(); }); }); } } }); }); } }); }
javascript
function createLinkProof(later_unit, earlier_unit, arrChain, cb){ storage.readJoint(db, later_unit, { ifNotFound: function(){ cb("later unit not found"); }, ifFound: function(objLaterJoint){ var later_mci = objLaterJoint.unit.main_chain_index; arrChain.push(objLaterJoint); storage.readUnitProps(db, objLaterJoint.unit.last_ball_unit, function(objLaterLastBallUnitProps){ var later_lb_mci = objLaterLastBallUnitProps.main_chain_index; storage.readJoint(db, earlier_unit, { ifNotFound: function(){ cb("earlier unit not found"); }, ifFound: function(objEarlierJoint){ var earlier_mci = objEarlierJoint.unit.main_chain_index; var earlier_unit = objEarlierJoint.unit.unit; if (later_mci < earlier_mci && later_mci !== null && earlier_mci !== null) return cb("not included"); if (later_lb_mci >= earlier_mci && earlier_mci !== null){ // was spent when confirmed // includes the ball of earlier unit proofChain.buildProofChain(later_lb_mci + 1, earlier_mci, earlier_unit, arrChain, function(){ cb(); }); } else{ // the output was unconfirmed when spent graph.determineIfIncluded(db, earlier_unit, [later_unit], function(bIncluded){ if (!bIncluded) return cb("not included"); buildPath(objLaterJoint, objEarlierJoint, arrChain, function(){ cb(); }); }); } } }); }); } }); }
[ "function", "createLinkProof", "(", "later_unit", ",", "earlier_unit", ",", "arrChain", ",", "cb", ")", "{", "storage", ".", "readJoint", "(", "db", ",", "later_unit", ",", "{", "ifNotFound", ":", "function", "(", ")", "{", "cb", "(", "\"later unit not found\"", ")", ";", "}", ",", "ifFound", ":", "function", "(", "objLaterJoint", ")", "{", "var", "later_mci", "=", "objLaterJoint", ".", "unit", ".", "main_chain_index", ";", "arrChain", ".", "push", "(", "objLaterJoint", ")", ";", "storage", ".", "readUnitProps", "(", "db", ",", "objLaterJoint", ".", "unit", ".", "last_ball_unit", ",", "function", "(", "objLaterLastBallUnitProps", ")", "{", "var", "later_lb_mci", "=", "objLaterLastBallUnitProps", ".", "main_chain_index", ";", "storage", ".", "readJoint", "(", "db", ",", "earlier_unit", ",", "{", "ifNotFound", ":", "function", "(", ")", "{", "cb", "(", "\"earlier unit not found\"", ")", ";", "}", ",", "ifFound", ":", "function", "(", "objEarlierJoint", ")", "{", "var", "earlier_mci", "=", "objEarlierJoint", ".", "unit", ".", "main_chain_index", ";", "var", "earlier_unit", "=", "objEarlierJoint", ".", "unit", ".", "unit", ";", "if", "(", "later_mci", "<", "earlier_mci", "&&", "later_mci", "!==", "null", "&&", "earlier_mci", "!==", "null", ")", "return", "cb", "(", "\"not included\"", ")", ";", "if", "(", "later_lb_mci", ">=", "earlier_mci", "&&", "earlier_mci", "!==", "null", ")", "{", "// was spent when confirmed", "// includes the ball of earlier unit", "proofChain", ".", "buildProofChain", "(", "later_lb_mci", "+", "1", ",", "earlier_mci", ",", "earlier_unit", ",", "arrChain", ",", "function", "(", ")", "{", "cb", "(", ")", ";", "}", ")", ";", "}", "else", "{", "// the output was unconfirmed when spent", "graph", ".", "determineIfIncluded", "(", "db", ",", "earlier_unit", ",", "[", "later_unit", "]", ",", "function", "(", "bIncluded", ")", "{", "if", "(", "!", "bIncluded", ")", "return", "cb", "(", "\"not included\"", ")", ";", "buildPath", "(", "objLaterJoint", ",", "objEarlierJoint", ",", "arrChain", ",", "function", "(", ")", "{", "cb", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", "}", "}", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
adds later unit earlier unit is not included in the chain
[ "adds", "later", "unit", "earlier", "unit", "is", "not", "included", "in", "the", "chain" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/light.js#L441-L480
15,299
byteball/ocore
desktop_app.js
getAppsDataDir
function getAppsDataDir(){ switch(process.platform){ case 'win32': return process.env.LOCALAPPDATA; case 'linux': return process.env.HOME + '/.config'; case 'darwin': return process.env.HOME + '/Library/Application Support'; default: throw Error("unknown platform "+process.platform); } }
javascript
function getAppsDataDir(){ switch(process.platform){ case 'win32': return process.env.LOCALAPPDATA; case 'linux': return process.env.HOME + '/.config'; case 'darwin': return process.env.HOME + '/Library/Application Support'; default: throw Error("unknown platform "+process.platform); } }
[ "function", "getAppsDataDir", "(", ")", "{", "switch", "(", "process", ".", "platform", ")", "{", "case", "'win32'", ":", "return", "process", ".", "env", ".", "LOCALAPPDATA", ";", "case", "'linux'", ":", "return", "process", ".", "env", ".", "HOME", "+", "'/.config'", ";", "case", "'darwin'", ":", "return", "process", ".", "env", ".", "HOME", "+", "'/Library/Application Support'", ";", "default", ":", "throw", "Error", "(", "\"unknown platform \"", "+", "process", ".", "platform", ")", ";", "}", "}" ]
make browserify skip it
[ "make", "browserify", "skip", "it" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/desktop_app.js#L6-L13