├── .gitignore ├── .npmignore ├── .travis.yml ├── LICENSE ├── README.md ├── index.js ├── lib ├── constants.js ├── debug.js ├── dir.js ├── errors.js ├── eventType.js ├── getViaCache.js ├── identityDB.js ├── miscDB.js ├── msgDB.js ├── optimizations.js ├── rebufEncoding.js ├── txDB.js ├── typeDB.js ├── unchainer.js └── utils.js ├── licenses.csv ├── licenses.json ├── package.json └── test ├── client.js ├── end-to-end.js ├── entries.js ├── fixtures ├── bill-priv.json ├── bill-pub.json ├── rufus-priv.json ├── rufus-pub.json ├── ted-priv.json └── ted-pub.json ├── genUsers.js ├── getViaCache.js ├── helpers └── utils.js ├── identityDB.js ├── index.js ├── live.js └── server.js /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | 5 | # Runtime data 6 | pids 7 | *.pid 8 | *.seed 9 | 10 | # Directory for instrumented libs generated by jscoverage/JSCover 11 | lib-cov 12 | 13 | # Coverage directory used by tools like istanbul 14 | coverage 15 | 16 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 17 | .grunt 18 | 19 | # node-waf configuration 20 | .lock-wscript 21 | 22 | # Compiled binary addons (http://nodejs.org/api/addons.html) 23 | build/Release 24 | 25 | # Dependency directory 26 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git 27 | node_modules 28 | 29 | *.js1 30 | *.sublime-* 31 | depromisify.js 32 | eventTypes.md 33 | eventTypes1.md 34 | example.js 35 | publishIdentity.js 36 | schema.md 37 | storage/ 38 | 39 | checkLicenses.js 40 | lib/promise-queue.js 41 | shim.js 42 | storage1/ 43 | test/dsaKeys.json 44 | test/helpers/testDriver.js 45 | test/makeBill.js 46 | test/queue.js 47 | 48 | coverage/ 49 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | 5 | # Runtime data 6 | pids 7 | *.pid 8 | *.seed 9 | 10 | # Directory for instrumented libs generated by jscoverage/JSCover 11 | lib-cov 12 | 13 | # Coverage directory used by tools like istanbul 14 | coverage 15 | 16 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 17 | .grunt 18 | 19 | # node-waf configuration 20 | .lock-wscript 21 | 22 | # Compiled binary addons (http://nodejs.org/api/addons.html) 23 | build/Release 24 | 25 | # Dependency directory 26 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git 27 | node_modules 28 | 29 | *.js1 30 | *.sublime-* 31 | eventTypes.md 32 | eventTypes1.md 33 | example.js 34 | publishIdentity.js 35 | schema.md 36 | *storage*/ 37 | 38 | checkLicenses.js 39 | lib/promise-queue.js 40 | shim.js 41 | coverage/ 42 | test/ 43 | *.txt 44 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "4" 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Trust in Motion (TiM) 2 | 3 | [![Build status](https://travis-ci.org/tradle/tim.svg)](https://travis-ci.org/tradle/tim) 4 | 5 | TiM is Tradle's SDK that provides real-time messaging with an option for messages to be sealed on the blockchain. Mesages can be plain or structured messages. TiM is designed to work on mobiles, desktops and servers. Having one code base is important to minimize security reviews. 6 | 7 | TiM is designed to work with intermittent connections, common on mobile devices. For that it keeps an internal log of all actions and events, and resumes operations as soon as network connection is restored. 8 | 9 | TiM's operations are covered by a patent. The tatent is filed only for defensive purposes, so you are welcome to use it in your open source projects. 10 | 11 | _this module is used by [Tradle](https://github.com/tradle/about/wiki)_ 12 | _this npm module's name was graciously donated by [Sean Robertson](https://www.npmjs.com/~spro)_ 13 | 14 | TiM provides a higher level API to a number of low level Tradle components. A UI is developed separately. Currently we focus on [React Native based UI](https://github.com/pgmemk/TiM) (on iOS, the Android version of TiM is in works), see the [preview video](https://www.youtube.com/watch?v=S66T0dPNn5I) and the [screenshots](https://docs.google.com/document/d/10eV6wgKr_vmfrXR4bDZ5XuylWJMNIJxziXM9T2CzCew). 15 | 16 | Prior to React Native, we developed the UI for Tim as a [Chrome App](https://github.com/tradle/chromeapp), see this [Identity verification video](https://www.youtube.com/watch?v=rrt8U4M-yMg) and a [work completion video](https://www.youtube.com/watch?v=mRnaw4pdifA). And prior to that we developed a very cool node-webkit-based [craigslist on-chain concept app](https://github.com/tradle/craigslist-on-chain) on TiM, but it is very much behind now. We plan work on desktop version of TiM soon, let us know if you are interested in these environments and we will prioritize this work for you. 17 | 18 | ## TiM uses the following Tradle components: 19 | 20 | ### [zlorp](https://github.com/tradle/zlorp) 21 | 22 | [Zlorp](https://github.com/tradle/zlorp) is just the core chat module. It uses OTR for secure sessions (later will add support for Axolotl, used in [TextSecure](https://github.com/WhisperSystems/TextSecure/) and [Pond](https://pond.imperialviolet.org/)). Peer discovery today is done via bittorrent-dht. But DHT's regular announce messages leak IP/Port, so we will see if we can use BEP 44 to encrypt them. Zlorp provides UDP NAT traversal (firewall hole-punching), and a direct connection via rUDP (later via uTP). We plan to further investigate anonymous packet delivery, possibly via I2P (TOR does not support UDP). 23 | 24 | ### [bitkeeper-js](https://github.com/tradle/bitkeeper-js) 25 | 26 | [Bitkeeper](https://github.com/tradle/bitkeeper-js) module uses [WebTorrent](https://github.com/feross/webtorrent) for storing and ensuring replication of arbitrary files. In Tradle, bitkeeper is used to store the original (encrypted) versions of on-chain objects (structured messages). 27 | 28 | ### [chained-obj](https://github.com/tradle/chained-obj) 29 | 30 | [Chained-obj](https://github.com/tradle/chained-obj) is object builder and parser. Currently uses multipart to store arbitrary JSON data + attachments. These objects are later encrypted and put on-chain. 31 | 32 | ### [bitjoe-js](https://github.com/tradle/bitjoe-js) (to be renamed to: chainwriter) 33 | 34 | A collection of requests that can be used to put an object "on chain": encrypt an object for its recipients, store/seed it from a bitkeeper node and put private links on blockchain. 35 | 36 | ### [tradle-constants](https://github.com/tradle/tradle-constants) 37 | 38 | Wait for it...a bunch of constants 39 | 40 | ### [tradle-utils](https://github.com/tradle/tradle-utils) 41 | 42 | A small set of crypto and torrent-related functions used by a number of Tradle components 43 | 44 | ### [Identity](https://github.com/tradle/identity) 45 | 46 | [Identity](https://github.com/tradle/identity) is wrapper around an OpenName-compatible Identity schema. Used for building/parsing/validating identity objects. 47 | 48 | ### [kiki](https://github.com/tradle/kiki) 49 | 50 | [kiki](https://github.com/tradle/kiki) Wrappers for DSA, EC, Bitcoin and other keys to provide a common API for signing/verifying/importing/exporting. 51 | 52 | ### [chainloader](https://github.com/tradle/chainloader) 53 | 54 | Parses bitcoin transactions, attempts to process embedded links, loads intermediate files and original files from a bitkeeper node, decrypts and returns files and metadata. Implements stream.Transform. 55 | 56 | ### [simple-wallet](https://github.com/tradle/simple-wallet) 57 | 58 | One-key [common blockchain](https://github.com/common-blockchain/common-blockchain) based wallet. 59 | 60 | ### [tradle-tx-data](https://github.com/tradle/tx-data) 61 | 62 | For building/parsing bitcoin-transaction-embedded data 63 | 64 | ### [tradle-verifier](https://github.com/tradle/tradle-verifier) 65 | 66 | Plugin-based verifier for on-chain objects. Implements several default plugins: 67 | Signature Check 68 | Identity verification 69 | Previous Version verification 70 | 71 | ## Exports 72 | 73 | ### Datalog 74 | 75 | This module uses a datalog, a log-based database of experienced activity that you can write to and use to bootstrap your own databases from. 76 | 77 | ### Messaging API 78 | 79 | Details to follow 80 | 81 | ## Usage 82 | 83 | ### Identity Identifiers 84 | 85 | When you want to communicate with someone else on the network, you need to identify them uniquely. You can identify them by a fingerprint of one of their public keys, a public key string, or by their identity's root hash: 86 | 87 | ```js 88 | // if this is the identity of your friend Bill: 89 | { 90 | "_t": "tradle.Identity", 91 | "pubkeys": [ 92 | { 93 | "fingerprint": "mvDNdZFbCCmnAPCBmLY91LnfKWoMH39Q2c", 94 | "networkName": "testnet", 95 | "purpose": "payment", 96 | "type": "bitcoin", 97 | "value": "03a45ede4be12a812e6e2ef1650ecbd8900152b1c6e3fe47f427ee5d9323759fe3" 98 | } 99 | ] 100 | } 101 | 102 | // the following are equivalent identifiers for Bill: 103 | { 104 | fingerprint: 'mvDNdZFbCCmnAPCBmLY91LnfKWoMH39Q2c' 105 | } 106 | 107 | { 108 | _r: 'whatever the infoHash of the above JSON object is' 109 | } 110 | ``` 111 | 112 | ### Initialization 113 | 114 | ```js 115 | var path = require('path') 116 | var levelup = require('levelup') 117 | var leveldown = require('leveldown') // or asyncstorage-down or whatever you're using 118 | var Blockchain = require('cb-blockr') // use tradle/cb-blockr fork 119 | var Identity = require('@tradle/identity').Identity 120 | var defaultKeySet = require('@tradle/identity').defaultKeySet 121 | var Keeper = require('@tradle/http-keeper') 122 | var Tim = require('tim') 123 | 124 | // Setup components: 125 | var networkName = 'testnet' 126 | var blockchain = new Blockchain(networkName) 127 | // Create an identity or load an existing one (see tradle/identity readme): 128 | var jack = new Identity() 129 | var jackPrivKeys = defaultKeySet({ networkName: networkName }) 130 | jackPrivKeys.forEach(jack.addKey, jack) 131 | // to export private keys: jackPrivKeys.forEach(k => k.exportPrivate()) 132 | // to export public identity: jack.toJSON() 133 | 134 | var myDir = path.join(process.env.HOME, 'myTradle') 135 | // content-address storage for your encrypted messages 136 | var keeper = new Keeper({ 137 | db: levelup(path.resolve(myDir, 'keeper'), { db: leveldown, valueEncoding: 'binary' }), 138 | fallbacks: ['http://tradle.io:25667'] 139 | }) 140 | 141 | // the API 142 | var tim = new Tim({ 143 | pathPrefix: path.join(myDir, 'tim'), // for playing nice with other levelup-based storage 144 | leveldown: leveldown, 145 | networkName: networkName, 146 | identity: jack, 147 | keys: jackPrivKeys, 148 | keeper: keeper, 149 | blockchain: blockchain, 150 | // optional 151 | syncInterval: 600000 // how often to bother cb-blockr 152 | }) 153 | 154 | // define a _send function that will determine the transport to use 155 | // to deliver a message to a particular recipient 156 | tim._send = function (recipientRootHash, msg, recipientInfo) { 157 | // return a Promise that resolves when the message is delivered 158 | // e.g. tim2.receiveMsg(msg, { _r: recipientRootHash }) 159 | // 160 | // tradle has several network-adapters for message delivery that you can use here. 161 | // They are all open source on Github: 162 | // tradle/zlorp - pure p2p messaging with OTR over UDP 163 | // tradle/http-client & tradle/http-server 164 | // tradle/ws-client & tradle/ws-relay - OTR over websockets 165 | // 166 | // latest, but unstable: 167 | // tradle/sendy, tradle/sendy-otr 168 | // reliable delivery over network of choice. 169 | // websockets implementation: tradle/sendy-ws, tradle/sendy-ws-relay 170 | } 171 | 172 | tim.send({ 173 | to: [{ fingerprint: 'one of their fingerprints' }], 174 | msg: { hey: 'ho' }, 175 | deliver: true, 176 | chain: false 177 | }) 178 | 179 | ``` 180 | 181 | ### Publishing your identity 182 | 183 | ```js 184 | tim.publishMyIdentity() 185 | ``` 186 | 187 | ### Sending messages 188 | 189 | ```js 190 | 191 | tim.send({ 192 | msg: Object|Buffer, 193 | // record message on chain 194 | chain: true, 195 | // send message p2p 196 | deliver: true, 197 | to: [ 198 | identityIdentitifier // see Identity Identifiers 199 | ] 200 | }) 201 | 202 | ``` 203 | 204 | ### Sharing existing messages (via the blockchain) 205 | 206 | ```js 207 | 208 | var constants = require('@tradle/constants') 209 | var curHash = '...' // the infoHash of the existing message, see tradle/utils `getStorageKeyFor` 210 | var shareOpts = { 211 | // record message on chain 212 | chain: true, 213 | // send message p2p 214 | deliver: true, 215 | to: [ 216 | identityIdentitifier // see Identity Identifiers 217 | ] 218 | } 219 | 220 | shareOpts[constants.CUR_HASH] = curHash 221 | tim.share(shareOpts) 222 | 223 | ``` 224 | 225 | ### Publishing on chain 226 | 227 | Same as sending a message, but use tim.publish instead of tim.send 228 | 229 | ```js 230 | 231 | tim.publish({ 232 | msg: Object|Buffer, 233 | to: [ 234 | identityIdentitifier // see Identity Identifiers 235 | ] 236 | }) 237 | 238 | ``` 239 | 240 | ## Messages 241 | 242 | ```js 243 | var db = tim.messages() // read-only levelup instance 244 | 245 | // e.g. 246 | db.createValueStream() 247 | .on('data', function (err, msg) { 248 | // issue tim.lookupObject(msg) to get decrypted metadata and contents 249 | }) 250 | ``` 251 | 252 | ## Identities (loaded from chain) 253 | 254 | ```js 255 | var db = tim.identities() // read-only levelup instance 256 | 257 | // e.g. 258 | db.createValueStream() 259 | .on('data', function (err, identityJSON) { 260 | // do something with "identity" 261 | // console.log('yo', identityJSON.name.firstName) 262 | }) 263 | 264 | // additional convenience methods 265 | db.byRootHash(identityRootHash, callback) 266 | db.byFingerprint(fingerprint, callback) 267 | ``` 268 | 269 | ## Events 270 | 271 | ### tim.on('ready', function () {...}) 272 | 273 | Tim's ready to do stuff 274 | 275 | ### tim.on('chained', function (info) {...} 276 | 277 | An object was successfully put on chain1 278 | 279 | ### tim.on('unchained', function (info) {...} 280 | 281 | An object was read off chain1 282 | 283 | ### tim.on('message', function (info) {...} 284 | 285 | A message was received peer-to-peer1 286 | 287 | ### tim.on('sent', function (info) {...} 288 | 289 | A message was delivered1 290 | 291 | ### tim.on('resolved', function (info) {...} 292 | 293 | An object was both received peer-to-peer and read from the chain1 294 | 295 | 1 Note: does NOT contain chained-object contents. Use tim.lookupObject(info) to obtain those. 296 | -------------------------------------------------------------------------------- /lib/constants.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | IDENTITY_PUBLISH_ADDRESS: 'mhKnKtPFCbYpC61buDMgSBB57mqiWvXCUo', 3 | prevHash: '_p', 4 | rootHash: '_r', 5 | currentHash: '_c', 6 | owner: '_o', 7 | nextOwner: '_n' 8 | } 9 | -------------------------------------------------------------------------------- /lib/debug.js: -------------------------------------------------------------------------------- 1 | module.exports = process.env.NODE_ENV === 'development' 2 | -------------------------------------------------------------------------------- /lib/dir.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | outbound: 0, 3 | inbound: 1 4 | } 5 | -------------------------------------------------------------------------------- /lib/errors.js: -------------------------------------------------------------------------------- 1 | 2 | var TypedError = require('error/typed') 3 | var WrappedError = require('error/wrapped') 4 | module.exports = { 5 | NotEnoughFunds: WrappedError({ 6 | type: 'notEnoughFunds', 7 | message: 'current balance: {balance}', 8 | balance: '[unspecified]', 9 | timestamp: null 10 | }), 11 | ChainWrite: TypedError({ 12 | type: 'chainWrite', 13 | message: 'tx failed: {origMessage}', 14 | timestamp: null 15 | }), 16 | ChainRead: WrappedError({ 17 | type: 'chainRead', 18 | message: 'read failed: {origMessage}', 19 | timestamp: null 20 | }), 21 | Parse: WrappedError({ 22 | type: 'parse', 23 | message: 'obj parse failed: {origMessage}', 24 | timestamp: null 25 | }), 26 | Verification: TypedError({ 27 | type: 'verifier', 28 | message: 'obj verify failed: {origMessage}', 29 | timestamp: null 30 | }), 31 | 32 | getMessage: function (err) { 33 | return err.message || err.type || err.name 34 | }, 35 | 36 | group: { 37 | send: 'send', 38 | receive: 'receive', 39 | chain: 'chain', 40 | unchain: 'unchain' 41 | }, 42 | 43 | MAX_CHAIN: Infinity, 44 | MAX_UNCHAIN: 10, 45 | MAX_RESEND: Infinity 46 | } 47 | -------------------------------------------------------------------------------- /lib/eventType.js: -------------------------------------------------------------------------------- 1 | // var groupOffset = 0 2 | var types = module.exports = {} 3 | var reverse = exports.reverse = {} 4 | 5 | ;[ 6 | { 7 | group: 'tx', 8 | events: { 9 | new: 0, 10 | confirmation: 1, 11 | ignore: 2, 12 | watch: 3 13 | } 14 | }, 15 | { 16 | group: 'msg', 17 | events: { 18 | new: 0, 19 | // stored: 1, 20 | sendSuccess: 2, 21 | sendError: 3, 22 | delivered: 4, 23 | receivedValid: 5, 24 | receivedInvalid: 6, 25 | edit: 7 26 | } 27 | }, 28 | { 29 | group: 'chain', 30 | events: { 31 | readSuccess: 0, 32 | readError: 1, 33 | writeSuccess: 2, 34 | writeError: 3 35 | } 36 | }, 37 | { 38 | group: 'misc', 39 | events: { 40 | forget: 0, 41 | addIdentity: 1, 42 | watchAddresses: 2, 43 | unwatchAddresses: 3 44 | } 45 | } 46 | ].forEach(function (group, i) { 47 | var offset = 1000 * (i + 1) 48 | var g = types[group.group] = {} 49 | for (var event in group.events) { 50 | var code = offset + group.events[event] 51 | g[event] = code 52 | reverse[code] = group.group + '.' + event 53 | } 54 | }) 55 | 56 | // addGroup({ 57 | // tx: { 58 | // new: 0, 59 | // confirmation: 1 60 | // } 61 | // }) 62 | 63 | // addGroup({ 64 | // msg: { 65 | // new: 0, 66 | // // stored: 1, 67 | // sendSuccess: 2, 68 | // sendError: 3, 69 | // delivered: 4, 70 | // receivedValid: 5, 71 | // receivedInvalid: 6 72 | // } 73 | // }) 74 | 75 | // addGroup({ 76 | // chain: { 77 | // readSuccess: 0, 78 | // readError: 1, 79 | // writeSuccess: 2, 80 | // writeError: 3 81 | // } 82 | // }) 83 | 84 | // function addGroup (group) { 85 | // groupOffset += 1000 86 | // enumerate(group, 0) 87 | // for (var p in group) { 88 | // types[p] = group[p] 89 | // } 90 | // } 91 | 92 | // function enumerate (group, offset) { 93 | // for (var p in group) { 94 | // var sub = group[p] 95 | // if (typeof sub === 'number') { 96 | // group[p] += groupOffset 97 | // } else { 98 | // enumerate(sub, offset) 99 | // } 100 | // } 101 | // } 102 | -------------------------------------------------------------------------------- /lib/getViaCache.js: -------------------------------------------------------------------------------- 1 | 2 | module.exports = function getViaCache (get, getFromCache) { 3 | return function (ids, cb) { 4 | getFromCache(ids, function (err, fromCache) { 5 | if (err) { 6 | return fetchAndMerge(ids.map(function () { 7 | return null 8 | }), ids, cb) 9 | } 10 | 11 | // if (fromCache.length !== ids.length) { 12 | // throw new Error('getFromCache should return an array the same length as the input') 13 | // } 14 | 15 | return fetchAndMerge(fromCache, ids.filter(function (id, idx) { 16 | return !fromCache[idx] 17 | }), cb) 18 | }) 19 | 20 | function fetchAndMerge (results, missing) { 21 | if (missing.length) get(missing, onFetched) 22 | else onFetched(null, []) 23 | 24 | function onFetched (err, fetched) { 25 | if (err) return cb(err) 26 | 27 | var offset = 0 28 | results = results.map(function (r) { 29 | return r == null ? fetched[offset++] : r 30 | }) 31 | .filter(function (r) { 32 | return !r.ignore 33 | }) 34 | 35 | cb(null, results) 36 | } 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /lib/identityDB.js: -------------------------------------------------------------------------------- 1 | 2 | var debug = require('debug')('identityDB') 3 | var typeforce = require('typeforce') 4 | var extend = require('xtend') 5 | var map = require('map-stream') 6 | var levelup = require('levelup') 7 | var Q = require('q') 8 | var constants = require('@tradle/constants') 9 | var TYPE = constants.TYPE 10 | var IDENTITY_TYPE = constants.TYPES.IDENTITY 11 | var ROOT_HASH = constants.ROOT_HASH 12 | var CUR_HASH = constants.CUR_HASH 13 | var Simple = require('logbase').Simple 14 | var rebuf = require('./rebufEncoding') 15 | var EventType = require('./eventType') 16 | var DEBUG = require('./debug') 17 | var ENTRY_TIMEOUT = DEBUG ? false : 5000 18 | var prefixes = { 19 | fingerprint: 'f' 20 | } 21 | 22 | prefixes[CUR_HASH] = CUR_HASH 23 | prefixes[ROOT_HASH] = ROOT_HASH 24 | 25 | module.exports = function mkIdentityDB (path, options) { 26 | typeforce('String', path) 27 | typeforce({ 28 | leveldown: 'Function', 29 | log: 'Log', 30 | keeper: 'Object' 31 | }, options) 32 | 33 | var log = options.log 34 | var db = levelup(path, { 35 | db: options.leveldown, 36 | valueEncoding: rebuf 37 | }) 38 | 39 | db = Simple({ 40 | db: db, 41 | log: log, 42 | process: processEntry, 43 | timeout: typeof options.timeout === 'undefined' ? ENTRY_TIMEOUT : options.timeout, 44 | autostart: options.autostart, 45 | }) 46 | 47 | var topics = [ 48 | EventType.chain.readSuccess, 49 | EventType.misc.addIdentity 50 | ] 51 | 52 | var keeper = options.keeper 53 | 54 | var createReadStream = db.createReadStream 55 | db.createReadStream = function (options) { 56 | options = options || {} 57 | return createReadStream.call(db, extend(options, { 58 | start: prefixes[ROOT_HASH], 59 | end: prefixes[ROOT_HASH] + '\xff' 60 | })) 61 | .pipe(map(function (data, cb) { 62 | if (options.keys !== false) { 63 | var key = options.values === false ? data : data.key 64 | key = unprefixKey(ROOT_HASH, key) 65 | if (options.values === false) data = key 66 | else data.key = key 67 | } 68 | 69 | if (options.values === false) return cb(null, data) 70 | var id = options.keys === false ? data : data.value 71 | 72 | getContents(id, function (err, contents) { 73 | if (err) return cb(err) 74 | 75 | var ret = options.keys === false ? 76 | contents : 77 | { 78 | key: data.key, 79 | value: contents 80 | } 81 | 82 | cb(null, ret) 83 | }) 84 | })) 85 | } 86 | 87 | // db.createKeyStream = function (options) { 88 | // return db.createReadStream(extend({ values: false }, options)) 89 | // } 90 | 91 | // db.createValueStream = function (options) { 92 | // return db.createReadStream(extend({ keys: false }, options)) 93 | // } 94 | 95 | db.query = function (query, cb) { 96 | // by one and only one prop 97 | if (Object.keys(query).length !== 1 || 98 | !(query.fingerprint || query[ROOT_HASH] || query[CUR_HASH])) { 99 | return process.nextTick(function () { 100 | cb(new Error('specify "fingerprint", ' + ROOT_HASH + ' OR ' + CUR_HASH)) 101 | }) 102 | } 103 | 104 | if (query.fingerprint) { 105 | db.byFingerprint(query.fingerprint, cb) 106 | } else if (query[ROOT_HASH]) { 107 | db.byRootHash(query[ROOT_HASH], cb) 108 | } else if (query[CUR_HASH]) { 109 | db.byCurHash(query[CUR_HASH], cb) 110 | } 111 | } 112 | 113 | db.byFingerprint = function (fingerprint, cb) { 114 | db.rootHashByFingerprint(fingerprint, function (err, rootHash) { 115 | if (err) return cb(err) 116 | 117 | return db.byRootHash(rootHash, cb) 118 | }) 119 | } 120 | 121 | db.rootHashByFingerprint = db.liveOnly(function (fingerprint, cb) { 122 | db.get(prefixKey('fingerprint', fingerprint), cb) 123 | }) 124 | 125 | db.byRootHash = db.liveOnly(function (rootHash, cb) { 126 | db.get(prefixKey(ROOT_HASH, rootHash), function (err, id) { 127 | if (err) return cb(err) 128 | 129 | getContents(id, cb) 130 | }) 131 | }) 132 | 133 | db.byCurHash = db.liveOnly(function (curHash, cb) { 134 | db.get(prefixKey(CUR_HASH, curHash), function (err, id) { 135 | if (err) return cb(err) 136 | 137 | getContents(id, cb) 138 | }) 139 | }) 140 | 141 | return db 142 | 143 | function getContents (id, cb) { 144 | log.get(id, function (err, entry) { 145 | if (err) return cb(err) 146 | 147 | var curHash = entry.get(CUR_HASH) 148 | keeper.getOne(curHash) 149 | .then(function (buf) { 150 | var ret = { 151 | identity: toJSON(buf) 152 | } 153 | 154 | ret[ROOT_HASH] = entry.get(ROOT_HASH) 155 | ret[CUR_HASH] = curHash 156 | cb(null, ret) 157 | }) 158 | .catch(cb) 159 | .done() 160 | }) 161 | } 162 | 163 | function processEntry (entry, cb) { 164 | if (topics.indexOf(entry.get('type')) === -1) return cb() 165 | 166 | if (entry.get(TYPE) !== IDENTITY_TYPE) { 167 | return cb() 168 | } 169 | 170 | var rootHash = entry.get(ROOT_HASH) 171 | if (!rootHash) throw new Error('missing root hash ("' + ROOT_HASH + '")') 172 | 173 | var curHash = entry.get(CUR_HASH) 174 | if (!curHash) throw new Error('missing current hash ("' + CUR_HASH + '")') 175 | 176 | db.get(prefixKey(CUR_HASH, curHash), function (err, val) { 177 | if (err){ 178 | // TODO: handle this better 179 | if (!err.notFound) { 180 | debug('database choked on get: ' + JSON.stringify(err)) 181 | } 182 | 183 | save() 184 | } else { 185 | cb() 186 | } 187 | }) 188 | 189 | function save () { 190 | return keeper.getOne(curHash) 191 | .then(doSave, function (err) { 192 | if (err instanceof TypeError || 193 | err instanceof ReferenceError) { 194 | throw err 195 | } 196 | 197 | debug('unable to get identity from keeper', curHash, err) 198 | cb() 199 | }) 200 | } 201 | 202 | function doSave (buf) { 203 | var identityJSON = toJSON(buf) 204 | var batch = identityJSON.pubkeys.map(function (k) { 205 | return { 206 | type: 'put', 207 | key: prefixKey('fingerprint', k.fingerprint), 208 | value: rootHash 209 | } 210 | }) 211 | 212 | var results = batch.map(function (item) { 213 | return null 214 | }) 215 | 216 | batch.forEach(function (item, i) { 217 | db.get(item.key, function (err, result) { 218 | if (result) results[i] = result 219 | 220 | next() 221 | }) 222 | }) 223 | 224 | var togo = batch.length 225 | 226 | function next () { 227 | if (--togo) return 228 | 229 | var conflict = results.some(function (r) { 230 | // only allow iterations of identity 231 | // by original identity publisher 232 | return r && r !== rootHash 233 | }) 234 | 235 | if (conflict) { 236 | debug('ignoring identity that presents keys already presented by another identity') 237 | return cb() 238 | } 239 | 240 | batch.push({ 241 | type: 'put', 242 | key: prefixKey(ROOT_HASH, rootHash), 243 | value: entry.id() 244 | }, { 245 | type: 'put', 246 | key: prefixKey(CUR_HASH, curHash), 247 | value: entry.id() 248 | }) 249 | 250 | debug(db.name, 'stored identity', curHash) 251 | cb(batch) 252 | } 253 | } 254 | } 255 | } 256 | 257 | function toJSON (buf) { 258 | if (Buffer.isBuffer(buf)) buf = buf.toString() 259 | if (typeof buf === 'string') buf = JSON.parse(buf) 260 | 261 | return buf 262 | } 263 | 264 | function prefixKey (type, key) { 265 | if (!(type in prefixes)) throw new Error('no such type: ' + type) 266 | 267 | return prefixes[type] + '!' + key 268 | } 269 | 270 | function unprefixKey (type, key) { 271 | if (!(type in prefixes)) throw new Error('no such type: ' + type) 272 | if (key.indexOf(type) !== 0) throw new Error('key has wrong prefix') 273 | 274 | return key.slice(type.length + 1) 275 | } 276 | 277 | // function logify (cb, errsOnly) { 278 | // return function (err) { 279 | // if (errsOnly) { 280 | // if (err) debug(err) 281 | // } else { 282 | // debug(arguments) 283 | // } 284 | 285 | // cb(arguments[0], arguments[1], arguments[2], arguments[3]) 286 | // } 287 | // } 288 | 289 | // function liveOnly (db, fn, ctx) { 290 | // return function () { 291 | // var args = arguments 292 | // db.onLive(function () { 293 | // return fn.apply(ctx, args) 294 | // }) 295 | // } 296 | // } 297 | -------------------------------------------------------------------------------- /lib/miscDB.js: -------------------------------------------------------------------------------- 1 | 2 | var debug = require('debug')('txDB') 3 | var typeforce = require('typeforce') 4 | var levelup = require('levelup') 5 | var LiveStream = require('level-live-stream') 6 | // var CUR_HASH = constants.CUR_HASH 7 | var lb = require('logbase') 8 | var LogBase = lb.Simple 9 | var EventType = require('./eventType') 10 | var rebuf = require('./rebufEncoding') 11 | var DEBUG = require('./debug') 12 | var utils = require('./utils') 13 | var ENTRY_TIMEOUT = DEBUG ? false : 5000 14 | var WATCH_ADDRS_KEY = 'watched-addrs' 15 | var WATCH_TXS_KEY = 'watched-txs' 16 | 17 | module.exports = function createTxDB (path, options) { 18 | typeforce('String', path) 19 | typeforce({ 20 | leveldown: 'Function', 21 | log: 'Log' 22 | }, options) 23 | 24 | var db = levelup(path, { 25 | db: options.leveldown, 26 | valueEncoding: rebuf 27 | }) 28 | 29 | db = LogBase({ 30 | db: db, 31 | log: options.log, 32 | process: processEntry, 33 | timeout: typeof options.timeout === 'undefined' ? ENTRY_TIMEOUT : options.timeout, 34 | autostart: options.autostart, 35 | }) 36 | 37 | db.getWatchedAddresses = function (cb) { 38 | db.get(WATCH_ADDRS_KEY, getWatchCallback(cb)) 39 | } 40 | 41 | db.getWatchedTxs = function (cb) { 42 | db.get(WATCH_TXS_KEY, getWatchCallback(cb)) 43 | } 44 | 45 | return db 46 | 47 | function getWatchCallback (cb) { 48 | return function (err, results) { 49 | if (err && !err.notFound) return cb(err) 50 | 51 | return cb(null, results || []) 52 | } 53 | } 54 | 55 | function myDebug () { 56 | var args = [].slice.call(arguments) 57 | args.unshift(db.name) 58 | return debug.apply(null, args) 59 | } 60 | 61 | function processEntry (entry, cb) { 62 | var eType = entry.get('type') 63 | // entry = entry.clone() 64 | 65 | var now = Date.now() 66 | 67 | switch (eType) { 68 | case EventType.tx.watch: 69 | return editWatch({ 70 | watch: [entry.get('txId')], 71 | key: WATCH_TXS_KEY, 72 | event: 'watchedTxs' 73 | }, cb) 74 | case EventType.tx.ignore: 75 | return editWatch({ 76 | unwatch: [entry.get('txId')], 77 | key: WATCH_TXS_KEY, 78 | event: 'watchedTxs' 79 | }, cb) 80 | case EventType.misc.watchAddresses: 81 | return editWatch({ 82 | watch: entry.get('addresses'), 83 | key: WATCH_ADDRS_KEY, 84 | event: 'watchedAddresses' 85 | }, cb) 86 | case EventType.misc.unwatchAddresses: 87 | return editWatch({ 88 | unwatch: entry.get('addresses'), 89 | key: WATCH_ADDRS_KEY, 90 | event: 'watchedAddresses' 91 | }, cb) 92 | default: 93 | myDebug('ignoring entry of type', eType) 94 | return cb() 95 | } 96 | } 97 | 98 | function editWatch (opts, cb) { 99 | var watch = opts.watch 100 | var unwatch = opts.unwatch 101 | var key = opts.key 102 | 103 | db.get(opts.key, function (err, items) { 104 | if (err && !err.notFound) { 105 | if (DEBUG) throw err 106 | else return cb() 107 | } 108 | 109 | items = items || [] 110 | if (unwatch) { 111 | items = items.filter(function (item) { 112 | return unwatch.indexOf(item) !== -1 113 | }) 114 | } 115 | 116 | if (watch) { 117 | items = watch 118 | .filter(function (item) { 119 | return items.indexOf(item) === -1 120 | }) 121 | .concat(items) 122 | } 123 | 124 | if (opts.event) { 125 | process.nextTick(function () { 126 | db.emit(opts.event, items) 127 | }) 128 | } 129 | 130 | cb([{ 131 | type: 'put', 132 | key: opts.key, 133 | value: items 134 | }]) 135 | }) 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /lib/msgDB.js: -------------------------------------------------------------------------------- 1 | var debug = require('debug')('msgDB') 2 | var typeforce = require('typeforce') 3 | // var lexint = require('lexicographic-integer') 4 | var collect = require('stream-collector') 5 | var levelup = require('levelup') 6 | var Q = require('q') 7 | var pump = require('pump') 8 | // var levelQuery = require('level-queryengine') 9 | // var jsonQueryEngine = require('jsonquery-engine') 10 | var safe = require('safecb') 11 | var constants = require('@tradle/constants') 12 | // var TxData = require('tradle-tx-data').TxData 13 | var levelErrs = require('level-errors') 14 | var LiveStream = require('level-live-stream') 15 | var CUR_HASH = constants.CUR_HASH 16 | var ROOT_HASH = constants.ROOT_HASH 17 | var TYPE = constants.TYPE 18 | var TYPES = constants.TYPES 19 | var lb = require('logbase') 20 | var Entry = lb.Entry 21 | var LogBase = lb.Simple 22 | var EventType = require('./eventType') 23 | var rebuf = require('./rebufEncoding') 24 | var DEBUG = require('./debug') 25 | var utils = require('./utils') 26 | var Errors = require('./errors') 27 | var now = utils.now 28 | var ENTRY_TIMEOUT = DEBUG ? false : 5000 29 | var MAIN_PREFIX = 'm!' 30 | var TIMESTAMP_PREFIX = 't' 31 | var CHAIN_TIMESTAMP_PREFIX = TIMESTAMP_PREFIX + 'c!' 32 | var SEND_TIMESTAMP_PREFIX = TIMESTAMP_PREFIX + 's!' 33 | 34 | module.exports = function createMsgDB (path, options) { 35 | typeforce('String', path) 36 | typeforce({ 37 | leveldown: 'Function', 38 | log: 'Log' 39 | }, options) 40 | 41 | var db = levelup(path, { 42 | db: options.leveldown, 43 | valueEncoding: rebuf 44 | }) 45 | 46 | db = LogBase({ 47 | db: db, 48 | log: options.log, 49 | process: processEntry, 50 | timeout: typeof options.timeout === 'undefined' ? ENTRY_TIMEOUT : options.timeout, 51 | autostart: options.autostart 52 | }) 53 | 54 | var topics = [ 55 | EventType.misc.forget, 56 | EventType.msg.new, 57 | EventType.msg.edit, 58 | EventType.misc.addIdentity, 59 | EventType.msg.receivedValid, 60 | EventType.msg.receivedInvalid, 61 | EventType.msg.sendSuccess, 62 | EventType.msg.sendError, 63 | EventType.chain.writeSuccess, 64 | EventType.chain.writeError, 65 | EventType.chain.readSuccess, 66 | EventType.chain.readError 67 | ] 68 | 69 | // db = levelQuery(db) 70 | // db.query.use(jsonQueryEngine()) 71 | // db.ensureIndex(CUR_HASH) 72 | // db.ensureIndex(ROOT_HASH) 73 | LiveStream.install(db) 74 | 75 | // db.byCurHash = function (curHash, cb) { 76 | // collect(db.createReadStream({ 77 | // start: curHash, 78 | // end: curHash + '\xff' 79 | // }), cb) 80 | // } 81 | 82 | db.byRootHash = db.liveOnly(function (rootHash, cb) { 83 | collect(db.rawReadStream({ 84 | keys: false, 85 | start: MAIN_PREFIX + rootHash, 86 | end: MAIN_PREFIX + rootHash + '\xff' 87 | }), function (err, entries) { 88 | if (err) return cb(err) 89 | if (!entries || !entries.length) { 90 | return cb(new levelErrs.NotFoundError()) 91 | } 92 | 93 | return cb(null, entries) 94 | }) 95 | }) 96 | 97 | db.byCurHash = db.liveOnly(function (curHash, all, cb) { 98 | // TODO: add indices for searchable properties 99 | // to make this more efficient 100 | if (typeof all === 'function') { 101 | cb = all 102 | all = false 103 | } 104 | 105 | cb = safe(cb) 106 | var keys = db.createKeyStream() 107 | var found 108 | keys.on('data', function (key) { 109 | var parsed = utils.parseUID(key) 110 | if (parsed[CUR_HASH] !== curHash) return 111 | 112 | found = true 113 | keys.destroy() 114 | if (parsed.public || !all) { 115 | return db.get(key, cb) 116 | } 117 | 118 | // get all entries for this curHash 119 | // for all from/to 120 | // TODO: remove assumption on key formation 121 | start = parsed[ROOT_HASH] + '-' + parsed[CUR_HASH] 122 | collect(db.createReadStream({ 123 | keys: false, 124 | start: start, 125 | end: start + '\xff' 126 | }), function (err, list) { 127 | if (err) { 128 | cb(err) 129 | } else if (!list || !list.length) { 130 | errWithNotFound(cb) 131 | } else { 132 | cb(null, list) 133 | } 134 | }) 135 | }) 136 | 137 | keys.on('end', function () { 138 | if (!found) errWithNotFound(cb) 139 | }) 140 | }) 141 | 142 | db.byRootHashAndCurHash = db.liveOnly(function (rootHash, curHash, cb) { 143 | return db.byRootHash(rootHash, function (err, entries) { 144 | if (err) return cb(err) 145 | 146 | var found = entries.some(function (e) { 147 | if (e[CUR_HASH] === curHash) { 148 | cb(null, e) 149 | } 150 | }) 151 | 152 | if (!found) { 153 | cb(null, new levelErrs.NotFoundError()) 154 | } 155 | }) 156 | }) 157 | 158 | var createReadStream = db.createReadStream 159 | db.createReadStream = function (opts) { 160 | opts = opts || {} 161 | if (!(opts.gt || opts.lt || opts.gte || opts.lte || opts.start || opts.end)) { 162 | opts.gt = MAIN_PREFIX 163 | opts.lt = MAIN_PREFIX + '\xff' 164 | } 165 | 166 | return createReadStream.call(db, opts) 167 | } 168 | 169 | db.byUID = function (key, cb) { 170 | return db.get(MAIN_PREFIX + key, cb) 171 | } 172 | 173 | db.getToChainStream = function (opts) { 174 | return db.liveStream(getToChainStreamOpts(opts)) 175 | } 176 | 177 | db.getToSendStream = function (opts) { 178 | return db.liveStream(getToSendStreamOpts(opts)) 179 | } 180 | 181 | db.getConversation = function (otherGuyRootHash, raw, cb) { 182 | if (typeof raw === 'function') { 183 | cb = raw 184 | raw = false 185 | } 186 | 187 | collect(pump( 188 | raw ? db.rawReadStream({ keys: false }) : db.createValueStream(), 189 | utils.filterStream(function (val) { 190 | var from = val.from && val.from[ROOT_HASH] 191 | var to = val.to && val.to[ROOT_HASH] 192 | return val[TYPE] !== TYPES.IDENTITY && 193 | (from === otherGuyRootHash || to === otherGuyRootHash) 194 | }) 195 | ), cb) 196 | } 197 | 198 | db.setMaxListeners(0) 199 | return db 200 | 201 | function getToSendStreamOpts (opts) { 202 | opts = opts || {} 203 | opts.gt = SEND_TIMESTAMP_PREFIX 204 | opts.lt = SEND_TIMESTAMP_PREFIX + '\xff' 205 | return opts 206 | } 207 | 208 | function getToChainStreamOpts (opts) { 209 | opts = opts || {} 210 | opts.gt = CHAIN_TIMESTAMP_PREFIX 211 | opts.lt = CHAIN_TIMESTAMP_PREFIX + '\xff' 212 | return opts 213 | } 214 | 215 | function myDebug () { 216 | var args = [].slice.call(arguments) 217 | args.unshift(db.name) 218 | return debug.apply(null, args) 219 | } 220 | 221 | function processEntry (entry, cb) { 222 | var eType = entry.get('type') 223 | if (topics.indexOf(eType) === -1) return cb() 224 | 225 | entry = entry.clone() 226 | 227 | var postEvent 228 | 229 | switch (eType) { 230 | case EventType.misc.forget: 231 | // TODO: forget entry.get(ROOT_HASH) 232 | forget(entry, cb) 233 | return 234 | case EventType.msg.new: 235 | myDebug('new msg', entry.get(CUR_HASH)) 236 | break; 237 | case EventType.msg.edit: 238 | myDebug('edit msg', entry.get(CUR_HASH)) 239 | break; 240 | case EventType.misc.addIdentity: 241 | break 242 | case EventType.msg.receivedValid: 243 | postEvent = 'message' 244 | // fall through 245 | case EventType.msg.receivedInvalid: 246 | myDebug('received msg', entry.get(CUR_HASH)) 247 | entry.set('dateReceived', now()) 248 | break 249 | case EventType.msg.sendSuccess: 250 | myDebug('sent msg', entry.get(CUR_HASH)) 251 | entry.set('dateSent', now()) 252 | postEvent = 'sent' 253 | break 254 | case EventType.msg.sendError: 255 | case EventType.msg.giveUpSend: 256 | myDebug('send error', entry.get(CUR_HASH)) 257 | break 258 | case EventType.chain.writeSuccess: 259 | myDebug('msg chained', entry.get(CUR_HASH), entry.get('txId')) 260 | entry.set('dateChained', now()) 261 | postEvent = 'chained' 262 | break 263 | case EventType.chain.writeError: 264 | myDebug('msg chained (error)', entry.get(CUR_HASH)) 265 | break 266 | case EventType.chain.readSuccess: 267 | myDebug('unchained', entry.get(CUR_HASH), entry.get('txId'), entry.get('dateReceived')) 268 | entry.set('dateUnchained', now()) 269 | postEvent = 'unchained' 270 | break 271 | case EventType.chain.readError: 272 | myDebug('msg unchained (error)', entry.get(CUR_HASH), entry.get('txId')) 273 | try { 274 | getKey(entry) 275 | } catch (err) { 276 | // not storing 277 | return cb() 278 | } 279 | 280 | break 281 | // TODO: 282 | default: 283 | myDebug('ignoring entry of type', eType) 284 | return cb() 285 | } 286 | 287 | update(entry, function (batch) { 288 | cb(batch) 289 | if (postEvent && batch) { 290 | process.nextTick(function () { 291 | db.emit(postEvent, batch[0].value) 292 | }) 293 | } 294 | }) 295 | } 296 | 297 | function update (entry, cb) { 298 | var key 299 | try { 300 | key = getKey(entry) 301 | } catch (err) { 302 | myDebug(err.message) 303 | return cb() 304 | } 305 | 306 | return db.get(key, function (err, state) { 307 | if (!db.isOpen()) return cb() 308 | if (err && !err.notFound) throw err // should never happen 309 | 310 | var newEntry = state 311 | ? utils.updateEntry(state, entry) 312 | : entry 313 | 314 | var batch = [{ 315 | type: 'put', 316 | key: getKey(newEntry), 317 | value: newEntry.toJSON() 318 | }] 319 | 320 | // if (!utils.getEntryProp(newEntry, constants.TYPE)) { 321 | // throw new Error(utils.getEntryProp(newEntry, 'type')) 322 | // } 323 | 324 | addTimestampOps(newEntry, entry, batch) 325 | 326 | cb(batch) 327 | }) 328 | } 329 | 330 | function forget (entry, cb) { 331 | var otherGuyRootHash = entry.get('who') 332 | var togo = 3 333 | var batch = [] 334 | 335 | collect(db.rawReadStream(getToChainStreamOpts()), onCollected) 336 | collect(db.rawReadStream(getToSendStreamOpts()), onCollected) 337 | db.getConversation(otherGuyRootHash, true, function (err, results) { 338 | if (err) throw err 339 | 340 | batch.push.apply(batch, results.map(function (entry) { 341 | return { 342 | key: getKey(entry), 343 | type: 'del' 344 | } 345 | })) 346 | 347 | finish() 348 | }) 349 | 350 | function onCollected (err, results) { 351 | if (err) return finish() 352 | 353 | results.forEach(function (data) { 354 | if (data.value.indexOf(otherGuyRootHash) !== -1) { 355 | batch.push({ 356 | key: data.key, 357 | type: 'del', 358 | value: data.value 359 | }) 360 | } 361 | }) 362 | 363 | finish() 364 | } 365 | 366 | function finish () { 367 | if (--togo === 0) { 368 | cb(batch) 369 | db.emit('forgot', otherGuyRootHash) 370 | } 371 | } 372 | } 373 | } 374 | 375 | function getKey (entry) { 376 | return MAIN_PREFIX + utils.getUID(entry) 377 | } 378 | 379 | function addTimestampOps (state, update, batch) { 380 | var entryKey = getKey(state) 381 | var eType = utils.getEntryProp(update, 'type') 382 | var isNewOrEdit = eType === EventType.msg.new || eType === EventType.msg.edit 383 | var giveUpSend = eType === EventType.msg.giveUpSend 384 | if (utils.getEntryProp(state, 'chain')) { 385 | if (isNewOrEdit) { 386 | batch.push({ 387 | type: 'put', 388 | key: getChainTimestampKey(state), 389 | value: entryKey 390 | }) 391 | } else if (utils.getEntryProp(state, 'dateChained') || 392 | utils.getErrors(state, 'chain') >= Errors.MAX_CHAIN) { 393 | // remove from queue 394 | batch.push({ 395 | type: 'del', 396 | key: getChainTimestampKey(state), 397 | value: entryKey 398 | }) 399 | } 400 | } 401 | 402 | if (giveUpSend || utils.getEntryProp(state, 'deliver')) { 403 | if (isNewOrEdit) { 404 | batch.push({ 405 | type: 'put', 406 | key: getSendTimestampKey(state), 407 | value: entryKey 408 | }) 409 | } else if (giveUpSend 410 | || utils.getEntryProp(state, 'dateSent') 411 | || utils.getErrors(state, 'send') >= Errors.MAX_SEND) { 412 | batch.push({ 413 | type: 'del', 414 | key: getSendTimestampKey(state), 415 | value: entryKey 416 | }) 417 | } 418 | } 419 | } 420 | 421 | function getChainTimestampKey (entry) { 422 | return CHAIN_TIMESTAMP_PREFIX + utils.getEntryProp(entry, 'timestamp') 423 | } 424 | 425 | function getSendTimestampKey (entry) { 426 | return SEND_TIMESTAMP_PREFIX + utils.getEntryProp(entry, 'timestamp') 427 | } 428 | 429 | function errWithNotFound (cb) { 430 | return cb(new levelErrs.NotFoundError()) 431 | } 432 | -------------------------------------------------------------------------------- /lib/optimizations.js: -------------------------------------------------------------------------------- 1 | 2 | var Q = require('q') 3 | var bitcoin = require('@tradle/bitcoinjs-lib') 4 | var ECPubKey = bitcoin.ECPubKey 5 | var Keys = require('@tradle/kiki').Keys 6 | var ECKey = bitcoin.ECKey 7 | var Cache = require('lru-cache') 8 | var EllipticKeyPair = require('elliptic/lib/elliptic/ec/key') 9 | var utils = require('@tradle/utils') 10 | var extend = require('xtend') 11 | var Driver = require('../') 12 | var enabled = false 13 | var ID = 0 14 | var UINT16 = 0xffff; 15 | var getNextId = function () { 16 | return (ID++) & UINT16 17 | } 18 | 19 | function enable () { 20 | if (enabled) return 21 | 22 | enabled = true 23 | enableECPubKeyCaching() 24 | enableLookupObjectCaching() 25 | } 26 | 27 | module.exports = enable 28 | module.exports.enable = enable 29 | module.exports.enableLookupObjectCaching = enableLookupObjectCaching 30 | module.exports.enableECPubKeyCaching = enableECPubKeyCaching 31 | 32 | function enableLookupObjectCaching () { 33 | // var lookupObjectCache = new Cache({ 34 | // max: 30, 35 | // maxAge: 60000 // 1 min 36 | // }) 37 | 38 | // var lookupObject = Driver.prototype.lookupObject 39 | // Driver.prototype.lookupObject = function (info, verify) { 40 | // var key 41 | // if (info.txData) { 42 | // key = info.txData.toString('hex') 43 | // var cached = !verify && lookupObjectCache.get(key) 44 | // if (cached) return Q(cached) 45 | // } 46 | 47 | // return lookupObject.apply(this, arguments) 48 | // .then(function (result) { 49 | // key = key || result.txData.toString('hex') 50 | // lookupObjectCache.set(key, Object.freeze(result)) 51 | // return result 52 | // }) 53 | // } 54 | } 55 | 56 | function enableECPubKeyCaching () { 57 | // var cachedECPubKeys = new Cache({ 58 | // max: 500 59 | // }) 60 | 61 | var cachedBitcoinPubKeys = new Cache({ 62 | max: 500 63 | }) 64 | 65 | var cachedBitcoinPrivKeys = new Cache({ 66 | max: 500 67 | }) 68 | 69 | var fromBuffer = ECPubKey.fromBuffer 70 | var fromHex = ECPubKey.fromHex 71 | 72 | ECPubKey.fromBuffer = function (buffer, skipCache) { 73 | var hex 74 | if (!skipCache) { 75 | hex = buffer.toString('hex') 76 | var cached = cachedBitcoinPubKeys.get(hex) 77 | if (cached) return cached 78 | } 79 | 80 | var key = fromBuffer.call(ECPubKey, buffer) 81 | if (!skipCache) { 82 | cachedBitcoinPubKeys.set(hex, key) 83 | } 84 | 85 | return key 86 | } 87 | 88 | ECPubKey.fromHex = function (hex) { 89 | var cached = cachedBitcoinPubKeys.get(hex) 90 | if (!cached) { 91 | cached = ECPubKey.fromBuffer(new Buffer(hex, 'hex'), true) // skip cache 92 | cachedBitcoinPubKeys.set(hex, cached) 93 | } 94 | 95 | return cached 96 | } 97 | 98 | var fromWIF = ECKey.fromWIF 99 | ECKey.fromWIF = function (wif) { 100 | var cached = cachedBitcoinPrivKeys.get(wif) 101 | if (!cached) { 102 | cached = fromWIF(wif) 103 | cachedBitcoinPrivKeys.set(wif, cached) 104 | } 105 | 106 | return cached 107 | } 108 | 109 | Object.keys(Keys).filter(function (type) { 110 | return type !== 'Base' 111 | }).forEach(function (type) { 112 | var cache = new Cache({ 113 | max: 500 114 | }) 115 | 116 | var KeyCl = Keys[type] 117 | ;['parsePub', 'parsePriv'].forEach(function (method) { 118 | var orig = KeyCl.prototype[method] 119 | KeyCl.prototype[method] = function (pub) { 120 | var cached = cache.get(pub) 121 | if (!cached) { 122 | cached = orig.apply(this, arguments) 123 | cache.set(pub, cached) 124 | } 125 | 126 | return cached 127 | } 128 | }) 129 | }) 130 | 131 | var ecdh = utils.ecdh 132 | var cache = new Cache({ 133 | max: 500, 134 | maxAge: 60 * 1000 135 | }) 136 | 137 | utils.ecdh = function (aPriv, bPub) { 138 | var key = aPriv + bPub 139 | var cached = cache.get(key) 140 | if (!cached) { 141 | cached = ecdh.apply(this, arguments) 142 | cache.set(key, cached) 143 | } 144 | 145 | return cached 146 | } 147 | 148 | var ecdhCache = new Cache({ 149 | max: 1000, 150 | maxAge: 60 * 1000 151 | }) 152 | 153 | var sharedEncryptionKey = utils.sharedEncryptionKey 154 | utils.sharedEncryptionKey = function (aPriv, bPub, cb) { 155 | // TODO: unhardcode network 156 | if (typeof aPriv !== 'string') aPriv = aPriv.toWIF(bitcoin.networks.testnet) 157 | if (typeof bPub !== 'string') bPub = bPub.toHex() 158 | 159 | var key = aPriv + bPub 160 | var cached = ecdhCache.get(key) 161 | if (!cb) { 162 | if (!cached) { 163 | cached = sharedEncryptionKey.apply(this, arguments) 164 | ecdhCache.set(key, cached) 165 | } 166 | 167 | return cached 168 | } 169 | 170 | if (cached) return cb(null, cached) 171 | 172 | sharedEncryptionKey.call(utils, aPriv, bPub, function (err, result) { 173 | if (err) return cb(err) 174 | 175 | ecdhCache.set(key, result) 176 | return cb(null, result) 177 | }) 178 | } 179 | 180 | // var edCache = new Cache({ 181 | // max: 1000, 182 | // maxAge: 60 * 1000 183 | // }) 184 | 185 | // ;['encryptAsync', 'decryptAsync'].forEach(function (method) { 186 | // var orig = utils[method] 187 | // utils[method] = function (opts, cb) { 188 | // var key = method + opts.data.toString('hex') 189 | // var cached = edCache.get(key) 190 | // if (cached) { 191 | // console.log(method + ' from cache!') 192 | // return cb(null, cached) 193 | // } 194 | 195 | // orig.call(utils, opts, function (err, result) { 196 | // if (err) return cb(err) 197 | 198 | // edCache.set(key, result) 199 | // cb(null, result) 200 | // }) 201 | // } 202 | // }) 203 | } 204 | -------------------------------------------------------------------------------- /lib/rebufEncoding.js: -------------------------------------------------------------------------------- 1 | 2 | var rebuf = require('@tradle/utils').rebuf 3 | 4 | module.exports = { 5 | encode: function (entry) { 6 | return JSON.stringify(entry) 7 | }, 8 | decode: function (entry) { 9 | try { 10 | return rebuf(JSON.parse(entry)) 11 | } catch (err) { 12 | console.warn('failed to decode entry', entry) 13 | return entry 14 | } 15 | }, 16 | buffer: false, 17 | type: 'jsonWithBufs' 18 | } 19 | -------------------------------------------------------------------------------- /lib/txDB.js: -------------------------------------------------------------------------------- 1 | 2 | var debug = require('debug')('txDB') 3 | var typeforce = require('typeforce') 4 | var levelup = require('levelup') 5 | var LiveStream = require('level-live-stream') 6 | // var CUR_HASH = constants.CUR_HASH 7 | var lb = require('logbase') 8 | var LogBase = lb.Simple 9 | var EventType = require('./eventType') 10 | var rebuf = require('./rebufEncoding') 11 | var DEBUG = require('./debug') 12 | var utils = require('./utils') 13 | var ENTRY_TIMEOUT = DEBUG ? false : 5000 14 | 15 | module.exports = function createTxDB (path, options) { 16 | typeforce('String', path) 17 | typeforce({ 18 | leveldown: 'Function', 19 | log: 'Log' 20 | }, options) 21 | 22 | var db = levelup(path, { 23 | db: options.leveldown, 24 | valueEncoding: rebuf 25 | }) 26 | 27 | db = LogBase({ 28 | db: db, 29 | log: options.log, 30 | process: processEntry, 31 | timeout: typeof options.timeout === 'undefined' ? ENTRY_TIMEOUT : options.timeout, 32 | autostart: options.autostart, 33 | }) 34 | 35 | var topics = [ 36 | EventType.tx.new, 37 | EventType.tx.confirmation, 38 | EventType.tx.ignore, 39 | EventType.tx.watch, 40 | EventType.chain.writeSuccess, 41 | EventType.chain.readSuccess, 42 | EventType.chain.readError 43 | ] 44 | 45 | LiveStream.install(db) 46 | return db 47 | 48 | function myDebug () { 49 | var args = [].slice.call(arguments) 50 | args.unshift(db.name) 51 | return debug.apply(null, args) 52 | } 53 | 54 | function processEntry (entry, cb) { 55 | var eType = entry.get('type') 56 | if (topics.indexOf(eType) === -1) return cb() 57 | 58 | entry = entry.clone() 59 | 60 | var now = Date.now() 61 | 62 | switch (eType) { 63 | case EventType.tx.new: 64 | entry.set('dateDetected', now) 65 | myDebug('new tx') 66 | return updateOrPut(entry, cb) 67 | case EventType.tx.confirmation: 68 | // this may be the first confirmation 69 | // for a tx we put on chain 70 | entry.set('dateDetected', now) 71 | myDebug('confirmation tx') 72 | return updateOrPut(entry, cb) 73 | case EventType.tx.watch: 74 | entry.set('ignore', false) 75 | entry.set('watch', true) 76 | return updateOrPut(entry, cb) 77 | case EventType.tx.ignore: 78 | // this may be the first confirmation 79 | // for a tx we put on chain 80 | entry.set('dateDetected', now) 81 | entry.set('ignore', true) 82 | entry.set('watch', false) 83 | return updateOrPut(entry, cb) 84 | case EventType.chain.writeSuccess: 85 | entry.set('dateChained', now) 86 | myDebug('chain write success') 87 | return updateOrPut(entry, cb) 88 | case EventType.chain.readSuccess: 89 | entry.set('dateUnchained', now) 90 | myDebug('chain read success') 91 | return updateOrPut(entry, cb) 92 | case EventType.chain.readError: 93 | myDebug('chain read error') 94 | return updateOrPut(entry, cb) 95 | default: 96 | myDebug('ignoring entry of type', eType) 97 | return cb() 98 | } 99 | } 100 | 101 | function updateOrPut (entry, cb) { 102 | var key = getKey(entry) 103 | return db.get(key, function (err, root) { 104 | if (!db.isOpen()) return cb() 105 | if (err) { 106 | if (err.notFound) return put(entry, cb) 107 | else throw err // should never happen 108 | } 109 | 110 | doUpdate(root, entry, cb) 111 | }) 112 | } 113 | 114 | // function update (entry, cb) { 115 | // var key = getKey(entry) 116 | // return db.get(key, function (err, root) { 117 | // if (!db.isOpen()) return cb() 118 | // if (err) return cb(err) 119 | 120 | // // wtf is this? 121 | // doUpdate(root, entry, cb) 122 | // }) 123 | // } 124 | 125 | function doUpdate (root, entry, cb) { 126 | entry = utils.updateEntry(root, entry, ['dateDetected']) 127 | 128 | // console.log('overwriting', root, 'with', entryJSON, 'resulting in', entry.toJSON()) 129 | put(entry, cb) 130 | } 131 | 132 | function put (entry, cb) { 133 | myDebug('putting', entry.get('type'), entry.get('txId')) 134 | entry.unset('type') 135 | cb([{ 136 | type: 'put', 137 | key: getKey(entry), 138 | value: entry.toJSON() 139 | }]) 140 | } 141 | } 142 | 143 | function getKey (entry) { 144 | var txId = entry.get('txId') 145 | if (txId) return txId 146 | 147 | throw new Error('missing "txId"') 148 | } 149 | -------------------------------------------------------------------------------- /lib/typeDB.js: -------------------------------------------------------------------------------- 1 | var debug = require('debug')('msgDB') 2 | var typeforce = require('typeforce') 3 | // var lexint = require('lexicographic-integer') 4 | var collect = require('stream-collector') 5 | var levelup = require('levelup') 6 | var Q = require('q') 7 | var pump = require('pump') 8 | var map = require('map-stream') 9 | // var levelQuery = require('level-queryengine') 10 | // var jsonQueryEngine = require('jsonquery-engine') 11 | var safe = require('safecb') 12 | var constants = require('@tradle/constants') 13 | // var TxData = require('tradle-tx-data').TxData 14 | var levelErrs = require('level-errors') 15 | var LiveStream = require('level-live-stream') 16 | var CUR_HASH = constants.CUR_HASH 17 | var ROOT_HASH = constants.ROOT_HASH 18 | var TYPE = constants.TYPE 19 | var TYPES = constants.TYPES 20 | var lb = require('logbase') 21 | var Entry = lb.Entry 22 | var LogBase = lb.Simple 23 | var EventType = require('./eventType') 24 | var rebuf = require('./rebufEncoding') 25 | var DEBUG = require('./debug') 26 | var utils = require('./utils') 27 | var Errors = require('./errors') 28 | var SEPARATOR = '!' 29 | var now = utils.now 30 | var ENTRY_TIMEOUT = DEBUG ? false : 5000 31 | 32 | module.exports = function createMsgDB (path, options) { 33 | typeforce('String', path) 34 | typeforce({ 35 | leveldown: 'Function', 36 | log: 'Log', 37 | keeper: 'Object' 38 | }, options) 39 | 40 | var keeper = options.keeper 41 | var db = levelup(path, { 42 | db: options.leveldown, 43 | valueEncoding: rebuf 44 | }) 45 | 46 | db = LogBase({ 47 | db: db, 48 | log: options.log, 49 | process: processEntry, 50 | timeout: typeof options.timeout === 'undefined' ? ENTRY_TIMEOUT : options.timeout, 51 | autostart: options.autostart 52 | }) 53 | 54 | var topics = [ 55 | EventType.misc.forget, 56 | EventType.msg.new, 57 | EventType.msg.edit, 58 | EventType.msg.receivedValid, 59 | EventType.msg.sendSuccess, 60 | ] 61 | 62 | LiveStream.install(db) 63 | 64 | var createReadStream = db.createReadStream 65 | db.createReadStream = function (type) { 66 | return createReadStream.call(db, { 67 | lte: type + SEPARATOR + '\xff', 68 | gte: type + SEPARATOR, 69 | keys: false 70 | }) 71 | .pipe(map(function (val, cb) { 72 | cb(null, val.meta) 73 | })) 74 | } 75 | 76 | db.setMaxListeners(0) 77 | return db 78 | 79 | function myDebug () { 80 | var args = [].slice.call(arguments) 81 | args.unshift(db.name) 82 | return debug.apply(null, args) 83 | } 84 | 85 | function processEntry (entry, cb) { 86 | var eType = entry.get('type') 87 | if (topics.indexOf(eType) === -1) return cb() 88 | 89 | entry = entry.clone() 90 | 91 | if (eType === EventType.misc.forget) { 92 | return forget(entry, cb) 93 | } 94 | 95 | const type = entry.get(TYPE) 96 | if (!type) return cb() 97 | 98 | var key = type + SEPARATOR + entry.get(ROOT_HASH) 99 | return db.get(key, function (err, state) { 100 | if (!db.isOpen()) return cb() 101 | if (err && !err.notFound) throw err // should never happen 102 | 103 | var newEntry = state 104 | ? utils.updateEntry(state, entry) 105 | : entry 106 | 107 | var from = newEntry.get('from') 108 | from = from && from[ROOT_HASH] 109 | 110 | var to = newEntry.get('to') 111 | to = to && to[ROOT_HASH] 112 | var batch = [{ 113 | type: 'put', 114 | key: key, 115 | value: { 116 | // data needed for lookupObject 117 | meta: utils.pick(entry.toJSON(), ['txType', 'txData', 'addressesFrom', 'addressesTo']), 118 | participants: [ from, to ] 119 | } 120 | }] 121 | 122 | cb(batch) 123 | }) 124 | } 125 | 126 | function forget (entry, cb) { 127 | var otherGuyRootHash = entry.get('who') 128 | var togo = 3 129 | var stream = db.rawReadStream({ 130 | gt: '\x00' 131 | }) 132 | .pipe(map(function (data, cb) { 133 | if (data.value.participants.indexOf(otherGuyRootHash) !== -1) { 134 | cb(null, data) 135 | } else { 136 | cb() 137 | } 138 | })) 139 | 140 | collect(stream, function (err, results) { 141 | if (err) return cb(err) 142 | 143 | var batch = results.map(function (data) { 144 | return { 145 | key: data.key, 146 | type: 'del' 147 | } 148 | }) 149 | 150 | cb(batch) 151 | }) 152 | } 153 | } 154 | 155 | function errWithNotFound (cb) { 156 | return cb(new levelErrs.NotFoundError()) 157 | } 158 | -------------------------------------------------------------------------------- /lib/unchainer.js: -------------------------------------------------------------------------------- 1 | 2 | var bitcoin = require('@tradle/bitcoinjs-lib') 3 | var map = require('map-stream') 4 | var Q = require('q') 5 | var debug = require('debug')('unchainer') 6 | var extend = require('xtend/mutable') 7 | var typeforce = require('typeforce') 8 | var Parser = require('@tradle/chained-obj').Parser 9 | var Identity = require('@tradle/identity').Identity 10 | var Verifier = require('@tradle/verifier') 11 | var CONSTANTS = require('@tradle/constants') 12 | var utils = require('./utils') 13 | var Errors = require('./errors') 14 | var TYPE = CONSTANTS.TYPE 15 | var CUR_HASH = CONSTANTS.CUR_HASH 16 | var ROOT_HASH = CONSTANTS.ROOT_HASH 17 | var SIGNEE = CONSTANTS.SIGNEE 18 | var plugins = Verifier.plugins 19 | var DEFAULT_PLUGINS = [ 20 | plugins.sigcheck, 21 | plugins.prev, 22 | plugins.identity 23 | ] 24 | 25 | /** 26 | * transactions go in, verified on-chain objects come out (or die inside) 27 | * @param {[type]} options [description] 28 | * @return {[type]} [description] 29 | */ 30 | module.exports = function chainstream (options) { 31 | typeforce({ 32 | lookup: 'Function', 33 | chainloader: 'Object' 34 | }, options) 35 | 36 | var chainloader = options.chainloader 37 | var verifier = new Verifier({ 38 | lookup: options.lookup 39 | }) 40 | 41 | var plugins = DEFAULT_PLUGINS.slice() 42 | if (options.plugins) { 43 | options.plugins.forEach(function (p) { 44 | if (plugins.indexOf(p) === -1) { 45 | plugins.push(p) 46 | } 47 | }) 48 | } 49 | 50 | verifier.use(plugins) 51 | 52 | return { 53 | unchain: unchain 54 | } 55 | 56 | function unchain (txEntry, opts) { 57 | opts = opts || {} 58 | typeforce({ 59 | parse: '?Boolean', 60 | verify: '?Boolean' 61 | }, opts) 62 | 63 | var doVerify = opts.verify !== false 64 | var doParse = doVerify || opts.parse !== false 65 | var processed = extend({}, txEntry) 66 | return chainloader.load(txEntry) 67 | .catch(saveProgressAndRethrow(processed)) 68 | .then(function (obj) { 69 | extend(processed, obj) 70 | if (doParse) { 71 | return parse(processed) 72 | .then(checkFrom.bind(null, processed)) 73 | } 74 | }) 75 | .then(function () { 76 | processed[CUR_HASH] = processed.key 77 | processed[ROOT_HASH] = processed.parsed.data[ROOT_HASH] || processed.key 78 | processed[TYPE] = processed.parsed.data[TYPE] 79 | 80 | if (doVerify) { 81 | return verify(verifier, processed) 82 | } 83 | }) 84 | .then(function () { 85 | return processed 86 | }) 87 | } 88 | } 89 | 90 | function parse (chainedObj) { 91 | return Parser.parse(chainedObj.data) 92 | .then(function (parsed) { 93 | chainedObj.parsed = parsed 94 | }) 95 | .catch(saveProgressAndRethrow(chainedObj, Errors.Parse)) 96 | } 97 | 98 | function checkFrom (chainedObj) { 99 | var parsed = chainedObj.parsed 100 | var json = parsed.data 101 | var isIdentity = json[TYPE] === Identity.TYPE 102 | var from = chainedObj.from 103 | // only identities are allowed to be created without an identity 104 | if (!from && isIdentity) { 105 | chainedObj.from = { 106 | identity: Identity.fromJSON(json) 107 | } 108 | 109 | chainedObj.from[ROOT_HASH] = chainedObj[ROOT_HASH] || chainedObj.key 110 | } 111 | 112 | if (!(chainedObj.from && chainedObj.to)) return 113 | 114 | // at this point, from/to are based on tx addresses 115 | // if possible, take them from signing party 116 | // not possible if an object was shared that was authored by a third party 117 | var objAuthor = chainedObj.parsed.data[SIGNEE] 118 | if (!objAuthor) return 119 | 120 | var objAuthorRH = objAuthor && objAuthor.split(':')[0] 121 | var txAuthorRH = chainedObj.from[ROOT_HASH] 122 | var toRH = chainedObj.to[ROOT_HASH] 123 | if (toRH === objAuthorRH) { 124 | // switch 125 | var tmp = chainedObj.from 126 | chainedObj.from = chainedObj.to 127 | chainedObj.to = tmp 128 | } 129 | } 130 | 131 | function verify (verifier, chainedObj) { 132 | return Q.ninvoke(verifier, 'verify', chainedObj) 133 | .catch(saveProgressAndRethrow(chainedObj, Errors.Verification)) 134 | } 135 | 136 | function saveProgressAndRethrow (chainedObj, ErrType) { 137 | return function (err) { 138 | debug('unchain failed', chainedObj.key, err.message) 139 | if (ErrType) err = new ErrType(err) 140 | 141 | utils.addError({ 142 | entry: chainedObj, 143 | group: 'unchain', 144 | error: err 145 | }) 146 | 147 | throw err 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /lib/utils.js: -------------------------------------------------------------------------------- 1 | var Q = require('q') 2 | var extend = require('xtend') 3 | var typeforce = require('typeforce') 4 | var find = require('array-find') 5 | var map = require('map-stream') 6 | var constants = require('@tradle/constants') 7 | var tutils = require('@tradle/utils') 8 | var bitcoin = require('@tradle/bitcoinjs-lib') 9 | var hrtime = require('monotonic-timestamp') 10 | var Errors = require('./errors') 11 | var Builder = require('@tradle/chained-obj').Builder 12 | var Entry = require('logbase').Entry 13 | var debug = require('debug')('tim-utils') 14 | var NONCE = constants.NONCE 15 | var CUR_HASH = constants.CUR_HASH 16 | var ROOT_HASH = constants.ROOT_HASH 17 | var PREV_HASH = constants.PREV_HASH 18 | var TxData = require('@tradle/tx-data').TxData 19 | var Entry = require('logbase').Entry 20 | var MAX_ERRORS = 10 21 | 22 | var PRIVATE_MSG_SCHEMA = { 23 | txType: 'Number', 24 | encryptedPermission: 'Buffer', 25 | encryptedData: 'Buffer', 26 | // txData: '?Buffer', 27 | v: '?String' 28 | } 29 | 30 | var PUBLIC_MSG_SCHEMA = { 31 | txType: 'Number', 32 | data: 'Buffer', 33 | // txData: '?Buffer', 34 | v: '?String' 35 | } 36 | 37 | var getMsgSchema = function (msg) { 38 | return msg.txType === TxData.types.public 39 | ? PUBLIC_MSG_SCHEMA 40 | : PRIVATE_MSG_SCHEMA 41 | } 42 | 43 | var utils = module.exports = { 44 | getMsgProps: function (info) { 45 | var schema = getMsgSchema(info) 46 | var props = utils.pick(info, Object.keys(schema)) 47 | // if (info.encryptedKey) { 48 | // props.txData = info.encryptedKey 49 | // } 50 | 51 | return props 52 | }, 53 | 54 | validateMsg: function (msg) { 55 | try { 56 | typeforce(getMsgSchema(msg), msg) 57 | return true 58 | } catch (err) { 59 | console.log(err) 60 | return false 61 | } 62 | }, 63 | 64 | msgToBuffer: function (msg) { 65 | if (!utils.validateMsg(msg)) throw new Error('invalid msg') 66 | 67 | var schema = getMsgSchema(msg) 68 | msg = extend(msg) 69 | for (var p in schema) { 70 | var type = schema[p] 71 | var val = msg[p] 72 | if (Buffer.isBuffer(val)) { 73 | msg[p] = val.toString('base64') 74 | } 75 | } 76 | 77 | return utils.toBuffer(msg, 'binary') 78 | }, 79 | 80 | bufferToMsg: function (buf) { 81 | var msg = JSON.parse(buf.toString('binary')) 82 | var schema = getMsgSchema(msg) 83 | for (var p in schema) { 84 | var type = schema[p] 85 | var val = msg[p] 86 | if (val && type.indexOf('Buffer') !== -1) { 87 | msg[p] = new Buffer(val, 'base64') 88 | } 89 | } 90 | 91 | return msg 92 | }, 93 | 94 | /** 95 | * get msg uid, currently: 96 | * rootHash-curHash-senderRootHash-recipientRootHash 97 | * OR 98 | * rootHash-curHash-"public" 99 | * @param {Entry} entry 100 | * @return {String} 101 | */ 102 | getUID: function (entry) { 103 | var uid = utils.getEntryProp(entry, 'uid') 104 | if (uid) return uid 105 | 106 | var isPublic = utils.getEntryProp(entry, 'txType') === TxData.types.public 107 | var curHash = utils.getEntryProp(entry, CUR_HASH) 108 | var rootHash = utils.getEntryProp(entry, ROOT_HASH) 109 | if (!curHash || !rootHash) { 110 | throw new Error('missing one of required properties: ' + CUR_HASH + ', ' + ROOT_HASH) 111 | } 112 | 113 | var keyParts = [rootHash, curHash] 114 | if (isPublic) { 115 | keyParts.push('public') 116 | } else { 117 | var from = utils.getEntryProp(entry, 'from') 118 | from = from && from[ROOT_HASH] 119 | var to = utils.getEntryProp(entry, 'to') 120 | to = to && to[ROOT_HASH] 121 | if (!(from && to)) { 122 | throw new Error('unable to derive uid for entry: ' + JSON.stringify(entry)) 123 | } 124 | 125 | keyParts.push(from, to) 126 | } 127 | 128 | return keyParts.join('-') 129 | }, 130 | 131 | parseUID: function (uid) { 132 | var parts = uid.split('-') 133 | var parsed = {} 134 | parsed[ROOT_HASH] = parts.shift() 135 | parsed[CUR_HASH] = parts.shift() 136 | if (parts.indexOf('public') === -1) { 137 | parsed.from = parts.shift() 138 | parsed.to = parts.shift() 139 | } else { 140 | parsed.public = true 141 | } 142 | 143 | return parsed 144 | }, 145 | 146 | toErrInstance: function (err) { 147 | var n = new Error(err.message) 148 | for (var p in err) { 149 | n[p] = err[p] 150 | } 151 | 152 | return n 153 | }, 154 | 155 | pluck: function (arr, prop) { 156 | var vals = [] 157 | for (var i = 0; i < arr.length; i++) { 158 | vals.push(arr[i][prop]) 159 | } 160 | 161 | return vals 162 | }, 163 | 164 | pick: function (obj) { 165 | var a = {} 166 | var props = Array.isArray(arguments[1]) 167 | ? arguments[1] 168 | : [].slice.call(arguments, 1) 169 | 170 | for (var i = 0; i < props.length; i++) { 171 | var p = props[i] 172 | a[p] = obj[p] 173 | } 174 | 175 | return a 176 | }, 177 | 178 | setUID: function (entry) { 179 | utils.setEntryProp(entry, 'uid', utils.getUID(entry)) 180 | }, 181 | 182 | firstKey: function (keys, where) { 183 | if (typeof where === 'string') where = { fingerprint: where } 184 | 185 | return find(keys, function (k) { 186 | for (var p in where) { 187 | var val = k.get ? k.get(p) : k[p] 188 | if (where[p] !== val) return 189 | } 190 | 191 | return true 192 | }) 193 | }, 194 | 195 | getDHTKey: function (obj, cb) { 196 | if (!obj[NONCE]) return Q.reject(new Error('missing nonce')) 197 | 198 | return new Builder() 199 | .data(obj) 200 | .build() 201 | .then(function (buf) { 202 | return Q.ninvoke(tutils, 'getStorageKeyFor', buf) 203 | }) 204 | .then(function (key) { 205 | return key.toString('hex') 206 | }) 207 | }, 208 | 209 | addError: function (opts) { 210 | typeforce({ 211 | group: 'String', 212 | entry: 'Object', 213 | error: 'Object' 214 | }, opts) 215 | 216 | var group = opts.group 217 | if (!(group in Errors.group)) { 218 | throw new Error('invalid error group') 219 | } 220 | 221 | var entry = opts.entry 222 | var errs = utils.getEntryProp(entry, 'errors') || {} 223 | errs[group] = errs[group] || [] 224 | if (!errs[group]) errs[group] = [] 225 | 226 | errs[group].push(utils.errToJSON(opts.error)) 227 | utils.setEntryProp(entry, 'errors', errs) 228 | opts.error.progress = entry 229 | }, 230 | 231 | getErrors: function (entry, group) { 232 | if (!(group in Errors.group)) { 233 | throw new Error('invalid error group') 234 | } 235 | 236 | var errs = utils.getEntryProp(entry, 'errors') 237 | return errs && errs[group] 238 | }, 239 | 240 | countErrors: function (entry, group) { 241 | if (group) { 242 | var errs = utils.getErrors(entry, group) 243 | return errs ? errs.length : 0 244 | } else { 245 | var total = 0 246 | var errs = utils.getEntryProp(entry, 'errors') 247 | if (errs) { 248 | for (var g in errs) { 249 | total += errs[g].length 250 | } 251 | } 252 | 253 | return total 254 | } 255 | }, 256 | 257 | updateEntry: function (older, newer, dontOverride) { 258 | var olderJSON = older.toJSON ? older.toJSON() : older 259 | var newerJSON = newer.toJSON ? newer.toJSON() : newer 260 | var mergedErrs = extend(olderJSON.errors) 261 | var newErrs = newerJSON.errors 262 | if (newErrs) { 263 | for (var group in newErrs) { 264 | var gErrs = mergedErrs[group] = (mergedErrs[group] || []).concat(newErrs[group]) 265 | if (gErrs.length > MAX_ERRORS) { 266 | // keep first MAX_ERRORS - 1 plus the last one 267 | var last = gErrs.pop() 268 | gErrs = gErrs.slice(0, MAX_ERRORS - 1).concat(last) 269 | debug('avoiding saving too many errors to db') 270 | } 271 | } 272 | } 273 | 274 | var timesProcessed = (olderJSON.timesProcessed || 1) + 1 275 | var updated = Entry.fromJSON(olderJSON) 276 | .set(newerJSON) 277 | .set('timestamp', olderJSON.timestamp) 278 | .set('errors', mergedErrs) 279 | .set('timesProcessed', timesProcessed) 280 | 281 | if (dontOverride) { 282 | dontOverride.forEach(function (p) { 283 | if (olderJSON[p]) updated.set(p, olderJSON[p]) 284 | }) 285 | } 286 | 287 | return updated 288 | }, 289 | 290 | now: Date.now.bind(Date), 291 | 292 | toObj: function (/* k1, v1, k2, v2... */) { 293 | var obj = {} 294 | for (var i = 0; i < arguments.length; i += 2) { 295 | obj[arguments[i]] = arguments[i + 1] 296 | } 297 | 298 | return obj 299 | }, 300 | 301 | errToJSON: function (err) { 302 | if (!(err instanceof Error)) return err 303 | 304 | var json = {} 305 | 306 | Object.getOwnPropertyNames(err).forEach(function (key) { 307 | json[key] = err[key] 308 | }) 309 | 310 | delete json.progress 311 | delete json.cause 312 | delete json.stack 313 | return json 314 | }, 315 | 316 | toBuffer: function (data, enc) { 317 | if (typeof data.toBuffer === 'function') return data.toBuffer() 318 | if (Buffer.isBuffer(data)) return data 319 | if (typeof data === 'object') data = tutils.stringify(data) 320 | 321 | return new Buffer(data, enc || 'utf8') 322 | }, 323 | 324 | getEntryProp: function (entry, prop) { 325 | return entry instanceof Entry ? entry.get(prop) : entry[prop] 326 | }, 327 | 328 | setEntryProp: function (obj, name, val) { 329 | if (obj instanceof Entry) obj.set(name, val) 330 | else obj[name] = val 331 | }, 332 | 333 | getOTRKeyFingerprint: function (identity) { 334 | return find(identity.pubkeys, function (k) { 335 | return k.type === 'dsa' && k.purpose === 'sign' 336 | }).fingerprint 337 | }, 338 | 339 | keyForFingerprint: function (identityJSON, fingerprint) { 340 | return find(identityJSON.pubkeys, function (k) { 341 | return k.fingerprint === fingerprint 342 | }) 343 | }, 344 | 345 | updateChainedObj: function (obj, prevHash) { 346 | obj[ROOT_HASH] = obj[ROOT_HASH] || prevHash 347 | obj[PREV_HASH] = prevHash 348 | return obj 349 | }, 350 | 351 | filterStream: function (filter) { 352 | return map(function (data, cb) { 353 | if (filter(data)) { 354 | return cb(null, data) 355 | } else { 356 | return cb() 357 | } 358 | }) 359 | }, 360 | 361 | promiseDelay: function (millis) { 362 | return Q.Promise(function (resolve) { 363 | setTimeout(resolve, millis) 364 | }) 365 | }, 366 | 367 | /** 368 | * rate limits a function that returns a promise 369 | * @param {Function} fn function that returns a promise 370 | * @param {Integer} millis [description] 371 | * @return {Function} rate limited fn 372 | */ 373 | rateLimitPromiseFn: function (fn, millis) { 374 | var lastCalled = 0 375 | return function () { 376 | var now = utils.now() 377 | var timePassed = now - lastCalled 378 | var ctx = this 379 | var args = arguments 380 | if (timePassed >= millis) { 381 | return call() 382 | } 383 | 384 | var delay = millis - timePassed 385 | debug('rate limiting, delaying call by ' + delay + 'ms') 386 | return utils.promiseDelay(delay) 387 | .then(call) 388 | 389 | function call () { 390 | lastCalled = utils.now() 391 | return fn.apply(ctx, args) 392 | } 393 | } 394 | }, 395 | 396 | jsonifyErrors: function (entry) { 397 | var errs = utils.getEntryProp(entry, 'errors') 398 | if (errs) { 399 | for (var group in errs) { 400 | errs[group] = errs[group].map(function (err) { 401 | if (!err.timestamp) err.timestamp = hrtime() 402 | 403 | return utils.errToJSON(err) 404 | }) 405 | 406 | utils.setEntryProp(entry, 'errors', errs) 407 | } 408 | } 409 | 410 | return entry 411 | }, 412 | 413 | jsonify: map.bind(null, function (entry, cb) { 414 | cb(null, utils.jsonifyErrors(entry)) 415 | }), 416 | 417 | parseCommonBlockchainTxs: function (txInfos) { 418 | var parsed = [].concat(txInfos).map(function (txInfo) { 419 | var tx 420 | if (txInfo.txHex) tx = bitcoin.Transaction.fromHex(txInfo.txHex) 421 | else if (Buffer.isBuffer(txInfo.tx)) tx = bitcoin.Transaction.fromBuffer(txInfo.tx) 422 | else if (txInfo.tx instanceof bitcoin.Transaction) tx = txInfo.tx 423 | else throw new Error('unable to restore tx') 424 | 425 | return { 426 | txId: txInfo.txId, 427 | height: txInfo.height || txInfo.blockHeight, 428 | blockId: txInfo.blockId, 429 | confirmations: txInfo.confirmations || txInfo.__confirmations, 430 | blockTimestamp: txInfo.blockTimestamp || txInfo.__blockTimestamp, 431 | tx: tx 432 | } 433 | }) 434 | 435 | return Array.isArray(txInfos) ? parsed : parsed[0] 436 | }, 437 | 438 | argsToArray: function (args) { 439 | return Array.prototype.concat.apply([], args) 440 | } 441 | } 442 | -------------------------------------------------------------------------------- /licenses.csv: -------------------------------------------------------------------------------- 1 | "module name","license","repository" 2 | "@tradle/bitcoinjs-lib@1.5.7","MIT*","https://github.com/bitcoinjs/bitcoinjs-lib" 3 | "@tradle/bitjoe-js@0.1.1","MIT","https://github.com/tradle/bitjoe-js" 4 | "@tradle/bittorrent-dht@3.2.1","MIT","https://github.com/feross/bittorrent-dht" 5 | "@tradle/cb-blockr@3.1.1","ISC","https://github.com/weilu/cb-blockr" 6 | "@tradle/chained-obj@2.0.1","MIT","https://github.com/tradle/chained-obj" 7 | "@tradle/chainloader@1.1.2","MIT","git+https://github.com/tradle/chainloader" 8 | "@tradle/constants@1.1.3","MIT","https://github.com/mvayngrib/tradle-constants" 9 | "@tradle/dht-relay@1.0.0","ISC","" 10 | "@tradle/identity@1.0.7","MIT","" 11 | "@tradle/kiki@1.1.10","MIT","" 12 | "@tradle/multiplex-utp@1.0.1","ISC","https://github.com/mvayngrib/multiplex-utp" 13 | "@tradle/otr@0.2.15","MPL v2.0","https://github.com/arlolra/otr" 14 | "@tradle/permission@0.0.1","MIT","git+https://github.com/tradle/permission" 15 | "@tradle/simple-wallet@0.0.1","MIT","https://github.com/mvayngrib/simple-wallet" 16 | "@tradle/spender@1.0.2","MIT","https://github.com/mvayngrib/spender" 17 | "@tradle/talko@1.0.1","ISC","" 18 | "@tradle/test-helpers@0.0.4","MIT","git+https://github.com/tradle/test-helpers" 19 | "@tradle/tx-data@0.0.1","MIT","git+https://github.com/tradle/tx-data" 20 | "@tradle/utils@0.2.4","MIT","" 21 | "@tradle/utp@0.0.8","MIT*","https://github.com/mafintosh/utp" 22 | "@tradle/verifier@1.0.1","ISC","https://github.com/mvayngrib/tradle-verifier" 23 | "abbrev@1.0.7","ISC","http://github.com/isaacs/abbrev-js" 24 | "abstract-leveldown@0.12.4","MIT","https://github.com/rvagg/node-abstract-leveldown" 25 | "abstract-leveldown@2.4.1","MIT","https://github.com/level/abstract-leveldown" 26 | "accepts@1.2.13","MIT","https://github.com/jshttp/accepts" 27 | "acorn@1.2.2","MIT","https://github.com/marijnh/acorn" 28 | "add-stream@1.0.0","MIT","https://github.com/wilsonjackson/add-stream" 29 | "addr-to-ip-port@1.4.2","MIT","https://github.com/feross/addr-to-ip-port" 30 | "align-text@0.1.3","MIT","https://github.com/jonschlinkert/align-text" 31 | "alter@0.2.0","MIT","https://github.com/olov/alter" 32 | "amdefine@1.0.0","BSD-3-Clause AND MIT","https://github.com/jrburke/amdefine" 33 | "ansi-regex@1.1.1","MIT","https://github.com/sindresorhus/ansi-regex" 34 | "ansi-regex@2.0.0","MIT","https://github.com/sindresorhus/ansi-regex" 35 | "ansi-styles@2.1.0","MIT","https://github.com/chalk/ansi-styles" 36 | "argparse@1.0.3","MIT","git+https://github.com/nodeca/argparse" 37 | "array-find@0.1.1","ISC","https://github.com/stefanduberg/array-find" 38 | "array-find@1.0.0","MIT","https://github.com/stefanduberg/array-find" 39 | "array-flatten@1.1.1","MIT","https://github.com/blakeembrey/array-flatten" 40 | "asap@2.0.3","MIT","https://github.com/kriskowal/asap" 41 | "asn1@0.2.3","MIT","https://github.com/mcavage/node-asn1" 42 | "assert-plus@0.1.5","MIT*","https://github.com/mcavage/node-assert-plus" 43 | "assert-plus@0.2.0","MIT","https://github.com/mcavage/node-assert-plus" 44 | "ast-traverse@0.1.1","MIT","https://github.com/olov/ast-traverse" 45 | "ast-types@0.8.12","MIT","https://github.com/benjamn/ast-types" 46 | "async@0.9.2","MIT","https://github.com/caolan/async" 47 | "async@1.5.0","MIT","https://github.com/caolan/async" 48 | "aws-sign2@0.6.0","Apache-2.0","https://github.com/mikeal/aws-sign" 49 | "babel-core@5.8.34","MIT","https://github.com/babel/babel" 50 | "babel-plugin-constant-folding@1.0.1","MIT","https://github.com/babel-plugins/babel-plugin-constant-folding" 51 | "babel-plugin-dead-code-elimination@1.0.2","MIT","https://github.com/babel-plugins/babel-plugin-dead-code-elimination" 52 | "babel-plugin-eval@1.0.1","MIT","https://github.com/babel-plugins/babel-plugin-eval" 53 | "babel-plugin-inline-environment-variables@1.0.1","MIT","https://github.com/babel-plugins/babel-plugin-inline-environment-variables" 54 | "babel-plugin-jscript@1.0.4","MIT","https://github.com/babel-plugins/babel-plugin-jscript" 55 | "babel-plugin-member-expression-literals@1.0.1","MIT","https://github.com/babel-plugins/babel-plugin-member-expression-literals" 56 | "babel-plugin-property-literals@1.0.1","MIT","https://github.com/babel-plugins/babel-plugin-property-literals" 57 | "babel-plugin-proto-to-assign@1.0.4","MIT","https://github.com/babel-plugins/babel-plugin-proto-to-assign" 58 | "babel-plugin-react-constant-elements@1.0.3","MIT","https://github.com/babel-plugins/babel-plugin-react-constant-elements" 59 | "babel-plugin-react-display-name@1.0.3","MIT","https://github.com/babel-plugins/babel-plugin-react-display-name" 60 | "babel-plugin-remove-console@1.0.1","MIT","https://github.com/babel-plugins/babel-plugin-remove-console" 61 | "babel-plugin-remove-debugger@1.0.1","MIT","https://github.com/babel-plugins/babel-plugin-remove-debugger" 62 | "babel-plugin-runtime@1.0.7","MIT","https://github.com/babel-plugins/babel-plugin-runtime" 63 | "babel-plugin-undeclared-variables-check@1.0.2","MIT","https://github.com/babel-plugins/babel-plugin-undeclared-variables-check" 64 | "babel-plugin-undefined-to-void@1.1.6","MIT","https://github.com/babel-plugins/babel-plugin-undefined-to-void" 65 | "babylon@5.8.34","MIT","https://github.com/babel/babel" 66 | "balanced-match@0.3.0","MIT","https://github.com/juliangruber/balanced-match" 67 | "base64-js@0.0.2","MIT","https://github.com/beatgammit/deflate-js" 68 | "bencode@0.7.0","MIT","https://github.com/themasch/node-bencode" 69 | "bigi@1.4.1","MIT*","https://github.com/cryptocoinjs/bigi" 70 | "bl@0.8.2","MIT","https://github.com/rvagg/bl" 71 | "bl@1.0.0","MIT","https://github.com/rvagg/bl" 72 | "block-stream2@1.0.0","MIT","https://github.com/substack/block-stream2" 73 | "bluebird@2.10.2","MIT","https://github.com/petkaantonov/bluebird" 74 | "bn.js@2.2.0","MIT","https://github.com/indutny/bn.js" 75 | "bn.js@4.5.1","MIT","https://github.com/indutny/bn.js" 76 | "boom@2.10.1","BSD-3-Clause","https://github.com/hapijs/boom" 77 | "bops@0.1.1","MIT","https://github.com/chrisdickinson/bops" 78 | "brace-expansion@1.1.2","MIT","https://github.com/juliangruber/brace-expansion" 79 | "breakable@1.0.0","MIT","https://github.com/olov/breakable" 80 | "brorand@1.0.5","MIT","https://github.com/indutny/brorand" 81 | "browser-process-hrtime@0.1.2","BSD-2-Clause","https://github.com/kumavis/browser-process-hrtime" 82 | "bs58@2.0.1","MIT","http://github.com/cryptocoinjs/bs58" 83 | "bs58check@1.0.6","MIT","https://github.com/dcousens/bs58check" 84 | "buffer-equal@0.0.1","MIT","https://github.com/substack/node-buffer-equal" 85 | "bytewise@0.7.1","MIT","https://github.com/deanlandolt/bytewise" 86 | "camelcase@1.2.1","MIT","https://github.com/sindresorhus/camelcase" 87 | "caseless@0.11.0","Apache-2.0","https://github.com/mikeal/caseless" 88 | "center-align@0.1.2","MIT","https://github.com/jonschlinkert/center-align" 89 | "chalk@1.1.1","MIT","https://github.com/chalk/chalk" 90 | "changes-feed@1.1.0","MIT","https://github.com/mafintosh/changes-feed" 91 | "cipher-base@1.0.2","MIT","git+https://github.com/crypto-browserify/cipher-base" 92 | "cli-width@1.1.0","ISC","https://github.com/knownasilya/cli-width" 93 | "cliui@2.1.0","ISC","http://github.com/bcoe/cliui" 94 | "clone@1.0.2","MIT","https://github.com/pvorb/node-clone" 95 | "closest-to@0.0.2","MIT","https://github.com/michaelrhodes/closest-to" 96 | "combined-stream@0.0.7","MIT*","https://github.com/felixge/node-combined-stream" 97 | "combined-stream@1.0.5","MIT","https://github.com/felixge/node-combined-stream" 98 | "commander@2.9.0","MIT","https://github.com/tj/commander.js" 99 | "commoner@0.10.4","MIT","https://github.com/reactjs/commoner" 100 | "compact2string@1.4.0","BSD","https://github.com/bencevans/node-compact2string" 101 | "component-emitter@1.1.2","MIT*","https://github.com/component/emitter" 102 | "concat-map@0.0.1","MIT","https://github.com/substack/node-concat-map" 103 | "concat-stream@1.5.1","MIT","https://github.com/maxogden/concat-stream" 104 | "config-chain@1.1.9","MIT","https://github.com/dominictarr/config-chain" 105 | "content-disposition@0.5.0","MIT","https://github.com/jshttp/content-disposition" 106 | "content-type@1.0.1","MIT","https://github.com/jshttp/content-type" 107 | "convert-source-map@1.1.2","MIT","https://github.com/thlorenz/convert-source-map" 108 | "cookie@0.1.3","MIT","https://github.com/jshttp/cookie" 109 | "cookie-signature@1.0.6","MIT","https://github.com/visionmedia/node-cookie-signature" 110 | "cookiejar@2.0.1","MIT","https://github.com/bmeck/node-cookiejar" 111 | "core-js@1.2.6","MIT","https://github.com/zloirock/core-js" 112 | "core-util-is@1.0.2","MIT","https://github.com/isaacs/core-util-is" 113 | "create-hash@1.1.2","MIT","https://github.com/crypto-browserify/createHash" 114 | "create-hmac@1.1.4","MIT","https://github.com/crypto-browserify/createHmac" 115 | "create-torrent@3.18.1","MIT","https://github.com/feross/create-torrent" 116 | "cross-spawn@2.0.1","MIT","https://github.com/IndigoUnited/node-cross-spawn" 117 | "cross-spawn-async@2.1.1","MIT","https://github.com/IndigoUnited/node-cross-spawn-async" 118 | "cryptiles@2.0.5","BSD-3-Clause","https://github.com/hapijs/cryptiles" 119 | "cyclist@0.1.1","MIT*","https://github.com/mafintosh/cyclist" 120 | "d@0.1.1","MIT","https://github.com/medikoo/d" 121 | "dashdash@1.10.1","MIT","https://github.com/trentm/node-dashdash" 122 | "debug@0.7.4","MIT","https://github.com/visionmedia/debug" 123 | "debug@2.2.0","MIT","https://github.com/visionmedia/debug" 124 | "debug-log@1.0.0","MIT","https://github.com/sindresorhus/debug-log" 125 | "decamelize@1.1.1","MIT","https://github.com/sindresorhus/decamelize" 126 | "deep-equal@1.0.1","MIT","http://github.com/substack/node-deep-equal" 127 | "deep-is@0.1.3","MIT","http://github.com/thlorenz/deep-is" 128 | "defaults@1.0.3","MIT","https://github.com/tmpvar/defaults" 129 | "deferred-leveldown@0.2.0","MIT","https://github.com/Level/deferred-leveldown" 130 | "define-properties@1.1.2","MIT","https://github.com/ljharb/define-properties" 131 | "defined@0.0.0","MIT","https://github.com/substack/defined" 132 | "defined@1.0.0","MIT","https://github.com/substack/defined" 133 | "defs@1.1.1","MIT","https://github.com/olov/defs" 134 | "deglob@1.0.2","ISC","git+https://github.com/flet/deglob" 135 | "delayed-stream@0.0.5","MIT*","https://github.com/felixge/node-delayed-stream" 136 | "delayed-stream@1.0.0","MIT","https://github.com/felixge/node-delayed-stream" 137 | "depd@1.0.1","MIT","https://github.com/dougwilson/nodejs-depd" 138 | "destroy@1.0.3","MIT","https://github.com/stream-utils/destroy" 139 | "detect-indent@3.0.1","MIT","https://github.com/sindresorhus/detect-indent" 140 | "detective@4.3.1","MIT","https://github.com/substack/node-detective" 141 | "dezalgo@1.0.3","ISC","https://github.com/npm/dezalgo" 142 | "diff@1.4.0","BSD","https://github.com/kpdecker/jsdiff" 143 | "disparity@2.0.0","MIT","https://github.com/millermedeiros/disparity" 144 | "dns.js@1.0.1","MIT","https://github.com/indutny/dns.js" 145 | "doctrine@0.6.4","BSD","http://github.com/Constellation/doctrine" 146 | "dom-walk@0.1.1","MIT","https://github.com/Raynos/dom-walk" 147 | "duplexer2@0.0.2","BSD","https://github.com/deoxxa/duplexer2" 148 | "duplexify@3.4.2","MIT","https://github.com/mafintosh/duplexify" 149 | "ecc-jsbn@0.1.1","MIT","https://github.com/quartzjer/ecc-jsbn" 150 | "ecurve@1.0.2","MIT","https://github.com/cryptocoinjs/ecurve" 151 | "ee-first@1.1.1","MIT","https://github.com/jonathanong/ee-first" 152 | "elistener@1.0.2","ISC","" 153 | "elliptic@3.1.0","MIT","https://github.com/indutny/elliptic" 154 | "elliptic@6.0.2","MIT","https://github.com/indutny/elliptic" 155 | "end-of-stream@1.0.0","MIT","https://github.com/mafintosh/end-of-stream" 156 | "end-of-stream@1.1.0","MIT","https://github.com/mafintosh/end-of-stream" 157 | "errno@0.1.4","MIT","https://github.com/rvagg/node-errno" 158 | "error@7.0.2","MIT","https://github.com/Raynos/error" 159 | "es-abstract@1.4.3","MIT","https://github.com/ljharb/es-abstract" 160 | "es-to-primitive@1.0.0","MIT","https://github.com/ljharb/es-to-primitive" 161 | "es5-ext@0.10.10","MIT","https://github.com/medikoo/es5-ext" 162 | "es6-iterator@2.0.0","MIT","https://github.com/medikoo/es6-iterator" 163 | "es6-map@0.1.3","MIT","https://github.com/medikoo/es6-map" 164 | "es6-set@0.1.3","MIT","https://github.com/medikoo/es6-set" 165 | "es6-symbol@3.0.2","MIT","https://github.com/medikoo/es6-symbol" 166 | "es6-weak-map@2.0.1","MIT","https://github.com/medikoo/es6-weak-map" 167 | "escape-html@1.0.2","MIT","https://github.com/component/escape-html" 168 | "escape-string-regexp@1.0.3","MIT","https://github.com/sindresorhus/escape-string-regexp" 169 | "escope@3.3.0","BSD-2-Clause","git+https://github.com/estools/escope" 170 | "esformatter@0.8.1","MIT","git+https://github.com/millermedeiros/esformatter" 171 | "esformatter-eol-last@1.0.0","ISC","https://github.com/briandipalma/esformatter-eol-last" 172 | "esformatter-ignore@0.1.3","MIT","git+https://github.com/royriojas/esformatter-ignore" 173 | "esformatter-jsx@2.3.11","MIT","git+https://github.com/royriojas/esformatter-jsx" 174 | "esformatter-literal-notation@1.0.1","MIT","git+https://github.com/kewah/esformatter-literal-notation" 175 | "esformatter-quotes@1.0.3","MIT","https://github.com/millermedeiros/esformatter-quotes" 176 | "esformatter-semicolon-first@1.1.0","MIT","https://github.com/millermedeiros/esformatter-semicolon-first" 177 | "esformatter-spaced-lined-comment@2.0.1","ISC","https://github.com/briandipalma/esformatter-spaced-lined-comment" 178 | "eslint@0.24.1","MIT","https://github.com/eslint/eslint" 179 | "eslint-config-standard@3.4.1","MIT","https://github.com/feross/eslint-config-standard" 180 | "eslint-config-standard-react@1.0.1","MIT","https://github.com/feross/eslint-config-standard-react" 181 | "eslint-plugin-react@2.7.1","MIT","git+https://github.com/yannickcr/eslint-plugin-react" 182 | "espree@2.2.5","BSD","http://github.com/eslint/espree" 183 | "esprima@1.0.4","BSD","http://github.com/ariya/esprima" 184 | "esprima@2.7.1","BSD-2-Clause","git+https://github.com/jquery/esprima" 185 | "esprima-fb@15001.1001.0-dev-harmony-fb","BSD","http://github.com/facebook/esprima" 186 | "esrecurse@3.1.1","BSD","http://github.com/estools/esrecurse" 187 | "estraverse@3.1.0","BSD","http://github.com/estools/estraverse" 188 | "estraverse@4.1.1","BSD-2-Clause","https://github.com/estools/estraverse" 189 | "estraverse-fb@1.3.1","MIT","https://github.com/RReverser/estraverse-fb" 190 | "esutils@1.1.6","BSD","http://github.com/Constellation/esutils" 191 | "esutils@2.0.2","BSD","http://github.com/estools/esutils" 192 | "etag@1.7.0","MIT","https://github.com/jshttp/etag" 193 | "event-emitter@0.3.4","MIT","https://github.com/medikoo/event-emitter" 194 | "exit-hook@1.1.1","MIT","https://github.com/sindresorhus/exit-hook" 195 | "express@4.13.3","MIT","https://github.com/strongloop/express" 196 | "extend@1.2.1","MIT*","https://github.com/justmoon/node-extend" 197 | "extend@2.0.1","MIT","https://github.com/justmoon/node-extend" 198 | "extend@3.0.0","MIT","https://github.com/justmoon/node-extend" 199 | "extend.js@0.0.2","MIT*","" 200 | "externr@1.0.0","MIT","https://github.com/rvagg/externr" 201 | "extsprintf@1.0.2","MIT*","https://github.com/davepacheco/node-extsprintf" 202 | "fast-levenshtein@1.0.7","MIT","https://github.com/hiddentao/fast-levenshtein" 203 | "figures@1.4.0","MIT","https://github.com/sindresorhus/figures" 204 | "filestream@4.1.1","MIT","https://github.com/DamonOehlman/filestream" 205 | "finalhandler@0.4.0","MIT","https://github.com/pillarjs/finalhandler" 206 | "find-root@0.1.1","MIT","https://github.com/agilemd/find-root" 207 | "flatten@0.0.1","MIT*","https://github.com/jesusabdullah/node-flatten" 208 | "for-each@0.3.2","MIT","https://github.com/Raynos/for-each" 209 | "for-in@0.1.4","MIT","https://github.com/jonschlinkert/for-in" 210 | "for-own@0.1.3","MIT","https://github.com/jonschlinkert/for-own" 211 | "foreach@2.0.5","MIT","https://github.com/manuelstofer/foreach" 212 | "forever-agent@0.6.1","Apache-2.0","https://github.com/mikeal/forever-agent" 213 | "form-data@0.2.0","MIT","https://github.com/felixge/node-form-data" 214 | "form-data@1.0.0-rc3","MIT","https://github.com/form-data/form-data" 215 | "formidable@1.0.14","MIT*","https://github.com/felixge/node-formidable" 216 | "forwarded@0.1.0","MIT","https://github.com/jshttp/forwarded" 217 | "fresh@0.3.0","MIT","https://github.com/jshttp/fresh" 218 | "fresh-falafel@1.2.0","MIT","https://github.com/substack/node-falafel" 219 | "from2@1.3.0","MIT","https://github.com/hughsk/from2" 220 | "fs-readdir-recursive@0.1.2","MIT","https://github.com/fs-utils/fs-readdir-recursive" 221 | "function-bind@1.0.2","MIT","https://github.com/Raynos/function-bind" 222 | "functional-red-black-tree@1.0.1","MIT","https://github.com/mikolalysenko/functional-red-black-tree" 223 | "generate-function@2.0.0","MIT","https://github.com/mafintosh/generate-function" 224 | "generate-object-property@1.2.0","MIT","https://github.com/mafintosh/generate-object-property" 225 | "get-stdin@4.0.1","MIT","https://github.com/sindresorhus/get-stdin" 226 | "glob@5.0.15","ISC","https://github.com/isaacs/node-glob" 227 | "global@4.3.0","MIT","https://github.com/Raynos/global" 228 | "globals@6.4.1","MIT","https://github.com/sindresorhus/globals" 229 | "globals@8.14.0","MIT","https://github.com/sindresorhus/globals" 230 | "graceful-fs@4.1.2","ISC","https://github.com/isaacs/node-graceful-fs" 231 | "graceful-readlink@1.0.1","MIT","https://github.com/zhiyelee/graceful-readlink" 232 | "har-validator@2.0.3","ISC","https://github.com/ahmadnassri/har-validator" 233 | "has@1.0.1","MIT","https://github.com/tarruda/has" 234 | "has-ansi@2.0.0","MIT","https://github.com/sindresorhus/has-ansi" 235 | "hash.js@1.0.3","MIT","https://github.com/indutny/hash.js" 236 | "hashmap@2.0.4","MIT","https://github.com/flesler/hashmap" 237 | "hat@0.0.3","MIT/X11","http://github.com/substack/node-hat" 238 | "hawk@3.1.2","BSD-3-Clause","https://github.com/hueniverse/hawk" 239 | "hoek@2.16.3","BSD-3-Clause","https://github.com/hapijs/hoek" 240 | "home-or-tmp@1.0.0","MIT","https://github.com/sindresorhus/home-or-tmp" 241 | "http-errors@1.3.1","MIT","https://github.com/jshttp/http-errors" 242 | "http-signature@1.1.0","MIT","https://github.com/joyent/node-http-signature" 243 | "iconv-lite@0.4.13","MIT","https://github.com/ashtuchkin/iconv-lite" 244 | "ignore@2.2.19","MIT","https://github.com/kaelzhang/node-ignore" 245 | "inflight@1.0.4","ISC","https://github.com/isaacs/inflight" 246 | "inherit@2.2.2","MIT","http://github.com/dfilatov/node-inherit" 247 | "inherits@2.0.1","ISC","https://github.com/isaacs/inherits" 248 | "ini@1.3.4","ISC","https://github.com/isaacs/ini" 249 | "inquirer@0.8.5","MIT","https://github.com/SBoudrias/Inquirer.js" 250 | "invert-kv@1.0.0","MIT","https://github.com/sindresorhus/invert-kv" 251 | "ip-regex@1.0.3","MIT","https://github.com/sindresorhus/ip-regex" 252 | "ipaddr.js@1.0.5","MIT","https://github.com/whitequark/ipaddr.js" 253 | "is-absolute@0.1.7","MIT","https://github.com/jonschlinkert/is-absolute" 254 | "is-buffer@1.1.0","MIT","https://github.com/feross/is-buffer" 255 | "is-callable@1.1.1","MIT","https://github.com/ljharb/is-callable" 256 | "is-date-object@1.0.1","MIT","https://github.com/ljharb/is-date-object" 257 | "is-file@1.0.0","MIT","https://github.com/jsdevel/node-is-file" 258 | "is-finite@1.0.1","MIT","https://github.com/sindresorhus/is-finite" 259 | "is-function@1.0.1","MIT","https://github.com/grncdr/js-is-function" 260 | "is-integer@1.0.6","WTFPL","https://github.com/parshap/js-is-integer" 261 | "is-ip@1.0.0","MIT","https://github.com/sindresorhus/is-ip" 262 | "is-my-json-valid@2.12.3","MIT","https://github.com/mafintosh/is-my-json-valid" 263 | "is-property@1.0.2","MIT","https://github.com/mikolalysenko/is-property" 264 | "is-regex@1.0.3","MIT","https://github.com/ljharb/is-regex" 265 | "is-relative@0.1.3","MIT","https://github.com/jonschlinkert/is-relative" 266 | "is-symbol@1.0.1","MIT","https://github.com/ljharb/is-symbol" 267 | "is-typedarray@1.0.0","MIT","https://github.com/hughsk/is-typedarray" 268 | "isarray@0.0.1","MIT","https://github.com/juliangruber/isarray" 269 | "isobject@1.0.2","MIT","https://github.com/jonschlinkert/isobject" 270 | "isstream@0.1.2","MIT","https://github.com/rvagg/isstream" 271 | "jodid25519@1.0.2","MIT","https://github.com/meganz/jodid25519" 272 | "js-beautify@1.5.10","MIT","https://github.com/beautify-web/js-beautify" 273 | "js-tokens@1.0.1","MIT","https://github.com/lydell/js-tokens" 274 | "js-yaml@3.4.6","MIT","git+https://github.com/nodeca/js-yaml" 275 | "jsbn@0.1.0","BSD","https://github.com/andyperlitch/jsbn" 276 | "jsesc@0.5.0","MIT","https://github.com/mathiasbynens/jsesc" 277 | "json-schema@0.2.2","AFLv2.1,BSD","http://github.com/kriszyp/json-schema" 278 | "json-stable-stringify@1.0.0","MIT","https://github.com/substack/json-stable-stringify" 279 | "json-stringify-safe@5.0.1","ISC","https://github.com/isaacs/json-stringify-safe" 280 | "json5@0.4.0","MIT","https://github.com/aseemk/json5" 281 | "jsonify@0.0.0","Public Domain","http://github.com/substack/jsonify" 282 | "jsonpointer@2.0.0","MIT","http://github.com/janl/node-jsonpointer" 283 | "jsprim@1.2.2","MIT","https://github.com/davepacheco/node-jsprim" 284 | "junk@1.0.2","MIT","https://github.com/sindresorhus/junk" 285 | "k-bucket@0.4.4","MIT","https://github.com/tristanls/k-bucket" 286 | "kind-of@2.0.1","MIT","https://github.com/jonschlinkert/kind-of" 287 | "lazy-cache@0.2.7","MIT","git+https://github.com/jonschlinkert/lazy-cache" 288 | "lcid@1.0.0","MIT","https://github.com/sindresorhus/lcid" 289 | "left-pad@0.0.3","BSD","https://github.com/azer/left-pad" 290 | "length-prefixed-stream@1.4.0","MIT","https://github.com/mafintosh/length-prefixed-stream" 291 | "level-errors@1.0.4","MIT","https://github.com/level/errors" 292 | "level-live-stream@1.4.11","MIT","https://github.com/dominictarr/level-live-stream" 293 | "level-post@1.0.4","MIT","https://github.com/dominictarr/level-post" 294 | "level-sublevel@6.3.17","MIT","https://github.com/dominictarr/level-sublevel" 295 | "levelup@0.18.6","MIT","https://github.com/rvagg/node-levelup" 296 | "levelup@0.19.0","MIT","https://github.com/rvagg/node-levelup" 297 | "leven@1.0.2","MIT","https://github.com/sindresorhus/leven" 298 | "levn@0.2.5","MIT","https://github.com/gkz/levn" 299 | "lexicographic-integer@1.1.0","MIT","https://github.com/substack/lexicographic-integer" 300 | "line-numbers@0.2.0","MIT","https://github.com/lydell/line-numbers" 301 | "lodash@3.10.1","MIT","https://github.com/lodash/lodash" 302 | "logbase@3.3.2","ISC","https://github.com/mvayngrib/logbase" 303 | "longest@1.0.1","MIT","https://github.com/jonschlinkert/longest" 304 | "looper@2.0.0","MIT","https://github.com/dominictarr/looper" 305 | "lru-cache@3.2.0","ISC","https://github.com/isaacs/node-lru-cache" 306 | "ltgt@1.0.2","MIT","https://github.com/dominictarr/ltgt" 307 | "ltgt@2.0.0","MIT","https://github.com/dominictarr/ltgt" 308 | "magnet-uri@4.2.3","MIT","https://github.com/feross/magnet-uri" 309 | "map-stream@0.0.6","MIT","https://github.com/dominictarr/map-stream" 310 | "media-typer@0.3.0","MIT","https://github.com/jshttp/media-typer" 311 | "memdown@1.1.0","MIT","git+https://github.com/rvagg/node-memdown" 312 | "merge-descriptors@1.0.0","MIT","https://github.com/component/merge-descriptors" 313 | "methods@1.0.1","MIT","https://github.com/visionmedia/node-methods" 314 | "methods@1.1.1","MIT","https://github.com/jshttp/methods" 315 | "mime@1.3.4","MIT","https://github.com/broofa/node-mime" 316 | "mime-db@1.12.0","MIT","https://github.com/jshttp/mime-db" 317 | "mime-db@1.20.0","MIT","https://github.com/jshttp/mime-db" 318 | "mime-types@2.0.14","MIT","https://github.com/jshttp/mime-types" 319 | "mime-types@2.1.8","MIT","https://github.com/jshttp/mime-types" 320 | "min-document@2.17.0","MIT","https://github.com/Raynos/min-document" 321 | "minimatch@2.0.10","ISC","https://github.com/isaacs/minimatch" 322 | "minimatch@3.0.0","ISC","https://github.com/isaacs/minimatch" 323 | "minimist@0.0.8","MIT","https://github.com/substack/minimist" 324 | "minimist@1.2.0","MIT","https://github.com/substack/minimist" 325 | "mkdirp@0.5.1","MIT","https://github.com/substack/node-mkdirp" 326 | "monotonic-timestamp@0.0.9","MIT","https://github.com/dominictarr/monotonic-timestamp" 327 | "mout@0.11.1","MIT","https://github.com/mout/mout" 328 | "ms@0.7.1","MIT*","https://github.com/guille/ms.js" 329 | "multistream@2.0.2","MIT","https://github.com/feross/multistream" 330 | "mute-stream@0.0.4","BSD","https://github.com/isaacs/mute-stream" 331 | "mutexify@1.1.0","MIT","https://github.com/mafintosh/mutexify" 332 | "negotiator@0.5.3","MIT","https://github.com/jshttp/negotiator" 333 | "nets@3.2.0","ISC","https://github.com/maxogden/nets" 334 | "network-address@1.0.0","MIT","https://github.com/mafintosh/network-address" 335 | "node-uuid@1.4.7","MIT","https://github.com/broofa/node-uuid" 336 | "nopt@3.0.6","ISC","https://github.com/npm/nopt" 337 | "npm-path@1.0.2","MIT","git+https://github.com/timoxley/npm-path" 338 | "npm-run@1.1.1","MIT","https://github.com/timoxley/npm-run" 339 | "number-is-nan@1.0.0","MIT","https://github.com/sindresorhus/number-is-nan" 340 | "oauth-sign@0.8.0","Apache-2.0","https://github.com/mikeal/oauth-sign" 341 | "object-assign@2.1.1","MIT","https://github.com/sindresorhus/object-assign" 342 | "object-inspect@1.0.2","MIT","https://github.com/substack/object-inspect" 343 | "object-keys@1.0.9","MIT","https://github.com/ljharb/object-keys" 344 | "object-path@0.6.0","MIT","https://github.com/mariocasciaro/object-path" 345 | "object.omit@1.1.0","MIT","https://github.com/jonschlinkert/object.omit" 346 | "object.pick@1.1.1","MIT","https://github.com/jonschlinkert/object.pick" 347 | "on-finished@2.3.0","MIT","https://github.com/jshttp/on-finished" 348 | "once@1.1.1","BSD","https://github.com/isaacs/once" 349 | "once@1.3.3","ISC","https://github.com/isaacs/once" 350 | "optionator@0.5.0","MIT","https://github.com/gkz/optionator" 351 | "os-homedir@1.0.1","MIT","https://github.com/sindresorhus/os-homedir" 352 | "os-locale@1.4.0","MIT","https://github.com/sindresorhus/os-locale" 353 | "os-shim@0.1.3","MIT","https://github.com/h2non/node-os-shim" 354 | "os-tmpdir@1.0.1","MIT","https://github.com/sindresorhus/os-tmpdir" 355 | "output-file-sync@1.1.1","MIT","https://github.com/shinnn/output-file-sync" 356 | "parse-headers@2.0.1","MIT","https://github.com/kesla/parse-headers" 357 | "parse-torrent@3.0.1","MIT","https://github.com/feross/parse-torrent" 358 | "parse-torrent-file@2.1.4","MIT","https://github.com/feross/parse-torrent-file" 359 | "parseurl@1.3.0","MIT","https://github.com/expressjs/parseurl" 360 | "path-exists@1.0.0","MIT","https://github.com/sindresorhus/path-exists" 361 | "path-is-absolute@1.0.0","MIT","https://github.com/sindresorhus/path-is-absolute" 362 | "path-to-regexp@0.1.7","MIT","git+https://github.com/component/path-to-regexp" 363 | "piece-length@0.0.0","MIT","https://github.com/michaelrhodes/piece-length" 364 | "pinkie@2.0.1","MIT","https://github.com/floatdrop/pinkie" 365 | "pinkie-promise@2.0.0","MIT","https://github.com/floatdrop/pinkie-promise" 366 | "pkg-config@1.1.0","MIT","git+https://github.com/ahmadnassri/pkg-config" 367 | "pre-commit@1.1.2","MIT","https://github.com/observing/pre-commit" 368 | "prelude-ls@1.1.2","MIT","https://github.com/gkz/prelude-ls" 369 | "private@0.1.6","MIT","https://github.com/benjamn/private" 370 | "process@0.5.2","MIT*","https://github.com/shtylman/node-process" 371 | "process-nextick-args@1.0.6","MIT","https://github.com/calvinmetcalf/process-nextick-args" 372 | "proto-list@1.2.4","ISC","git+https://github.com/isaacs/proto-list" 373 | "protochain@1.0.3","ISC","git+https://github.com/timoxley/protochain" 374 | "proxy-addr@1.0.10","MIT","https://github.com/jshttp/proxy-addr" 375 | "prr@0.0.0","MIT","https://github.com/rvagg/prr" 376 | "pseudomap@1.0.1","ISC","git+https://github.com/isaacs/pseudomap" 377 | "pull-cat@1.1.8","MIT","https://github.com/dominictarr/pull-cat" 378 | "pull-core@1.0.0","MIT","https://github.com/dominictarr/pull-core" 379 | "pull-core@1.1.0","MIT","https://github.com/dominictarr/pull-core" 380 | "pull-level@1.4.1","MIT","https://github.com/dominictarr/pull-level" 381 | "pull-pushable@1.1.4","MIT","https://github.com/dominictarr/pull-pushable" 382 | "pull-stream@2.18.3","MIT","https://github.com/dominictarr/pull-stream" 383 | "pull-stream@2.21.0","MIT","https://github.com/dominictarr/pull-stream" 384 | "pull-stream@2.28.4","MIT","https://github.com/dominictarr/pull-stream" 385 | "pull-stream-to-stream@1.2.6","MIT","https://github.com/dominictarr/pull-stream-to-stream" 386 | "pull-window@2.1.3","MIT","https://github.com/dominictarr/pull-window" 387 | "pump@1.0.1","MIT","https://github.com/mafintosh/pump" 388 | "q@1.4.1","MIT","https://github.com/kriskowal/q" 389 | "qs@2.3.3","BSD","https://github.com/hapijs/qs" 390 | "qs@4.0.0","BSD-3-Clause","https://github.com/hapijs/qs" 391 | "qs@5.2.0","BSD-3-Clause","https://github.com/hapijs/qs" 392 | "randombytes@2.0.1","MIT","https://github.com/crypto-browserify/randombytes" 393 | "range-parser@1.0.3","MIT","https://github.com/jshttp/range-parser" 394 | "re-emitter@1.1.1","MIT","https://github.com/feross/re-emitter" 395 | "readable-stream@1.0.27-1","MIT","https://github.com/isaacs/readable-stream" 396 | "readable-stream@1.0.33","MIT","https://github.com/isaacs/readable-stream" 397 | "readable-stream@1.0.33-1","MIT","https://github.com/isaacs/readable-stream" 398 | "readable-stream@1.1.13","MIT","https://github.com/isaacs/readable-stream" 399 | "readable-stream@2.0.4","MIT","https://github.com/nodejs/readable-stream" 400 | "readline2@0.1.1","MIT","https://github.com/SBoudrias/readline2" 401 | "recast@0.10.33","MIT","https://github.com/benjamn/recast" 402 | "recast@0.10.39","MIT","https://github.com/benjamn/recast" 403 | "reduce-component@1.0.1","Apache, Version 2.0","https://github.com/redventures/reduce" 404 | "regenerate@1.2.1","MIT","https://github.com/mathiasbynens/regenerate" 405 | "regenerator@0.8.40","BSD","https://github.com/facebook/regenerator" 406 | "regexpu@1.3.0","MIT","https://github.com/mathiasbynens/regexpu" 407 | "regjsgen@0.2.0","MIT","https://github.com/d10/regjsgen" 408 | "regjsparser@0.1.5","BSD","https://github.com/jviereck/regjsparser" 409 | "repeat-string@1.5.2","MIT","https://github.com/jonschlinkert/repeat-string" 410 | "repeating@1.1.3","MIT","https://github.com/sindresorhus/repeating" 411 | "request@2.67.0","Apache-2.0","https://github.com/request/request" 412 | "resolve@1.1.6","MIT","https://github.com/substack/node-resolve" 413 | "resumer@0.0.0","MIT","https://github.com/substack/resumer" 414 | "right-align@0.1.3","MIT","https://github.com/jonschlinkert/right-align" 415 | "rimraf@2.4.4","ISC","https://github.com/isaacs/rimraf" 416 | "ripemd160@1.0.1","BSD-3-Clause","https://github.com/crypto-browserify/ripemd160" 417 | "rocambole@0.3.6","MIT","https://github.com/millermedeiros/rocambole" 418 | "rocambole@0.7.0","MIT","git+https://github.com/millermedeiros/rocambole" 419 | "rocambole-indent@2.0.4","MIT","https://github.com/millermedeiros/rocambole-indent" 420 | "rocambole-linebreak@1.0.1","MIT","https://github.com/millermedeiros/rocambole-linebreak" 421 | "rocambole-node@1.0.0","MIT","https://github.com/millermedeiros/rocambole-node" 422 | "rocambole-token@1.2.1","MIT","https://github.com/millermedeiros/rocambole-token" 423 | "rocambole-whitespace@1.0.0","MIT","https://github.com/millermedeiros/rocambole-whitespace" 424 | "run-parallel@1.1.4","MIT","https://github.com/feross/run-parallel" 425 | "rusha@0.8.3","MIT","https://github.com/srijs/rusha" 426 | "rx@2.5.3","Apache-2.0","https://github.com/Reactive-Extensions/RxJS" 427 | "safecb@0.0.1","MIT","https://github.com/mvayngrib/safecb" 428 | "semver@2.3.2","BSD","https://github.com/isaacs/node-semver" 429 | "semver@4.3.6","ISC","https://github.com/npm/node-semver" 430 | "send@0.13.0","MIT","https://github.com/pillarjs/send" 431 | "serializerr@1.0.2","ISC","git+https://github.com/timoxley/serializerr" 432 | "serve-static@1.10.0","MIT","https://github.com/expressjs/serve-static" 433 | "sha.js@2.4.4","MIT","https://github.com/crypto-browserify/sha.js" 434 | "shebang-regex@1.0.0","MIT","https://github.com/sindresorhus/shebang-regex" 435 | "simple-fmt@0.1.0","MIT","https://github.com/olov/simple-fmt" 436 | "simple-get@1.4.3","MIT","https://github.com/feross/simple-get" 437 | "simple-is@0.2.0","MIT","https://github.com/olov/simple-is" 438 | "simple-sha1@2.0.7","MIT","https://github.com/michaelrhodes/simple-sha1" 439 | "slash@1.0.0","MIT","https://github.com/sindresorhus/slash" 440 | "sntp@1.0.9","BSD","https://github.com/hueniverse/sntp" 441 | "sock-plex@1.0.2","MIT","git+https://github.com/mvayngrib/sock-plex" 442 | "sort-by@1.1.1","MIT","https://github.com/kvnneff/sort-by" 443 | "source-map@0.1.32","BSD","http://github.com/mozilla/source-map" 444 | "source-map@0.5.3","BSD-3-Clause","http://github.com/mozilla/source-map" 445 | "source-map-support@0.2.10","MIT","https://github.com/evanw/node-source-map-support" 446 | "spawn-sync@1.0.13","MIT","https://github.com/ForbesLindesay/spawn-sync" 447 | "sprintf-js@1.0.3","BSD-3-Clause","git+https://github.com/alexei/sprintf.js" 448 | "sshpk@1.7.1","MIT","git+https://github.com/arekinath/node-sshpk" 449 | "stable@0.1.5","MIT","https://github.com/Two-Screen/stable" 450 | "standard@4.5.4","MIT","https://github.com/feross/standard" 451 | "standard-format@1.6.10","BSD-2-Clause","git+https://github.com/maxogden/standard-format" 452 | "statuses@1.2.1","MIT","https://github.com/jshttp/statuses" 453 | "stdin@0.0.1","MIT*","" 454 | "stream-collector@1.0.1","MIT","https://github.com/mafintosh/stream-collector" 455 | "stream-combiner2@1.0.2","MIT","https://github.com/substack/stream-combiner2" 456 | "stream-to-pull-stream@1.6.6","MIT","https://github.com/dominictarr/stream-to-pull-stream" 457 | "string-range@1.2.2","MIT","https://github.com/dominictarr/string-range" 458 | "string-template@0.2.1","MIT","https://github.com/Matt-Esch/string-template" 459 | "string.prototype.endswith@0.2.0","MIT","https://github.com/mathiasbynens/String.prototype.endsWith" 460 | "string.prototype.trim@1.1.1","MIT","https://github.com/es-shims/String.prototype.trim" 461 | "string2compact@1.2.2","MIT","https://github.com/feross/string2compact" 462 | "string_decoder@0.10.31","MIT","https://github.com/rvagg/string_decoder" 463 | "stringmap@0.2.2","MIT","https://github.com/olov/stringmap" 464 | "stringset@0.2.1","MIT","https://github.com/olov/stringset" 465 | "stringstream@0.0.5","MIT","https://github.com/mhart/StringStream" 466 | "strip-ansi@2.0.1","MIT","https://github.com/sindresorhus/strip-ansi" 467 | "strip-ansi@3.0.0","MIT","https://github.com/sindresorhus/strip-ansi" 468 | "strip-json-comments@0.1.3","MIT","https://github.com/sindresorhus/strip-json-comments" 469 | "strip-json-comments@1.0.4","MIT","https://github.com/sindresorhus/strip-json-comments" 470 | "superagent@1.5.0","MIT","https://github.com/visionmedia/superagent" 471 | "supports-color@1.3.1","MIT","https://github.com/sindresorhus/supports-color" 472 | "supports-color@2.0.0","MIT","https://github.com/chalk/supports-color" 473 | "sync-exec@0.5.0","GNU GPLv2","https://github.com/gvarsanyi/sync-exec" 474 | "tape@4.2.2","MIT","https://github.com/substack/tape" 475 | "tape-extra@1.0.0","ISC","" 476 | "text-table@0.2.0","MIT","https://github.com/substack/text-table" 477 | "thirty-two@0.0.2","MIT*","https://github.com/chrisumbel/thirty-two" 478 | "throttleme@1.0.3","ISC","https://github.com/mvayngrib/throttleme" 479 | "through@2.3.8","MIT","https://github.com/dominictarr/through" 480 | "through2@0.5.1","MIT","https://github.com/rvagg/through2" 481 | "through2@0.6.5","MIT","https://github.com/rvagg/through2" 482 | "thunky@0.1.0","MIT*","https://github.com/mafintosh/thunky" 483 | "tim@2.0.0","ISC","https://github.com/tradle/tim" 484 | "time-method@2.0.0","ISC","https://github.com/mvayngrib/time-method" 485 | "to-fast-properties@1.0.1","MIT","https://github.com/sindresorhus/to-fast-properties" 486 | "to-utf8@0.0.1","MIT","https://github.com/chrisdickinson/to-utf8" 487 | "tough-cookie@2.2.1","BSD-3-Clause","https://github.com/SalesforceEng/tough-cookie" 488 | "trim@0.0.1","MIT*","" 489 | "trim-right@1.0.1","MIT","https://github.com/sindresorhus/trim-right" 490 | "try-resolve@1.0.1","MIT","https://github.com/sebmck/try-resolve" 491 | "tryor@0.1.2","MIT","https://github.com/olov/tryor" 492 | "tunnel-agent@0.4.2","Apache-2.0","git+https://github.com/mikeal/tunnel-agent" 493 | "tweetnacl@0.13.2","CC0-1.0","https://github.com/dchest/tweetnacl-js" 494 | "type-check@0.3.1","MIT","https://github.com/gkz/type-check" 495 | "type-is@1.6.10","MIT","https://github.com/jshttp/type-is" 496 | "typedarray@0.0.6","MIT","https://github.com/substack/typedarray" 497 | "typedarray-to-buffer@3.0.4","MIT","https://github.com/feross/typedarray-to-buffer" 498 | "typeforce@1.6.1","MIT","https://github.com/dcousens/typeforce" 499 | "typewiselite@1.0.0","MIT","https://github.com/dominictarr/typewiselite" 500 | "uniq@1.0.1","MIT","https://github.com/mikolalysenko/uniq" 501 | "unpipe@1.0.0","MIT","https://github.com/stream-utils/unpipe" 502 | "unzip-response@1.0.0","MIT","https://github.com/sindresorhus/unzip-response" 503 | "user-home@1.1.1","MIT","https://github.com/sindresorhus/user-home" 504 | "user-home@2.0.0","MIT","https://github.com/sindresorhus/user-home" 505 | "util-deprecate@1.0.2","MIT","https://github.com/TooTallNate/util-deprecate" 506 | "utils-merge@1.0.0","MIT","https://github.com/jaredhanson/utils-merge" 507 | "varint@4.0.0","MIT","https://github.com/chrisdickinson/varint" 508 | "vary@1.0.1","MIT","https://github.com/jshttp/vary" 509 | "verror@1.3.6","MIT*","https://github.com/davepacheco/node-verror" 510 | "which@1.1.2","ISC","https://github.com/isaacs/node-which" 511 | "which@1.2.0","ISC","https://github.com/isaacs/node-which" 512 | "window-size@0.1.4","MIT","https://github.com/jonschlinkert/window-size" 513 | "wordwrap@0.0.2","MIT/X11","https://github.com/substack/node-wordwrap" 514 | "wordwrap@0.0.3","MIT","https://github.com/substack/node-wordwrap" 515 | "wrappy@1.0.1","ISC","https://github.com/npm/wrappy" 516 | "xhr@2.2.0","MIT","https://github.com/Raynos/xhr" 517 | "xml-escape@1.0.0","MIT License","https://github.com/miketheprogrammer/xml-escape" 518 | "xtend@3.0.0","MIT","https://github.com/Raynos/xtend" 519 | "xtend@4.0.1","MIT","https://github.com/Raynos/xtend" 520 | "y18n@3.2.0","ISC","https://github.com/bcoe/y18n" 521 | "yargs@3.27.0","MIT","http://github.com/bcoe/yargs" 522 | "zlorp@2.0.1","MIT","https://github.com/tradle/zlorp" 523 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "tim", 3 | "version": "6.5.2", 4 | "description": "Tradle's P2P OTR-based chat with plaintext and structured messages, and the ability to externalize messages onto a blockchain (currently bitcoin's)", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "node test && MULTIPLEX=1 node test", 8 | "style": "standard $(git ls-files '**.js')" 9 | }, 10 | "pre-commit": [ 11 | "test" 12 | ], 13 | "keywords": [ 14 | "tradle", 15 | "bitcoin", 16 | "blockchain", 17 | "p2p", 18 | "webtorrent", 19 | "bittorrent", 20 | "otr", 21 | "messaging", 22 | "chat" 23 | ], 24 | "repository": { 25 | "type": "git", 26 | "url": "https://github.com/tradle/tim.git" 27 | }, 28 | "author": "Mark Vayngrib (http://github.com/mvayngrib)", 29 | "license": "GPLv3", 30 | "dependencies": { 31 | "@tradle/bitcoinjs-lib": "^1.5.7", 32 | "@tradle/bitjoe-js": "^1.0.3", 33 | "@tradle/bittorrent-dht": "^3.2.1", 34 | "@tradle/chained-obj": "^2.1.0", 35 | "@tradle/chainloader": "^2.2.1", 36 | "@tradle/constants": "^1.1.3", 37 | "@tradle/identity": "^1.2.2", 38 | "@tradle/kiki": "^1.1.13", 39 | "@tradle/multiplex-utp": "^1.0.1", 40 | "@tradle/permission": "^1.0.4", 41 | "@tradle/simple-wallet": "^1.1.1", 42 | "@tradle/transport-p2p": "^1.0.0", 43 | "@tradle/tx-data": "^1.0.3", 44 | "@tradle/utils": "^1.3.0", 45 | "@tradle/verifier": "^1.1.1", 46 | "array-find": "^1.0.0", 47 | "debug": "^2.2.0", 48 | "deep-equal": "^1.0.1", 49 | "elliptic": "^6.0.2", 50 | "error": "^7.0.2", 51 | "level-errors": "^1.0.3", 52 | "level-live-stream": "^1.4.9", 53 | "levelup": "^0.18.0", 54 | "lexicographic-integer": "^1.1.0", 55 | "logbase": "^4.0.0", 56 | "lru-cache": "^3.2.0", 57 | "map-stream": "0.0.6", 58 | "monotonic-timestamp": "0.0.9", 59 | "nets": "^3.2.0", 60 | "object.omit": "^1.1.0", 61 | "object.pick": "^1.1.1", 62 | "pump": "^1.0.0", 63 | "q": "^1.4.1", 64 | "re-emitter": "^1.1.1", 65 | "readable-stream": "~1.0.33", 66 | "safecb": "0.0.1", 67 | "stream-collector": "^1.0.1", 68 | "stream-combiner2": "~1.0.2", 69 | "typeforce": "^1.4.0", 70 | "uniq": "^1.0.1", 71 | "xtend": "^4.0.0", 72 | "zlorp": "^2.0.1" 73 | }, 74 | "devDependencies": { 75 | "@tradle/cb-blockr": "^3.1.1", 76 | "@tradle/test-helpers": "^1.2.0", 77 | "@tradle/transport-http": "^1.0.0", 78 | "bluebird-q": "^1.0.3", 79 | "clone": "^1.0.2", 80 | "express": "^4.13.3", 81 | "leveldown": "^1.4.4", 82 | "memdown": "^1.0.0", 83 | "minimist": "^1.2.0", 84 | "mockery": "^1.4.0", 85 | "pre-commit": "^1.0.10", 86 | "random-name": "^0.1.1", 87 | "rimraf": "^2.4.1", 88 | "standard": "^4.5.2", 89 | "tape": "^4.0.0", 90 | "tape-extra": "^1.0.0", 91 | "time-method": "^2.0.0" 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /test/client.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | var mockery = require('mockery') 4 | mockery.enable({ 5 | warnOnReplace: false, 6 | warnOnUnregistered: false 7 | }) 8 | 9 | mockery.registerSubstitute('q', 'bluebird-q') 10 | 11 | var fs = require('fs') 12 | var path = require('path') 13 | var test = require('tape') 14 | var find = require('array-find') 15 | var typeforce = require('typeforce') 16 | var extend = require('xtend') 17 | var rimraf = require('rimraf') 18 | var clone = require('clone') 19 | var Q = require('q') 20 | var express = require('express') 21 | var leveldown = require('memdown') 22 | var argv = require('minimist')(process.argv.slice(2), { 23 | alias: { 24 | g: 'gen', 25 | n: 'number', 26 | s: 'sign', 27 | c: 'cache-path' 28 | }, 29 | boolean: ['gen'] 30 | }) 31 | 32 | var numUsers = Number(argv.number) 33 | if (!numUsers) { 34 | console.log('-n value must be positive') 35 | process.exit(1) 36 | } 37 | 38 | var cachePath = argv['cache-path'] 39 | if (!cachePath) { 40 | throw new Error('expected "cache-path"') 41 | } 42 | 43 | cachePath = path.resolve(cachePath) 44 | 45 | var bitcoin = require('@tradle/bitcoinjs-lib') 46 | var helpers = require('@tradle/test-helpers') 47 | var constants = require('@tradle/constants') 48 | var utils = require('../lib/utils') 49 | var tradleUtils = require('@tradle/utils') 50 | var ROOT_HASH = constants.ROOT_HASH 51 | var Identity = require('@tradle/identity').Identity 52 | var FakeKeeper = helpers.fakeKeeper 53 | var fakeWallet = helpers.fakeWallet 54 | var Transport = require('@tradle/transport-http') 55 | var Tim = require('../') 56 | Tim.enableOptimizations() 57 | 58 | var NONCE = 0 59 | var BASE_PORT = 22222 60 | var networkName = 'testnet' 61 | var users = require('./users') 62 | var ONE 63 | var MANY 64 | var STORAGE_PATH = './storage' 65 | var sharedKeeper = FakeKeeper.empty() 66 | var DAY_MILLIS = 24 * 60 * 1000 * 1000 67 | Tim.CATCH_UP_INTERVAL = DAY_MILLIS 68 | var commonOpts = { 69 | syncInterval: DAY_MILLIS, 70 | chainThrottle: DAY_MILLIS, 71 | unchainThrottle: DAY_MILLIS, 72 | sendThrottle: DAY_MILLIS, 73 | networkName: networkName, 74 | leveldown: leveldown 75 | } 76 | 77 | var serverInfo = users.shift() 78 | var serverHash = serverInfo.rootHash 79 | 80 | run() 81 | 82 | function printStats (timer) { 83 | var stats = timer.getStats() 84 | // .filter(function (s) { 85 | // return s.time > 200000000 // 200 ms 86 | // }) 87 | 88 | stats.forEach(function (s) { 89 | s.time /= 1e6 90 | s.timePerInvocation /= 1e6 91 | }) 92 | 93 | console.log(stats) 94 | timer.reset() 95 | } 96 | 97 | function clearStorage () { 98 | rimraf.sync(path.join(STORAGE_PATH, '*')) 99 | } 100 | 101 | function run () { 102 | // TODO: skip initializing tims 103 | var identities = users.slice(0, numUsers) 104 | if (argv.gen) { 105 | genMessages() 106 | } else { 107 | sendMessages() 108 | } 109 | 110 | function genMessages () { 111 | if (identities.length < numUsers) { 112 | throw new Error('not enough users') 113 | } 114 | 115 | var CACHE = {} 116 | console.log('generating', numUsers, 'messages') 117 | var batches = [] 118 | var batchSize = 25 119 | for (var i = 0; i < numUsers; i += batchSize) { 120 | batches.push(identities.slice(i, i + batchSize)) 121 | } 122 | 123 | return batches.reduce(function (prev, batch) { 124 | return prev.then(function () { 125 | return Q.all(batch.map(sendAndCache)) 126 | }) 127 | }, Q()) 128 | .done(function () { 129 | fs.writeFileSync(cachePath, JSON.stringify(CACHE)) 130 | process.exit(0) 131 | }) 132 | 133 | function sendAndCache (userInfo, i) { 134 | var defer = Q.defer() 135 | var wallet = walletFor(userInfo.priv, null, 'messaging') 136 | var pub = userInfo.pub 137 | var user = new Tim(extend(commonOpts, { 138 | keys: userInfo.priv, 139 | identity: Identity.fromJSON(pub), 140 | pathPrefix: getPathPrefix(pub.name.firstName), 141 | wallet: wallet, 142 | blockchain: wallet.blockchain, 143 | keeper: keeperWithFallback(sharedKeeper), 144 | _send: function (rh, msg) { 145 | CACHE[user.myRootHash()] = msg.toString() 146 | // pretend we sent 147 | // we're only generating messages 148 | // but the caller expects to get a promise back 149 | defer.resolve() 150 | return defer.promise 151 | } 152 | })) 153 | 154 | user.ready() 155 | .then(function () { 156 | return user.addContactIdentity(serverInfo.pub) 157 | }) 158 | .then(function () { 159 | var msg = { 160 | _t: 'tradle.SimpleMessage', 161 | _z: '' + i, 162 | hey: 'ho' 163 | } 164 | 165 | return argv.sign 166 | ? user.sign(msg) 167 | : msg 168 | }) 169 | .then(function (signed) { 170 | return user.send({ 171 | msg: signed, 172 | to: [{ _r: serverHash }], 173 | deliver: true 174 | }) 175 | }) 176 | 177 | return defer.promise 178 | } 179 | } 180 | 181 | function sendMessages () { 182 | var CACHE = fs.readFileSync(cachePath) 183 | CACHE = JSON.parse(CACHE) 184 | for (var key in CACHE) { 185 | CACHE[key] = new Buffer(CACHE[key]) 186 | } 187 | 188 | var times = identities.map(function (i) {}) // pre-fill with undefined 189 | var togo = identities.length 190 | identities.forEach(function (userInfo, i) { 191 | var cached = CACHE[userInfo.rootHash] 192 | var httpClient = new Transport.HttpClient({ rootHash: userInfo.rootHash }) 193 | httpClient.addRecipient(serverHash, 'http://127.0.0.1:' + BASE_PORT + '/' + serverHash) 194 | 195 | var name = userInfo.pub.name.formatted 196 | var start = process.hrtime() 197 | httpClient.send(serverHash, cached, serverInfo).done() 198 | httpClient.once('message', function () { 199 | var time = process.hrtime(start) 200 | times[i] = time[0] * 1e3 + time[1] / 1e6 | 0 201 | if (--togo === 0) { 202 | printTotals(times) 203 | } 204 | }) 205 | }) 206 | } 207 | 208 | function printTotals (times) { 209 | var sum = times.reduce(function (a, b) { return a + b }) 210 | var avg = sum / times.length | 0 211 | var min = Math.min.apply(Math, times) 212 | var max = Math.max.apply(Math, times) 213 | console.log('avg roundtrip time', avg) 214 | console.log('min roundtrip time', min) 215 | console.log('max roundtrip time', max) 216 | } 217 | } 218 | 219 | function walletFor (keys, blockchain, purpose) { 220 | var unspents = [] 221 | for (var i = 0; i < 20; i++) { 222 | unspents.push(100000) 223 | } 224 | 225 | return fakeWallet({ 226 | blockchain: blockchain, 227 | unspents: unspents, 228 | priv: find(keys, function (k) { 229 | return k.type === 'bitcoin' && 230 | k.networkName === networkName && 231 | k.purpose === purpose 232 | }).priv 233 | }) 234 | } 235 | 236 | function randomMessage () { 237 | return { 238 | _t: 'tradle.SimpleMessage', 239 | _z: '' + NONCE++, 240 | message: 'something random: ' + Math.random() 241 | } 242 | } 243 | 244 | function getPathPrefix (name) { 245 | return path.join(STORAGE_PATH, name.replace(/\s/g, '')) 246 | } 247 | 248 | function keeperWithFallback (fallbackKeeper) { 249 | var k = FakeKeeper.empty() 250 | var getOne = k.getOne 251 | k.getOne = function (key) { 252 | return getOne.apply(this, arguments) 253 | .catch(function (err) { 254 | return fallbackKeeper.getOne(key) 255 | }) 256 | } 257 | 258 | k.push = function (opts) { 259 | typeforce({ 260 | key: 'String', 261 | value: 'Buffer' 262 | }, opts) 263 | 264 | return fallbackKeeper.put(opts.key, opts.value) 265 | } 266 | 267 | return k 268 | } 269 | -------------------------------------------------------------------------------- /test/entries.js: -------------------------------------------------------------------------------- 1 | 2 | var test = require('tape') 3 | var Entry = require('logbase').Entry 4 | var utils = require('../lib/utils') 5 | 6 | test('merge entries - simple', function (t) { 7 | var a = new Entry({ 8 | a: 1, 9 | b: 2 10 | }) 11 | 12 | var b = new Entry({ 13 | a: 1, 14 | c: 3 15 | }) 16 | 17 | var merged = utils.updateEntry(a, b) 18 | t.equal(merged.get('a'), 1) 19 | t.equal(merged.get('b'), 2) 20 | t.equal(merged.get('c'), 3) 21 | t.end() 22 | }) 23 | 24 | test('entry or json', function (t) { 25 | var a = new Entry({ 26 | a: 1, 27 | b: 2 28 | }) 29 | 30 | var b = new Entry({ 31 | a: 1, 32 | c: 3 33 | }) 34 | 35 | var ab1 = utils.updateEntry(a, b) 36 | var ab2 = utils.updateEntry(a.toJSON(), b) 37 | var ab3 = utils.updateEntry(a, b.toJSON()) 38 | var ab4 = utils.updateEntry(a.toJSON(), b.toJSON()) 39 | 40 | t.deepEqual(ab1, ab2) 41 | t.deepEqual(ab3, ab4) 42 | t.deepEqual(ab1, ab4) 43 | t.end() 44 | }) 45 | 46 | test('merge entries - don\'t override timestamp', function (t) { 47 | var a = new Entry({ 48 | timestamp: 2 49 | }) 50 | 51 | var b = new Entry({ 52 | timestamp: 1 53 | }) 54 | 55 | var merged = utils.updateEntry(a, b) 56 | t.equal(merged.get('timestamp'), 2) 57 | merged = utils.updateEntry(b, a) 58 | t.equal(merged.get('timestamp'), 1) 59 | t.end() 60 | }) 61 | 62 | test('merge entries - merge errors', function (t) { 63 | var a = new Entry({ 64 | errors: { 65 | chain: [new Error('good'), new Error('bad')] 66 | } 67 | }) 68 | 69 | var b = new Entry({ 70 | errors: { 71 | chain: [new Error('ugly')], 72 | send: [new Error('weird')] 73 | } 74 | }) 75 | 76 | var merged = utils.updateEntry(a, b).toJSON() 77 | t.deepEqual(merged.errors.chain.map(function (e) { 78 | return e.message 79 | }), ['good', 'bad', 'ugly']) 80 | 81 | t.equal(merged.errors.send[0].message, 'weird') 82 | t.end() 83 | }) 84 | -------------------------------------------------------------------------------- /test/fixtures/bill-priv.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "fingerprint": "mvDNdZFbCCmnAPCBmLY91LnfKWoMH39Q2c", 4 | "networkName": "testnet", 5 | "priv": "cVC5qBv6js7ZZeizm7kz7VV25vU7Xpt7su7r5p2zrdj3WwYTQ41n", 6 | "purpose": "payment", 7 | "type": "bitcoin", 8 | "value": "03a45ede4be12a812e6e2ef1650ecbd8900152b1c6e3fe47f427ee5d9323759fe3" 9 | }, 10 | { 11 | "fingerprint": "mxFoKKA7R8CbjZk1ybaXwgrF8c8QnvnkdC", 12 | "networkName": "testnet", 13 | "priv": "cS8b81LCJyKV11Q8SJ3SFFSnww5fUbgwuUiE2FgJdmxiciESwZC3", 14 | "purpose": "messaging", 15 | "type": "bitcoin", 16 | "value": "03beaabf87e4a30640d4e05f957bf06c92c9f53a42697af7ac377d8813e3ace599" 17 | }, 18 | { 19 | "curve": "secp256k1", 20 | "fingerprint": "68893b2b4fd4da9b599642d808311a1b2283a9d0c69f34fed188b03f8dbad5ff", 21 | "priv": "ee223dc85cfb0b895701384c3788c4482cc42bce9b8c5d5be8ec353edd406787", 22 | "purpose": "sign", 23 | "type": "ec", 24 | "value": "03c1a15c30b0fa726d1c43e8277ecb0542fb8a9eff2163a4c457c40cdbe371be14" 25 | }, 26 | { 27 | "curve": "secp256k1", 28 | "fingerprint": "412a79cdcbe92012b658a9080603d7fa6a26aff0f643ab8d9a81e0d53183cda5", 29 | "priv": "032295a6a3aa185c107bfc67ff414cf968ba98f7dec48ff3bb26b19208762f1a", 30 | "purpose": "update", 31 | "type": "ec", 32 | "value": "030c6815bfa049a73ad732e352c172f10c2bc4cb702c4bd846fd0cd408a4589cd8" 33 | }, 34 | { 35 | "fingerprint": "ef30488f7afb43729e942b48582cc3e6a0d2b612", 36 | "priv": "AAAAAACAlQebM8J5aOgjcA3hy3WZrnpEeuBCgD6RlyTqYmQ9vfYfITos7znEPQX8ChPNgqfg1vtcvnb+bmyA3DPEbS5Okr4ZuCmSF+Z+z6sIpL/7IKwfd3wcxvLPD8zO71zd4zz8SayxzBvORjV6eZZOIgmF51DMNBz+21g9T8cOeTeShiUAAAAUjfAeevfP1vzNrcOmJjrAP6y6y9UAAACAjvdtJFGfdKhoviqN2i2v29Muifh1DtuLYXwlCOFllnCb0lbpyXaxCOFkCsBfwIsZF1UnfLXQuUe6d6oKaHekxJZjrgsE1xN7zu/oMedaFzJmPmjQ8qulljDWt3AyiCvfBRsnX9zw7AoQ7b2nwCWC+9I3NziAa6iooE4WRJX9MVUAAACAdiJYBGhyP4sXgOxtDSZ8qQM9s8ERlGIhDv+UxrCqU8EdtJwJ9TjGjqK7N+kPgKXyvFBSmZBneYCIPnYxgOU8/BMdkRWHXwWCYT2KfjeDshGi29wK2LFJHTUIJerESUpqtQC4gWJ3iB659PQN4wHnEFagvbPlvogAQ3EARgN/ndEAAAAUgD7v/H+xiGwmJc4M/bhqaU+AwfM=", 37 | "purpose": "sign", 38 | "type": "dsa", 39 | "value": "AAAAAACAlQebM8J5aOgjcA3hy3WZrnpEeuBCgD6RlyTqYmQ9vfYfITos7znEPQX8ChPNgqfg1vtcvnb+bmyA3DPEbS5Okr4ZuCmSF+Z+z6sIpL/7IKwfd3wcxvLPD8zO71zd4zz8SayxzBvORjV6eZZOIgmF51DMNBz+21g9T8cOeTeShiUAAAAUjfAeevfP1vzNrcOmJjrAP6y6y9UAAACAjvdtJFGfdKhoviqN2i2v29Muifh1DtuLYXwlCOFllnCb0lbpyXaxCOFkCsBfwIsZF1UnfLXQuUe6d6oKaHekxJZjrgsE1xN7zu/oMedaFzJmPmjQ8qulljDWt3AyiCvfBRsnX9zw7AoQ7b2nwCWC+9I3NziAa6iooE4WRJX9MVUAAACAdiJYBGhyP4sXgOxtDSZ8qQM9s8ERlGIhDv+UxrCqU8EdtJwJ9TjGjqK7N+kPgKXyvFBSmZBneYCIPnYxgOU8/BMdkRWHXwWCYT2KfjeDshGi29wK2LFJHTUIJerESUpqtQC4gWJ3iB659PQN4wHnEFagvbPlvogAQ3EARgN/ndE=" 40 | } 41 | ] -------------------------------------------------------------------------------- /test/fixtures/bill-pub.json: -------------------------------------------------------------------------------- 1 | { 2 | "_t": "tradle.Identity", 3 | "_z": "1", 4 | "contact": [ 5 | { 6 | "identifier": "somebody", 7 | "type": "skype" 8 | } 9 | ], 10 | "location": { 11 | "city": "San Dimas", 12 | "country": "USA", 13 | "formatted": "666 Wyld Stallyns Dr, San Dimas, California", 14 | "postalCode": 666, 15 | "region": "California", 16 | "street": "666 Wyld Stallyns Dr" 17 | }, 18 | "name": { 19 | "firstName": "Bill", 20 | "formatted": "Bill S. Preston", 21 | "lastName": "Preston", 22 | "middleName": "S" 23 | }, 24 | "photos": [ 25 | { 26 | "type": "headshot", 27 | "url": "http://www.celebritynooz.com/images2/alexwinter-then.jpg" 28 | } 29 | ], 30 | "pubkeys": [ 31 | { 32 | "fingerprint": "mvDNdZFbCCmnAPCBmLY91LnfKWoMH39Q2c", 33 | "networkName": "testnet", 34 | "purpose": "payment", 35 | "type": "bitcoin", 36 | "value": "03a45ede4be12a812e6e2ef1650ecbd8900152b1c6e3fe47f427ee5d9323759fe3" 37 | }, 38 | { 39 | "fingerprint": "mxFoKKA7R8CbjZk1ybaXwgrF8c8QnvnkdC", 40 | "networkName": "testnet", 41 | "purpose": "messaging", 42 | "type": "bitcoin", 43 | "value": "03beaabf87e4a30640d4e05f957bf06c92c9f53a42697af7ac377d8813e3ace599" 44 | }, 45 | { 46 | "curve": "secp256k1", 47 | "fingerprint": "68893b2b4fd4da9b599642d808311a1b2283a9d0c69f34fed188b03f8dbad5ff", 48 | "purpose": "sign", 49 | "type": "ec", 50 | "value": "03c1a15c30b0fa726d1c43e8277ecb0542fb8a9eff2163a4c457c40cdbe371be14" 51 | }, 52 | { 53 | "curve": "secp256k1", 54 | "fingerprint": "412a79cdcbe92012b658a9080603d7fa6a26aff0f643ab8d9a81e0d53183cda5", 55 | "purpose": "update", 56 | "type": "ec", 57 | "value": "030c6815bfa049a73ad732e352c172f10c2bc4cb702c4bd846fd0cd408a4589cd8" 58 | }, 59 | { 60 | "fingerprint": "ef30488f7afb43729e942b48582cc3e6a0d2b612", 61 | "purpose": "sign", 62 | "type": "dsa", 63 | "value": "AAAAAACAlQebM8J5aOgjcA3hy3WZrnpEeuBCgD6RlyTqYmQ9vfYfITos7znEPQX8ChPNgqfg1vtcvnb+bmyA3DPEbS5Okr4ZuCmSF+Z+z6sIpL/7IKwfd3wcxvLPD8zO71zd4zz8SayxzBvORjV6eZZOIgmF51DMNBz+21g9T8cOeTeShiUAAAAUjfAeevfP1vzNrcOmJjrAP6y6y9UAAACAjvdtJFGfdKhoviqN2i2v29Muifh1DtuLYXwlCOFllnCb0lbpyXaxCOFkCsBfwIsZF1UnfLXQuUe6d6oKaHekxJZjrgsE1xN7zu/oMedaFzJmPmjQ8qulljDWt3AyiCvfBRsnX9zw7AoQ7b2nwCWC+9I3NziAa6iooE4WRJX9MVUAAACAdiJYBGhyP4sXgOxtDSZ8qQM9s8ERlGIhDv+UxrCqU8EdtJwJ9TjGjqK7N+kPgKXyvFBSmZBneYCIPnYxgOU8/BMdkRWHXwWCYT2KfjeDshGi29wK2LFJHTUIJerESUpqtQC4gWJ3iB659PQN4wHnEFagvbPlvogAQ3EARgN/ndE=" 64 | } 65 | ], 66 | "summary": "Ted's best friend", 67 | "v": "0.3", 68 | "websites": [ 69 | { 70 | "url": "wyldstallyns.com" 71 | } 72 | ] 73 | } 74 | -------------------------------------------------------------------------------- /test/fixtures/rufus-priv.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "fingerprint": "mh2ohnVtug58y43yCLWN94fnh4u3aBhTbn", 4 | "networkName": "testnet", 5 | "priv": "cRzqXXUFdZJkuGbE2S3hTZG3W2wMB3QnoChUywwP7KmtCEKoxXU8", 6 | "purpose": "payment", 7 | "type": "bitcoin", 8 | "value": "02ab5eb837f60a46a7df370fc8f6ec168584ae63faeb387c4bc06c612af04894f9" 9 | }, 10 | { 11 | "fingerprint": "n4k5GdVh5C2bkPvKrQZZGfXUuWBwbTyXJC", 12 | "networkName": "testnet", 13 | "priv": "cNo1caUaTvFoxwfoGhkuK5cWDHqGPTRhv8rQJtSbe7Hx5Jbkp9SK", 14 | "purpose": "messaging", 15 | "type": "bitcoin", 16 | "value": "03b1b2b4ab7357bfbf8b55ff06d42c70df3e63a6d8a8a512a8e72dbb4b82b1a917" 17 | }, 18 | { 19 | "curve": "secp256k1", 20 | "fingerprint": "f970852c1f6c34330341239102fd58e0b34b34f766195dbc6ebd90ba8ce1df8e", 21 | "priv": "b75f628914df769ccd3095d3ec2cb38cca5c8989412313d1c93e2578aea1e2f9", 22 | "purpose": "sign", 23 | "type": "ec", 24 | "value": "022ca6732de155b529104b5815c91188a4ab897028cedca292f33169de02476545" 25 | }, 26 | { 27 | "curve": "secp256k1", 28 | "fingerprint": "0370dd01759e9a55ff030ed6aeca842fd3ebe3f357195f8625ccfe6f3448c2d4", 29 | "priv": "4649d5993f33d4670078d8989b16368b2b0c36c5fe371d1d731a2e694ba2ba41", 30 | "purpose": "update", 31 | "type": "ec", 32 | "value": "02968bbba810f433fcfa75b683dc74b2c72c8aa91a42e062f6152823e3fad10cde" 33 | }, 34 | { 35 | "fingerprint": "78ff4e9fd6a0e4c751edc7e030c2c1254ee9f7bc", 36 | "priv": "AAAAAACAv8e4LjUSadZRz9kDaUVw1Y0e7IjyFR6t5sM3WjMF7dWkWEHq6iGjwNJG4l/1EI/Wm0aJteFTyDSP0s9EBDjTpM0cx2ZvJ2FGTqESMvu+OTs3PeLZV/oveEboKOU9RY+Vb7N7Zs9SFwf45Xr4jO5Ah9oIbzbGO1t+08U+iQWkbAMAAAAUlomrQgaZ4MBFaBifW3LuDKlx5+cAAACACt/UC1RMj4fy4703V5DtKon+LXYUkR+b3AwEYLxf4QvFdSXDugZJ8xZaqD5nRGqlKNxDkGvwEwvTqYt9tAF/NdaRIwd1MSFn/bURygP2Uce2WKbP3D9HagvtwmujnsQZFL4ijmIMVjqKmXKno9UTphDuL5WjxrTBH2jjrCsoNWgAAACAGnPqteoYK/PzgDVNozsKMg4o1t1lr8WKYtzf75qydRwr9MPemiWzD/MduiIZrbitd+Kg9Q89S1dLpnep2gqkh2YfobG15mvp4je/GPmD+4EW85vlyMLo1eQRhfPtbi5KDf2J6hnHpwWboi8bzFl50yvHjD+zc6mrPmWhzCo2oowAAAAUPM3wcPDrUAHh5lvWTX6VSKKMav8=", 37 | "purpose": "sign", 38 | "type": "dsa", 39 | "value": "AAAAAACAv8e4LjUSadZRz9kDaUVw1Y0e7IjyFR6t5sM3WjMF7dWkWEHq6iGjwNJG4l/1EI/Wm0aJteFTyDSP0s9EBDjTpM0cx2ZvJ2FGTqESMvu+OTs3PeLZV/oveEboKOU9RY+Vb7N7Zs9SFwf45Xr4jO5Ah9oIbzbGO1t+08U+iQWkbAMAAAAUlomrQgaZ4MBFaBifW3LuDKlx5+cAAACACt/UC1RMj4fy4703V5DtKon+LXYUkR+b3AwEYLxf4QvFdSXDugZJ8xZaqD5nRGqlKNxDkGvwEwvTqYt9tAF/NdaRIwd1MSFn/bURygP2Uce2WKbP3D9HagvtwmujnsQZFL4ijmIMVjqKmXKno9UTphDuL5WjxrTBH2jjrCsoNWgAAACAGnPqteoYK/PzgDVNozsKMg4o1t1lr8WKYtzf75qydRwr9MPemiWzD/MduiIZrbitd+Kg9Q89S1dLpnep2gqkh2YfobG15mvp4je/GPmD+4EW85vlyMLo1eQRhfPtbi5KDf2J6hnHpwWboi8bzFl50yvHjD+zc6mrPmWhzCo2oow=" 40 | } 41 | ] -------------------------------------------------------------------------------- /test/fixtures/rufus-pub.json: -------------------------------------------------------------------------------- 1 | { 2 | "_t": "tradle.Identity", 3 | "_z": "1", 4 | "contact": [ 5 | { 6 | "identifier": "rufus", 7 | "type": "skype" 8 | } 9 | ], 10 | "location": { 11 | "formatted": "the future" 12 | }, 13 | "name": { 14 | "firstName": "Rufus", 15 | "formatted": "Rufus" 16 | }, 17 | "photos": [ 18 | { 19 | "type": "headshot", 20 | "url": "http://i2.wp.com/www.nowverybad.com/wp-content/uploads/bill_and_teds_excellent_adventure_still2.jpg" 21 | } 22 | ], 23 | "pubkeys": [ 24 | { 25 | "fingerprint": "mh2ohnVtug58y43yCLWN94fnh4u3aBhTbn", 26 | "networkName": "testnet", 27 | "purpose": "payment", 28 | "type": "bitcoin", 29 | "value": "02ab5eb837f60a46a7df370fc8f6ec168584ae63faeb387c4bc06c612af04894f9" 30 | }, 31 | { 32 | "fingerprint": "n4k5GdVh5C2bkPvKrQZZGfXUuWBwbTyXJC", 33 | "networkName": "testnet", 34 | "purpose": "messaging", 35 | "type": "bitcoin", 36 | "value": "03b1b2b4ab7357bfbf8b55ff06d42c70df3e63a6d8a8a512a8e72dbb4b82b1a917" 37 | }, 38 | { 39 | "curve": "secp256k1", 40 | "fingerprint": "f970852c1f6c34330341239102fd58e0b34b34f766195dbc6ebd90ba8ce1df8e", 41 | "purpose": "sign", 42 | "type": "ec", 43 | "value": "022ca6732de155b529104b5815c91188a4ab897028cedca292f33169de02476545" 44 | }, 45 | { 46 | "curve": "secp256k1", 47 | "fingerprint": "0370dd01759e9a55ff030ed6aeca842fd3ebe3f357195f8625ccfe6f3448c2d4", 48 | "purpose": "update", 49 | "type": "ec", 50 | "value": "02968bbba810f433fcfa75b683dc74b2c72c8aa91a42e062f6152823e3fad10cde" 51 | }, 52 | { 53 | "fingerprint": "78ff4e9fd6a0e4c751edc7e030c2c1254ee9f7bc", 54 | "purpose": "sign", 55 | "type": "dsa", 56 | "value": "AAAAAACAv8e4LjUSadZRz9kDaUVw1Y0e7IjyFR6t5sM3WjMF7dWkWEHq6iGjwNJG4l/1EI/Wm0aJteFTyDSP0s9EBDjTpM0cx2ZvJ2FGTqESMvu+OTs3PeLZV/oveEboKOU9RY+Vb7N7Zs9SFwf45Xr4jO5Ah9oIbzbGO1t+08U+iQWkbAMAAAAUlomrQgaZ4MBFaBifW3LuDKlx5+cAAACACt/UC1RMj4fy4703V5DtKon+LXYUkR+b3AwEYLxf4QvFdSXDugZJ8xZaqD5nRGqlKNxDkGvwEwvTqYt9tAF/NdaRIwd1MSFn/bURygP2Uce2WKbP3D9HagvtwmujnsQZFL4ijmIMVjqKmXKno9UTphDuL5WjxrTBH2jjrCsoNWgAAACAGnPqteoYK/PzgDVNozsKMg4o1t1lr8WKYtzf75qydRwr9MPemiWzD/MduiIZrbitd+Kg9Q89S1dLpnep2gqkh2YfobG15mvp4je/GPmD+4EW85vlyMLo1eQRhfPtbi5KDf2J6hnHpwWboi8bzFl50yvHjD+zc6mrPmWhzCo2oow=" 57 | } 58 | ], 59 | "summary": "rock star", 60 | "v": "0.3", 61 | "websites": [ 62 | { 63 | "url": "wyldstallyns.com" 64 | } 65 | ] 66 | } 67 | -------------------------------------------------------------------------------- /test/fixtures/ted-priv.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "fingerprint": "mqr7PxxqHsJXtmJFK2ZTKAKRAdrKyu6tDm", 4 | "networkName": "testnet", 5 | "priv": "cUaL3uVQDC8iC7zUesct9eVsRHMsZBXdAfyEuseURLBNJEnnaySL", 6 | "purpose": "payment", 7 | "type": "bitcoin", 8 | "value": "035b5a47dc3664ca3de80cb2f4073321e64f6e79bb51155afa2d115a43b2965c40" 9 | }, 10 | { 11 | "fingerprint": "mszCijohgq93dkJ5tv872PJ6NDTqCfhXkB", 12 | "networkName": "testnet", 13 | "priv": "cRSMLHCrqSgBWSyGDM9trYMymTsnJhiJUsUJdUR5sKHCwjR1jqwC", 14 | "purpose": "messaging", 15 | "type": "bitcoin", 16 | "value": "037b753c4e9ad29a387347460319b00675a936fe01ef083e41a3a819838be46056" 17 | }, 18 | { 19 | "curve": "secp256k1", 20 | "fingerprint": "b6a8845a0b3632da071015118b90de63e79dd2bf84dc17d7f96625e4be3cae1e", 21 | "priv": "fac27b08f332455c1d5eeaeb301841d6945171c077bf835217ae14a9728bc9d0", 22 | "purpose": "sign", 23 | "type": "ec", 24 | "value": "03841947e74f7e140955f6f5c2e149916d71f78ea2b27c6387f0cd95527b3f975e" 25 | }, 26 | { 27 | "curve": "secp256k1", 28 | "fingerprint": "df85cb647850a0588068c71707bd30b42c19f1e1987c7ba7b03ac4e30774f45b", 29 | "priv": "3ed050f21eaa5c8a9298c4b564da456d30bd3dfce2c75d0b0a2e4baad9f8b32b", 30 | "purpose": "update", 31 | "type": "ec", 32 | "value": "039bed0cd5edfac6442ada7ded097520065a2bec1b184730eb33da52742eaa5b31" 33 | }, 34 | { 35 | "fingerprint": "e7ce27370b81431e617f172739a0d1a0c313da26", 36 | "priv": "AAAAAACAlQebM8J5aOgjcA3hy3WZrnpEeuBCgD6RlyTqYmQ9vfYfITos7znEPQX8ChPNgqfg1vtcvnb+bmyA3DPEbS5Okr4ZuCmSF+Z+z6sIpL/7IKwfd3wcxvLPD8zO71zd4zz8SayxzBvORjV6eZZOIgmF51DMNBz+21g9T8cOeTeShiUAAAAUjfAeevfP1vzNrcOmJjrAP6y6y9UAAACAjvdtJFGfdKhoviqN2i2v29Muifh1DtuLYXwlCOFllnCb0lbpyXaxCOFkCsBfwIsZF1UnfLXQuUe6d6oKaHekxJZjrgsE1xN7zu/oMedaFzJmPmjQ8qulljDWt3AyiCvfBRsnX9zw7AoQ7b2nwCWC+9I3NziAa6iooE4WRJX9MVUAAACAelwmnPmXvK6E8nOk3P0i/fXJOOkCpiZEfgiiL2JhNl9NH1HhBcYTL0bO2p55ZNUwcsahmXaa/lYmlonX+gGt+2j34Y4h3/6XGxsK/3EP++e7Da8xSocMSFQC5B6AY6mfsGXOWoyB9xpzejJNlzO7Ut0XJyOgkz1Pk1LXKpoZwLcAAAAUhMtyXxrwg0+txAIHMRnrnfUAq8I=", 37 | "purpose": "sign", 38 | "type": "dsa", 39 | "value": "AAAAAACAlQebM8J5aOgjcA3hy3WZrnpEeuBCgD6RlyTqYmQ9vfYfITos7znEPQX8ChPNgqfg1vtcvnb+bmyA3DPEbS5Okr4ZuCmSF+Z+z6sIpL/7IKwfd3wcxvLPD8zO71zd4zz8SayxzBvORjV6eZZOIgmF51DMNBz+21g9T8cOeTeShiUAAAAUjfAeevfP1vzNrcOmJjrAP6y6y9UAAACAjvdtJFGfdKhoviqN2i2v29Muifh1DtuLYXwlCOFllnCb0lbpyXaxCOFkCsBfwIsZF1UnfLXQuUe6d6oKaHekxJZjrgsE1xN7zu/oMedaFzJmPmjQ8qulljDWt3AyiCvfBRsnX9zw7AoQ7b2nwCWC+9I3NziAa6iooE4WRJX9MVUAAACAelwmnPmXvK6E8nOk3P0i/fXJOOkCpiZEfgiiL2JhNl9NH1HhBcYTL0bO2p55ZNUwcsahmXaa/lYmlonX+gGt+2j34Y4h3/6XGxsK/3EP++e7Da8xSocMSFQC5B6AY6mfsGXOWoyB9xpzejJNlzO7Ut0XJyOgkz1Pk1LXKpoZwLc=" 40 | } 41 | ] -------------------------------------------------------------------------------- /test/fixtures/ted-pub.json: -------------------------------------------------------------------------------- 1 | { 2 | "_t": "tradle.Identity", 3 | "_z": "1", 4 | "contact": [ 5 | { 6 | "identifier": "somebodyelse", 7 | "type": "skype" 8 | } 9 | ], 10 | "location": { 11 | "city": "San Dimas", 12 | "country": "USA", 13 | "formatted": "666 Wyld Stallyns Dr, San Dimas, California", 14 | "postalCode": 666, 15 | "region": "California", 16 | "street": "666 Wyld Stallyns Dr" 17 | }, 18 | "name": { 19 | "firstName": "Ted", 20 | "formatted": "Ted Theodore Logan", 21 | "lastName": "Logan", 22 | "middleName": "Theodore" 23 | }, 24 | "photos": [ 25 | { 26 | "type": "headshot", 27 | "url": "http://scrapetv.com/News/News%20Pages/Entertainment/images-9/keanu-reeves-bill-and-ted.jpg" 28 | } 29 | ], 30 | "pubkeys": [ 31 | { 32 | "fingerprint": "mqr7PxxqHsJXtmJFK2ZTKAKRAdrKyu6tDm", 33 | "networkName": "testnet", 34 | "purpose": "payment", 35 | "type": "bitcoin", 36 | "value": "035b5a47dc3664ca3de80cb2f4073321e64f6e79bb51155afa2d115a43b2965c40" 37 | }, 38 | { 39 | "fingerprint": "mszCijohgq93dkJ5tv872PJ6NDTqCfhXkB", 40 | "networkName": "testnet", 41 | "purpose": "messaging", 42 | "type": "bitcoin", 43 | "value": "037b753c4e9ad29a387347460319b00675a936fe01ef083e41a3a819838be46056" 44 | }, 45 | { 46 | "curve": "secp256k1", 47 | "fingerprint": "b6a8845a0b3632da071015118b90de63e79dd2bf84dc17d7f96625e4be3cae1e", 48 | "purpose": "sign", 49 | "type": "ec", 50 | "value": "03841947e74f7e140955f6f5c2e149916d71f78ea2b27c6387f0cd95527b3f975e" 51 | }, 52 | { 53 | "curve": "secp256k1", 54 | "fingerprint": "df85cb647850a0588068c71707bd30b42c19f1e1987c7ba7b03ac4e30774f45b", 55 | "purpose": "update", 56 | "type": "ec", 57 | "value": "039bed0cd5edfac6442ada7ded097520065a2bec1b184730eb33da52742eaa5b31" 58 | }, 59 | { 60 | "fingerprint": "e7ce27370b81431e617f172739a0d1a0c313da26", 61 | "purpose": "sign", 62 | "type": "dsa", 63 | "value": "AAAAAACAlQebM8J5aOgjcA3hy3WZrnpEeuBCgD6RlyTqYmQ9vfYfITos7znEPQX8ChPNgqfg1vtcvnb+bmyA3DPEbS5Okr4ZuCmSF+Z+z6sIpL/7IKwfd3wcxvLPD8zO71zd4zz8SayxzBvORjV6eZZOIgmF51DMNBz+21g9T8cOeTeShiUAAAAUjfAeevfP1vzNrcOmJjrAP6y6y9UAAACAjvdtJFGfdKhoviqN2i2v29Muifh1DtuLYXwlCOFllnCb0lbpyXaxCOFkCsBfwIsZF1UnfLXQuUe6d6oKaHekxJZjrgsE1xN7zu/oMedaFzJmPmjQ8qulljDWt3AyiCvfBRsnX9zw7AoQ7b2nwCWC+9I3NziAa6iooE4WRJX9MVUAAACAelwmnPmXvK6E8nOk3P0i/fXJOOkCpiZEfgiiL2JhNl9NH1HhBcYTL0bO2p55ZNUwcsahmXaa/lYmlonX+gGt+2j34Y4h3/6XGxsK/3EP++e7Da8xSocMSFQC5B6AY6mfsGXOWoyB9xpzejJNlzO7Ut0XJyOgkz1Pk1LXKpoZwLc=" 64 | } 65 | ], 66 | "summary": "Bill's best friend", 67 | "v": "0.3", 68 | "websites": [ 69 | { 70 | "url": "wyldstallyns.com" 71 | } 72 | ] 73 | } 74 | -------------------------------------------------------------------------------- /test/genUsers.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | var fs = require('fs') 4 | var path = require('path') 5 | var Q = require('q') 6 | var typeforce = require('typeforce') 7 | var randomName = require('random-name') 8 | var kiki = require('@tradle/kiki') 9 | var identityLib = require('@tradle/identity') 10 | var Identity = identityLib.Identity 11 | var constants = require('@tradle/constants') 12 | var NONCE = constants.NONCE 13 | var argv = require('minimist')(process.argv.slice(2), { 14 | alias: { 15 | f: 'file', 16 | n: 'number' 17 | } 18 | }) 19 | 20 | var utils = require('../lib/utils') 21 | genUsers(argv) 22 | 23 | function genUsers (opts) { 24 | typeforce({ 25 | file: 'String', 26 | number: 'Number' 27 | }, opts) 28 | 29 | var file = path.resolve(opts.file) 30 | var number = opts.number 31 | var users = [] 32 | for (var i = 0; i < number; i++) { 33 | var first = randomName.first() 34 | var last = randomName.last() 35 | var identity = new Identity() 36 | .name({ 37 | firstName: first, 38 | lastName: last, 39 | formatted: first + ' ' + last 40 | }) 41 | .set(NONCE, '' + i) 42 | 43 | var keys = identityLib.defaultKeySet({ 44 | networkName: 'testnet' 45 | }) 46 | 47 | if (keys.every(function (k) { 48 | return k.type() !== 'dsa' 49 | })) { 50 | keys.push(kiki.Keys.DSA.gen({ purpose: 'sign' })) 51 | } 52 | 53 | keys.forEach(identity.addKey, identity) 54 | 55 | users.push({ 56 | pub: identity.toJSON(), 57 | priv: keys.map(function (k) { 58 | return k.exportPrivate() 59 | }) 60 | }) 61 | } 62 | 63 | Q.all(users.map(function (u) { 64 | return utils.getDHTKey(u.pub) 65 | })) 66 | .done(function (hashes) { 67 | users.forEach(function (u, i) { 68 | u.rootHash = hashes[i] 69 | }) 70 | 71 | fs.writeFile(file, JSON.stringify(users, null, 2)) 72 | }) 73 | } 74 | -------------------------------------------------------------------------------- /test/getViaCache.js: -------------------------------------------------------------------------------- 1 | 2 | var test = require('tape') 3 | var getViaCache = require('../lib/getViaCache') 4 | 5 | test('getViaCache', function (t) { 6 | 7 | var cached = {} 8 | var UNCACHED = 0 9 | var CACHED = 1 10 | 11 | function getRegular (ids, cb) { 12 | ids.forEach(function (id) { 13 | cached[id] = true 14 | }) 15 | 16 | cb(null, ids.map(function () { 17 | return UNCACHED 18 | })) 19 | } 20 | 21 | function getFromCache (ids, cb) { 22 | cb(null, ids.map(function (id) { 23 | return cached[id] ? CACHED : UNCACHED 24 | })) 25 | } 26 | 27 | var get = getViaCache( 28 | getRegular, 29 | getFromCache 30 | ) 31 | 32 | var query = [1, 2, 3] 33 | get(query, function (err, results) { 34 | if (err) throw err 35 | 36 | results.forEach(function (r, i) { 37 | t.equal(r, UNCACHED) 38 | }) 39 | 40 | query = [2, 3, 4] 41 | get(query, function (err, results) { 42 | if (err) throw err 43 | 44 | t.equal(results[0], CACHED) 45 | t.equal(results[1], CACHED) 46 | t.equal(results[2], UNCACHED) 47 | 48 | query = [2, 7, 1] 49 | get(query, function (err, results) { 50 | if (err) throw err 51 | 52 | t.equal(results[0], CACHED) 53 | t.equal(results[1], UNCACHED) 54 | t.equal(results[2], CACHED) 55 | t.end() 56 | }) 57 | }) 58 | }) 59 | }) 60 | -------------------------------------------------------------------------------- /test/helpers/utils.js: -------------------------------------------------------------------------------- 1 | 2 | var typeforce = require('typeforce') 3 | var Zlorp = require('zlorp') 4 | var DSA = Zlorp.DSA 5 | var memdown = require('memdown') 6 | var DHT = require('@tradle/bittorrent-dht') 7 | var basePort = 22222 8 | 9 | module.exports = { 10 | makeConnectedDHTs: makeConnectedDHTs, 11 | destroyZlorps: destroyZlorps, 12 | connectDHTs: connectDHTs, 13 | makeConnectedZlorps: makeConnectedZlorps 14 | } 15 | 16 | function makeConnectedDHTs (n, cb) { 17 | var dhts = [] 18 | for (var i = 0; i < n; i++) { 19 | var dht = new DHT({ bootstrap: false }) 20 | dht.listen(basePort++, finish) 21 | dhts.push(dht) 22 | } 23 | 24 | function finish () { 25 | if (--n === 0) { 26 | connectDHTs(dhts) 27 | cb(dhts) 28 | } 29 | } 30 | 31 | return dhts 32 | } 33 | 34 | function makeConnectedZlorps (identityInfos, cb) { 35 | identityInfos.forEach(function (identityInfo) { 36 | typeforce({ 37 | pub: 'Object', 38 | priv: 'Array' 39 | }, identityInfo) 40 | }) 41 | 42 | makeConnectedDHTs(identityInfos.length, function (dhts) { 43 | var nodes = dhts.map(function (dht, i) { 44 | var identityInfo = identityInfos[i] 45 | return new Zlorp({ 46 | name: identityInfo.pub.name.firstName, 47 | port: process.env.MULTIPLEX ? dht.address().port : basePort++, 48 | dht: dht, 49 | key: getDSAKey(identityInfo.priv), 50 | leveldown: memdown 51 | }) 52 | }) 53 | 54 | cb(nodes) 55 | }) 56 | } 57 | 58 | function destroyZlorps (nodes, cb) { 59 | nodes = [].concat(nodes) 60 | var togo = nodes.length * 2 61 | nodes.forEach(function (node) { 62 | node.destroy(finish) 63 | node._dht.destroy(finish) 64 | }) 65 | 66 | function finish () { 67 | if (--togo === 0 && cb) cb() 68 | } 69 | } 70 | 71 | function connectDHTs (dhts) { 72 | var n = dhts.length 73 | 74 | for (var i = 0; i < n; i++) { 75 | var next = dhts[(i + 1) % n] 76 | dhts[i].addNode('127.0.0.1:' + next.address().port, next.nodeId) 77 | } 78 | } 79 | 80 | function getDSAKey (keys) { 81 | var key = keys.filter(function (k) { 82 | return k.type === 'dsa' 83 | })[0] 84 | 85 | return DSA.parsePrivate(key.priv) 86 | } 87 | -------------------------------------------------------------------------------- /test/identityDB.js: -------------------------------------------------------------------------------- 1 | 2 | var test = require('tape') 3 | var extend = require('xtend') 4 | var leveldown = require('memdown') 5 | var Q = require('q') 6 | var collect = require('stream-collector') 7 | var constants = require('@tradle/constants') 8 | var Log = require('logbase').Log 9 | var Entry = require('logbase').Entry 10 | var fakeKeeper = require('@tradle/test-helpers').fakeKeeper 11 | var createIdentityDB = require('../lib/identityDB') 12 | var ted = require('./fixtures/ted-pub') 13 | var EventType = require('../lib/eventType') 14 | var utils = require('../lib/utils') 15 | var TYPE = constants.TYPE 16 | var ROOT_HASH = constants.ROOT_HASH 17 | var PREV_HASH = constants.PREV_HASH 18 | var CUR_HASH = constants.CUR_HASH 19 | var IDENTITY_TYPE = constants.TYPES.IDENTITY 20 | var dbCounter = 0 21 | var nextDBName = function () { 22 | return 'db' + (dbCounter++) 23 | } 24 | 25 | test('ignore identities that collide on keys', function (t) { 26 | t.plan(ted.pubkeys.length) 27 | 28 | var log = new Log(nextDBName(), { 29 | db: leveldown 30 | }) 31 | 32 | ted = extend(ted) // defensive copy 33 | var badPerson = extend(ted, { name: 'evil ted' }) 34 | var keeperMap = {} 35 | var tedHash = 'abc' 36 | var badPersonHash = 'efg' 37 | keeperMap[tedHash] = ted 38 | keeperMap[badPersonHash] = badPerson 39 | 40 | var tedFromChain = new Entry({ 41 | type: EventType.chain.readSuccess 42 | }) 43 | .set(TYPE, IDENTITY_TYPE) 44 | .set(CUR_HASH, tedHash) 45 | .set(ROOT_HASH, tedHash) 46 | 47 | var badPersonFromChain = new Entry({ 48 | type: EventType.chain.readSuccess 49 | }) 50 | .set(TYPE, IDENTITY_TYPE) 51 | .set(CUR_HASH, badPersonHash) 52 | .set(ROOT_HASH, badPersonHash) 53 | 54 | log.append(tedFromChain) 55 | log.append(badPersonFromChain) 56 | 57 | var keeper = fakeKeeper.forMap(keeperMap) 58 | var identities = createIdentityDB(nextDBName(), { 59 | leveldown: leveldown, 60 | log: log, 61 | keeper: keeper 62 | }) 63 | 64 | identities.onLive(function () { 65 | Q.all(ted.pubkeys.map(function (k) { 66 | return Q.ninvoke(identities, 'byFingerprint', k.fingerprint) 67 | })) 68 | .done(function (identities) { 69 | identities.forEach(function (i) { 70 | t.deepEqual(i.identity.name, ted.name) 71 | }) 72 | }) 73 | }) 74 | }) 75 | 76 | test('update identity', function (t) { 77 | t.plan(7) 78 | 79 | var log = new Log(nextDBName(), { 80 | db: leveldown 81 | }) 82 | 83 | ted = extend(ted) 84 | 85 | var keeperMap = {} 86 | var originalHash = 'abc' 87 | var entry = new Entry({ 88 | type: EventType.chain.readSuccess 89 | }) 90 | .set(TYPE, IDENTITY_TYPE) 91 | .set(CUR_HASH, originalHash) 92 | .set(ROOT_HASH, originalHash) 93 | 94 | keeperMap[originalHash] = ted 95 | log.append(entry) 96 | 97 | ted = extend(ted) 98 | ted.name = 'ted!' 99 | 100 | var updateHash = 'abc1' 101 | var update = new Entry(entry.toJSON()) 102 | .set(CUR_HASH, updateHash) 103 | .set(PREV_HASH, originalHash) 104 | 105 | keeperMap[updateHash] = ted 106 | log.append(update) 107 | 108 | var keeper = fakeKeeper.forMap(keeperMap) 109 | var identities = createIdentityDB(nextDBName(), { 110 | leveldown: leveldown, 111 | log: log, 112 | keeper: keeper 113 | }) 114 | 115 | identities.on('change', function (id) { 116 | if (id !== 2) return 117 | 118 | identities.byFingerprint(ted.pubkeys[0].fingerprint, function (err, storedTed) { 119 | if (err) { 120 | t.error(err) 121 | throw err 122 | } 123 | 124 | t.deepEqual(storedTed.identity, ted) 125 | }) 126 | 127 | testStreams() 128 | }) 129 | 130 | function testStreams () { 131 | collect(identities.createReadStream(), function (err, stored) { 132 | if (err) throw err 133 | 134 | t.equal(stored.length, 1) 135 | t.deepEqual(stored[0].value.identity, ted) 136 | }) 137 | 138 | collect(identities.createKeyStream(), function (err, stored) { 139 | if (err) throw err 140 | 141 | t.equal(stored.length, 1) 142 | t.equal(stored[0], originalHash) 143 | }) 144 | 145 | collect(identities.createValueStream(), function (err, stored) { 146 | if (err) throw err 147 | 148 | t.equal(stored.length, 1) 149 | t.equal(stored[0].identity, ted) 150 | }) 151 | } 152 | }) 153 | -------------------------------------------------------------------------------- /test/index.js: -------------------------------------------------------------------------------- 1 | require('./end-to-end') 2 | require('./identityDB') 3 | require('./entries') 4 | // require('./messengers') 5 | require('./getViaCache') 6 | // require('./typestore') 7 | -------------------------------------------------------------------------------- /test/live.js: -------------------------------------------------------------------------------- 1 | 2 | var leveldown = require('memdown') 3 | // var utils = require('tradle-utils') 4 | var Identity = require('midentity').Identity 5 | // var tedPriv = require('chained-chat/test/fixtures/ted-priv') 6 | // var Fakechain = require('blockloader/fakechain') 7 | // var Blockchain = require('cb-blockr') 8 | // var Keeper = require('bitkeeper-js') 9 | // var Wallet = require('simple-wallet') 10 | // var fakeKeeper = help.fakeKeeper 11 | // var fakeWallet = help.fakeWallet 12 | // var ted = Identity.fromJSON(tedPriv) 13 | var billPriv = require('./fixtures/bill-priv') 14 | billPriv.forEach(function (k) { 15 | if (k.type === 'bitcoin' && k.purpose === 'messaging') { 16 | // invalidate key 17 | k.fingerprint = 'mxFoKKA7R8CbjZk1ybaXwgrF8c8QnvnkdD' 18 | } 19 | }) 20 | 21 | var billPub = require('./fixtures/bill-pub.json') 22 | // var networkName = 'testnet' 23 | var BILL_PORT = 51086 24 | var TestDriver = require('./helpers/testDriver') 25 | // var keeper = fakeKeeper.empty() 26 | 27 | // function buildDriver (identity, keys, port) { 28 | // var iJSON = identity.toJSON() 29 | // var dht = dhtFor(iJSON) 30 | // dht.listen(port) 31 | 32 | // var keeper = new Keeper({ 33 | // dht: dht 34 | // }) 35 | 36 | // var blockchain = new Blockchain(networkName) 37 | 38 | // return new Driver({ 39 | // pathPrefix: iJSON.name.firstName.toLowerCase(), 40 | // networkName: networkName, 41 | // keeper: keeper, 42 | // blockchain: blockchain, 43 | // leveldown: leveldown, 44 | // identity: identity, 45 | // identityKeys: keys, 46 | // dht: dht, 47 | // port: port, 48 | // syncInterval: 60000 49 | // }) 50 | 51 | // } 52 | 53 | // var tedPub = new Buffer(stringify(require('./fixtures/ted-pub.json')), 'binary') 54 | // var tedPriv = require('./fixtures/ted-priv') 55 | // var ted = Identity.fromJSON(tedPriv) 56 | // var tedPort = 51087 57 | // var tedWallet = realWalletFor(ted) 58 | // var blockchain = tedWallet.blockchain 59 | // var tedWallet = walletFor(ted) 60 | 61 | var driverBill = TestDriver.real({ 62 | identity: Identity.fromJSON(billPub), 63 | identityKeys: billPriv, 64 | port: BILL_PORT, 65 | leveldown: leveldown 66 | }) 67 | 68 | driverBill.once('ready', function () { 69 | driverBill.on('chained', function (obj) { 70 | console.log('chained', obj) 71 | }) 72 | 73 | debugger 74 | driverBill.publishMyIdentity() 75 | driverBill.on('error', function (err) { 76 | console.error(err) 77 | }) 78 | }) 79 | 80 | console.log('Send money to', driverBill.wallet.addressString) 81 | printBalance() 82 | setInterval(printBalance, 60000).unref() 83 | 84 | // setTimeout(function () { 85 | // driverBill.destroy() 86 | // .then(function () { 87 | // driverBill.dht.destroy() 88 | // }) 89 | // }, 5000) 90 | 91 | // driverTed.on('ready', function () { 92 | // var msg = new Buffer(stringify({ 93 | // hey: 'ho' 94 | // }), 'binary') 95 | 96 | // driverTed.send({ 97 | // msg: msg, 98 | // to: bill 99 | // }) 100 | // }) 101 | 102 | function printBalance () { 103 | driverBill.wallet.balance(function (err, balance) { 104 | if (err) console.error('failed to get balance', err.message) 105 | else console.log('balance', balance) 106 | }) 107 | } 108 | 109 | // function fakeWalletFor (identity) { 110 | // return fakeWallet({ 111 | // blockchain: blockchain, 112 | // unspents: [100000, 100000, 100000, 100000], 113 | // priv: identity.keys({ 114 | // type: 'bitcoin', 115 | // networkName: networkName 116 | // })[0].priv() 117 | // }) 118 | // } 119 | -------------------------------------------------------------------------------- /test/server.js: -------------------------------------------------------------------------------- 1 | 2 | var mockery = require('mockery') 3 | mockery.enable({ 4 | warnOnReplace: false, 5 | warnOnUnregistered: false 6 | }) 7 | 8 | mockery.registerSubstitute('q', 'bluebird-q') 9 | 10 | var http = require('http') 11 | // http.globalAgent.maxSockets = 100 12 | var path = require('path') 13 | var test = require('tape') 14 | var find = require('array-find') 15 | var typeforce = require('typeforce') 16 | var extend = require('xtend') 17 | var rimraf = require('rimraf') 18 | var clone = require('clone') 19 | var Q = require('q') 20 | var express = require('express') 21 | var leveldown = require('leveldown') 22 | var helpers = require('@tradle/test-helpers') 23 | var constants = require('@tradle/constants') 24 | var ROOT_HASH = constants.ROOT_HASH 25 | var Identity = require('@tradle/identity').Identity 26 | var FakeKeeper = helpers.fakeKeeper 27 | var fakeWallet = helpers.fakeWallet 28 | var Transport = require('@tradle/transport-http') 29 | var Tim = require('../') 30 | var DAY_MILLIS = 24 * 3600 * 1000 31 | Tim.CATCH_UP_INTERVAL = DAY_MILLIS 32 | Tim.enableOptimizations() 33 | var NONCE = 0 34 | var BASE_PORT = 22222 35 | var networkName = 'testnet' 36 | var users = require('./users') 37 | var bitcoin = require('@tradle/bitcoinjs-lib') 38 | var kiki = require('@tradle/kiki') 39 | 40 | // pre-cache key-parsing 41 | users.forEach(function (u) { 42 | u.pub.pubkeys.forEach(function (k) { 43 | kiki.toKey(k) 44 | }) 45 | }) 46 | 47 | var ONE 48 | var MANY 49 | var STORAGE_PATH = './server-storage' 50 | var sharedKeeper = FakeKeeper.empty() 51 | var commonOpts = { 52 | syncInterval: DAY_MILLIS, 53 | chainThrottle: DAY_MILLIS, 54 | unchainThrottle: DAY_MILLIS, 55 | sendThrottle: DAY_MILLIS, 56 | networkName: networkName, 57 | leveldown: leveldown 58 | } 59 | 60 | var TimeMethod = require('time-method') 61 | // var timTimer = TimeMethod.timeFunctions(Tim.prototype) 62 | // var processTimer = TimeMethod.timerFor(process) 63 | // processTimer.time('nextTick') 64 | 65 | init() 66 | // setInterval(process.exit.bind(process, 0), 10000) 67 | process.on('SIGINT', function () { 68 | // printStats(timTimer) 69 | process.exit(1) 70 | }) 71 | 72 | function printStats (timer) { 73 | var stats = timer.getStats() 74 | // .filter(function (s) { 75 | // return s.time > 200000000 // 200 ms 76 | // }) 77 | 78 | stats.forEach(function (s) { 79 | s.time /= 1e6 80 | s.timePerInvocation /= 1e6 81 | }) 82 | 83 | console.log(stats) 84 | timer.reset() 85 | } 86 | 87 | function clearStorage () { 88 | rimraf.sync(path.join(STORAGE_PATH, '*')) 89 | } 90 | 91 | function init () { 92 | clearStorage() 93 | var userInfo = users[0] 94 | var wallet = walletFor(userInfo.priv, null, 'messaging') 95 | var pub = userInfo.pub 96 | var app = express() 97 | var router = express.Router() 98 | var server = app.listen(BASE_PORT) 99 | var httpServer = new Transport.HttpServer({ 100 | router: router, 101 | receive: function (msg, from) { 102 | return respondTo(msg, from) 103 | } 104 | }) 105 | 106 | var serverMan = new Tim(extend(commonOpts, { 107 | keys: userInfo.priv, 108 | identity: Identity.fromJSON(pub), 109 | pathPrefix: getPathPrefix(pub.name.firstName), 110 | wallet: wallet, 111 | blockchain: wallet.blockchain, 112 | keeper: newKeeper(), 113 | _send: function (rh, msg) { 114 | var recipientInfo = {} 115 | recipientInfo[ROOT_HASH] = serverMan.myRootHash() 116 | return httpServer.send(rh, msg, recipientInfo) 117 | } 118 | })) 119 | 120 | users.slice(1).forEach(function (u) { 121 | serverMan.addContactIdentity(u.pub) 122 | }) 123 | 124 | serverMan.ready().then(function () { 125 | app.use('/' + serverMan.myRootHash(), router) 126 | console.log(serverMan.name(), 'is ready!') 127 | }) 128 | 129 | function respondTo (msg, from) { 130 | var defer = Q.defer() 131 | serverMan.receiveMsg(msg, from).done() 132 | serverMan.on('message', handler) 133 | return defer.promise 134 | 135 | function handler (info) { 136 | if (info.from[ROOT_HASH] !== from[ROOT_HASH]) return 137 | 138 | serverMan.lookupObject(info) 139 | .then(function (obj) { 140 | var msg = obj.parsed.data 141 | msg.ack = true 142 | // TODO: sign 143 | return serverMan.send({ 144 | msg: msg, 145 | to: [from], 146 | deliver: true 147 | }) 148 | }) 149 | .then(function (entries) { 150 | var entry = entries[0] 151 | serverMan.on('sent', function (info) { 152 | if (info.uid === entry.get('uid')) { 153 | serverMan.removeListener('message', handler) 154 | defer.resolve() 155 | } 156 | }) 157 | }) 158 | .done() 159 | 160 | } 161 | } 162 | } 163 | 164 | function walletFor (keys, blockchain, purpose) { 165 | var unspents = [] 166 | for (var i = 0; i < 20; i++) { 167 | unspents.push(100000) 168 | } 169 | 170 | return fakeWallet({ 171 | blockchain: blockchain, 172 | unspents: unspents, 173 | priv: find(keys, function (k) { 174 | return k.type === 'bitcoin' && 175 | k.networkName === networkName && 176 | k.purpose === purpose 177 | }).priv 178 | }) 179 | } 180 | 181 | function publishIdentities (drivers, cb) { 182 | var defer = Q.defer() 183 | var togo = drivers.length * drivers.length 184 | drivers.forEach(function (d) { 185 | global.d = d 186 | d.on('unchained', onUnchained) 187 | d.publishMyIdentity().done() 188 | }) 189 | 190 | return defer.promise.nodeify(cb || noop) 191 | 192 | function onUnchained (info) { 193 | if (--togo) return 194 | 195 | drivers.forEach(function (d) { 196 | d.removeListener('unchained', onUnchained) 197 | }) 198 | 199 | defer.resolve() 200 | } 201 | } 202 | 203 | function newKeeper () { 204 | var k = FakeKeeper.empty() 205 | var getOne = k.getOne 206 | k.getOne = function (key) { 207 | return getOne.apply(this, arguments) 208 | .catch(function (err) { 209 | return sharedKeeper.getOne(key) 210 | }) 211 | } 212 | 213 | k.push = function (opts) { 214 | typeforce({ 215 | key: 'String', 216 | value: 'Buffer' 217 | }, opts) 218 | 219 | return sharedKeeper.put(opts.key, opts.value) 220 | } 221 | 222 | return k 223 | } 224 | 225 | function randomMessage () { 226 | return { 227 | _t: 'tradle.SimpleMessage', 228 | _z: '' + NONCE++, 229 | message: 'something random: ' + Math.random() 230 | } 231 | } 232 | 233 | function getPathPrefix (name) { 234 | return path.join(STORAGE_PATH, name.replace(/\s/g, '')) 235 | } 236 | --------------------------------------------------------------------------------