Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 | 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 12x 12x 6x 6x 6x 12x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 12x 12x 12x 12x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 24x 6x 6x | import bsv from 'bsv'; import Message from 'bsv/message'; import { MAX_INT, SIGNING_PATH_PREFIX, BAP_SERVER, BAP_BITCOM_ADDRESS, AIP_BITCOM_ADDRESS, } from './constants'; import { Utils } from './utils'; /** * BAP_ID class * * This class should be used in conjunction with the BAP class * * @type {BAP_ID} */ export const BAP_ID = class { #HDPrivateKey = null; #BAP_SERVER = BAP_SERVER; #BAP_TOKEN = ''; #rootPath; #previousPath; #currentPath; constructor(HDPrivateKey, identityAttributes = {}) { this.#HDPrivateKey = HDPrivateKey; this.name = 'ID 1'; this.description = ''; this.#rootPath = `${SIGNING_PATH_PREFIX}/0/0/0`; this.#previousPath = `${SIGNING_PATH_PREFIX}/0/0/0`; this.#currentPath = `${SIGNING_PATH_PREFIX}/0/0/1`; const rootChild = this.#HDPrivateKey.deriveChild(this.#rootPath); this.rootAddress = rootChild.privateKey.publicKey.toAddress().toString(); this.identityKey = this.deriveIdentityKey(this.rootAddress); // unlink the object identityAttributes = { ...identityAttributes }; this.identityAttributes = this.parseAttributes(identityAttributes); } set BAP_SERVER(bapServer) { this.#BAP_SERVER = bapServer; } get BAP_SERVER() { return this.#BAP_SERVER; } set BAP_TOKEN(token) { this.#BAP_TOKEN = token; } get BAP_TOKEN() { return this.#BAP_TOKEN; } deriveIdentityKey(address) { const rootAddressHash = bsv.crypto.Hash.sha256(Buffer.from(address)); return bsv.encoding.Base58(bsv.crypto.Hash.ripemd160(rootAddressHash)).toString(); } /** * Helper function to parse identity attributes * * @param identityAttributes * @returns {{}} */ parseAttributes(identityAttributes) { Iif (typeof identityAttributes === 'string') { return this.parseStringUrns(identityAttributes); } Object.keys(identityAttributes).forEach((key) => { if ( !identityAttributes[key].value || !identityAttributes[key].nonce ) { throw new Error('Invalid identity attribute'); } }); return identityAttributes || {}; } /** * Parse a text of urn string into identity attributes * * urn:bap:id:name:John Doe:e2c6fb4063cc04af58935737eaffc938011dff546d47b7fbb18ed346f8c4d4fa * urn:bap:id:birthday:1990-05-22:e61f23cbbb2284842d77965e2b0e32f0ca890b1894ca4ce652831347ee3596d9 * urn:bap:id:over18:1:480ca17ccaacd671b28dc811332525f2f2cd594d8e8e7825de515ce5d52d30e8 * * @param urnIdentityAttributes */ parseStringUrns(urnIdentityAttributes) { const identityAttributes = {}; urnIdentityAttributes.replace(/^\s+/g, '').replace(/\r/gm, '') .split('\n') .forEach((line) => { // remove any whitespace from the string (trim) line = line.replace(/^\s+/g, '').replace(/\s+$/g, ''); const urn = line.split(':'); if (urn[0] === 'urn' && urn[1] === 'bap' && urn[2] === 'id' && urn[3] && urn[4] && urn[5]) { identityAttributes[urn[3]] = { value: urn[4], nonce: urn[5], }; } }); return identityAttributes; } /** * Returns the identity key * * @returns {*|string} */ getIdentityKey() { return this.identityKey; } /** * Returns all the attributes in the identity * * @returns {*} */ getAttributes() { return this.identityAttributes; } /** * Get the value of the given attribute * * @param attributeName * @returns {{}|null} */ getAttribute(attributeName) { if (this.identityAttributes.hasOwnProperty(attributeName)) { return this.identityAttributes[attributeName]; } return null; } /** * Get all attribute urn's for this id * * @returns {string} */ getAttributeUrns() { let urns = ''; Object.keys(this.identityAttributes) .forEach((key) => { const urn = this.getAttributeUrn(key); if (urn) { urns += `${urn}\n`; } }); return urns; } /** * Create an return the attribute urn for the given attribute * * @param attributeName * @returns {string|null} */ getAttributeUrn(attributeName) { const attribute = this.identityAttributes[attributeName]; if (attribute) { return `urn:bap:id:${attributeName}:${attribute.value}:${attribute.nonce}`; } return null; } /** * Add an attribute to this identity * * @param attributeName * @param value * @param nonce */ addAttribute(attributeName, value, nonce = false) { if (!nonce) { nonce = Utils.getRandomString(); } this.identityAttributes[attributeName] = { value, nonce, }; } /** * This should be called with the last part of the signing path (/.../.../...) * This library assumes the first part is m/424150'/0'/0' as defined at the top of this file * * @param path The second path of the signing path in the format [0-9]{0,9}/[0-9]{0,9}/[0-9]{0,9} */ set rootPath(path) { Eif (path.split('/').length < 5) { path = `${SIGNING_PATH_PREFIX}${path}`; } Iif (!this.validatePath(path)) { throw new Error('invalid signing path given ' + path); } this.#rootPath = path; const derivedChild = this.#HDPrivateKey.deriveChild(path); this.rootAddress = derivedChild.publicKey.toAddress().toString(); // Identity keys should be derivatives of the root address - this allows checking // of the creation transaction this.identityKey = this.deriveIdentityKey(this.rootAddress); // we also set this previousPath / currentPath to the root as we seem to be (re)setting this ID this.#previousPath = path; this.#currentPath = path; } get rootPath() { return this.#rootPath; } /** * This should be called with the last part of the signing path (/.../.../...) * This library assumes the first part is m/424150'/0'/0' as defined at the top of this file * * @param path The second path of the signing path in the format [0-9]{0,9}/[0-9]{0,9}/[0-9]{0,9} */ set currentPath(path) { Eif (path.split('/').length < 5) { path = `${SIGNING_PATH_PREFIX}${path}`; } Iif (!this.validatePath(path)) { throw new Error('invalid signing path given'); } this.#previousPath = this.#currentPath; this.#currentPath = path; } get currentPath() { return this.#currentPath; } /** * Check whether the given path is a valid path for use with this class * The signing paths used here always have a length of 3 * * @param path The last part of the signing path (example "/0/0/1") * @returns {boolean} */ validatePath(path) { /* eslint-disable max-len */ Eif (path.match(/\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?\/[0-9]{1,10}'?/)) { const pathValues = path.split('/'); Eif (pathValues.length === 7 && Number(pathValues[1].replace('\'', '')) <= MAX_INT && Number(pathValues[2].replace('\'', '')) <= MAX_INT && Number(pathValues[3].replace('\'', '')) <= MAX_INT && Number(pathValues[4].replace('\'', '')) <= MAX_INT && Number(pathValues[5].replace('\'', '')) <= MAX_INT && Number(pathValues[6].replace('\'', '')) <= MAX_INT ) { return true; } } return false; } /** * Get the OP_RETURN for the initial ID transaction (signed with root address) * * @returns {[]} */ getInitialIdTransaction() { return this.getIdTransaction(this.#rootPath); } /** * Get the OP_RETURN for the initial ID transaction (signed with root address) * * @returns {[]} */ getIdTransaction(previousPath = false) { Iif (this.#currentPath === this.#rootPath) { throw new Error('Current path equals rootPath. ID was probably not initialized properly'); } const opReturn = [ Buffer.from(BAP_BITCOM_ADDRESS).toString('hex'), Buffer.from('ID').toString('hex'), Buffer.from(this.identityKey).toString('hex'), Buffer.from(this.getCurrentAddress()).toString('hex'), ]; previousPath = previousPath || this.#previousPath; return this.signOpReturnWithAIP(opReturn, previousPath); } /** * Get address for given path * * @param path * @returns {*} */ getAddress(path) { const derivedChild = this.#HDPrivateKey.deriveChild(path); return derivedChild.privateKey.publicKey.toAddress().toString(); } /** * Get current signing address * * @returns {*} */ getCurrentAddress() { return this.getAddress(this.#currentPath); } /** * Get an attestation string for the given urn for this identity * * @param urn * @returns {string} */ getAttestation(urn) { const urnHash = bsv.crypto.Hash.sha256(Buffer.from(urn)); return `bap:attest:${urnHash.toString('hex')}:${this.getIdentityKey()}`; } /** * Generate and return the attestation hash for the given attribute of this identity * * @param attribute Attribute name (name, email etc.) * @returns {string} */ getAttestationHash(attribute) { const urn = this.getAttributeUrn(attribute); if (!urn) return null; const attestation = this.getAttestation(urn); const attestationHash = bsv.crypto.Hash.sha256(Buffer.from(attestation)); return attestationHash.toString('hex'); } /** * Sign a message with the current signing address of this identity * * @param message * @param signingPath * @returns {{address, signature}} */ signMessage(message, signingPath = false) { Iif (!(message instanceof Buffer)) { message = Buffer.from(message); } signingPath = signingPath || this.#currentPath; const derivedChild = this.#HDPrivateKey.deriveChild(signingPath); const address = derivedChild.privateKey.publicKey.toAddress().toString(); const signature = Message(message).sign(derivedChild.privateKey); return { address, signature }; } /** * Sign an op_return hex array with AIP * @param opReturn * @param signingPath * @return {[]} */ signOpReturnWithAIP(opReturn, signingPath = false) { const aipMessageBuffer = this.getAIPMessageBuffer(opReturn); const { address, signature } = this.signMessage(aipMessageBuffer, signingPath); return opReturn.concat([ Buffer.from('|').toString('hex'), Buffer.from(AIP_BITCOM_ADDRESS).toString('hex'), Buffer.from('BITCOIN_ECDSA').toString('hex'), Buffer.from(address).toString('hex'), Buffer.from(signature, 'base64').toString('hex'), ]); } /** * Construct an AIP buffer from the op return data * @param opReturn * @returns {Buffer} */ getAIPMessageBuffer(opReturn) { const buffers = []; Eif (opReturn[0].replace('0x', '') !== '6a') { // include OP_RETURN in constructing the signature buffer buffers.push(Buffer.from('6a', 'hex')); } opReturn.forEach((op) => { buffers.push(Buffer.from(op.replace('0x', ''), 'hex')); }); // add a trailing "|" - this is the AIP way buffers.push(Buffer.from('|')); return Buffer.concat([...buffers]); } /** * Get all signing keys for this identity */ async getIdSigningKeys() { const signingKeys = await this.getApiData('/signing-keys', { idKey: this.identityKey, }); console.log('getIdSigningKeys', signingKeys); return signingKeys; } /** * Get all attestations for the given attribute * * @param attribute */ async getAttributeAttestations(attribute) { // This function needs to make a call to a BAP server to get all the attestations for this // identity for the given attribute const attestationHash = this.getAttestationHash(attribute); // get all BAP ATTEST records for the given attestationHash const attestations = await this.getApiData('/attestations', { hash: attestationHash, }); console.log('getAttestations', attribute, attestationHash, attestations); return attestations; } /** * Helper function to get attestation from a BAP API server * * @param apiUrl * @param apiData * @returns {Promise<any>} */ async getApiData(apiUrl, apiData) { const url = `${this.#BAP_SERVER}${apiUrl}`; const response = await fetch(url, { method: 'post', headers: { 'Content-type': 'application/json; charset=utf-8', token: this.#BAP_TOKEN, format: 'json', }, body: JSON.stringify(apiData), }); return response.json(); } /** * Import an identity from a JSON object * * @param identity{{}} */ import(identity) { this.name = identity.name; this.description = identity.description || ''; this.identityKey = identity.identityKey; this.#rootPath = identity.rootPath; this.rootAddress = identity.rootAddress; this.#previousPath = identity.previousPath; this.#currentPath = identity.currentPath; this.identityAttributes = this.parseAttributes(identity.identityAttributes); } /** * Export this identity to a JSON object * @returns {{}} */ export() { return { name: this.name, description: this.description, identityKey: this.identityKey, rootPath: this.#rootPath, rootAddress: this.rootAddress, previousPath: this.#previousPath, currentPath: this.#currentPath, identityAttributes: this.getAttributes(), }; } }; |