├── LICENSE ├── README.md ├── contracts ├── lib │ ├── Bytes32Lib.sol │ ├── IntLib.sol │ ├── JSONLib.sol │ ├── StringLib.sol │ ├── ethereans │ │ ├── bank │ │ │ ├── Bank.sol │ │ │ └── CollaborationBank.sol │ │ ├── management │ │ │ ├── EpochLocker.sol │ │ │ ├── Lockable.sol │ │ │ ├── Owned.sol │ │ │ └── Secret.sol │ │ └── token │ │ │ ├── AbstractToken.sol │ │ │ ├── JustifiedCollaborationToken.sol │ │ │ ├── LockerToken.sol │ │ │ ├── Token.sol │ │ │ └── WrappedEthToken.sol │ ├── oraclize │ │ └── oraclizeAPI_0.4.sol │ └── strings.sol └── src │ ├── BountyBank.sol │ ├── BountyBank2.sol │ ├── DGitDB.sol │ ├── GitHubAPIReg.sol │ ├── GitHubOracle.sol │ ├── GitHubPoints.sol │ ├── GitHubRepositoryReg.sol │ ├── GitHubUserReg.sol │ ├── GitRepository.sol │ ├── GitRepositoryToken.sol │ ├── NameRegistry.sol │ └── oraclize │ └── oraclizeAPI_0.4.sol ├── ethereum.json ├── scenarios └── InitRegAddClaim.yaml ├── scripts ├── github-oracle │ ├── .Dockerfile.swp │ ├── Dockerfile │ └── github_oracle.py ├── issue_claim │ ├── Dockerfile │ ├── issue_status.py │ └── pullrequest_contributors.py ├── oraclize-args │ ├── Dockerfile │ ├── README.md │ └── testarg.py └── test.sh └── tools └── encrypted_queries_tools.py /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 | # GitHubOracle 2 | Tokenize github repositories by commits and issues. Accept donations in eth tokens, distribute donations and bounties to code commiters. 3 | 4 | ## Usage 5 | 6 | ## User Registration 7 | Create a gist in your github containing in it's body only an ethereum address you own. 8 | Must be in first line with no spaces and no more lines. 9 | Call `DGit.register("","")` (oracle cost ~0.06 USD) 10 | Example: `DGit.register("3esmit","31a58f2ddf2258697cce1b969e7c298b")` 11 | 12 | ## Repository 13 | Call `DGit.addRepository("/")` (oracle cost ~0.06 USD) 14 | Example: `DGit.addRepository("status-im/github-oracle")` 15 | 16 | ### Tokenize Contributions 17 | Push your commits to GitHub and simply call `DGit.updateCommits("/")` 18 | This call will cost $0.54 USD and can process up to 4000 commits. 19 | Call `DGit.continueCommits("/")` (oracle cost ~0.54 USD) 20 | Example: `DGit.updateCommits("status-im/github-oracle")` 21 | 22 | ### Bounty issue 23 | When you start an issue at GitHub, you can bounty it. First you need to open it: 24 | Call `DGit.openBounty("/",)` (oracle cost ~0.06 USD) 25 | This will enable people to bounty into this issue, this call can contain itself a bounty to be added. 26 | When issue is finalized call `DGit.updateIssue("/",)` (oracle cost ~0.54 USD) 27 | This will tokenize the commits of pull requests cross-referenced with this issue and, after a lock period, distribute a fair share of bounty between contributors. 28 | 29 | ### Withdraw donations 30 | When contract enters in lock period just call `GitHubToken.withdraw()` to get your share of the donations. 31 | -------------------------------------------------------------------------------- /contracts/lib/Bytes32Lib.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.0; 2 | 3 | library Bytes32Lib { 4 | 5 | function toString(bytes32 self) internal constant returns (string) { 6 | bytes memory bytesString = new bytes(32); 7 | uint charCount = 0; 8 | for (uint j = 0; j < 32; j++) { 9 | byte char = byte(bytes32(uint(self) * 2 ** (8 * j))); 10 | if (char != 0) { 11 | bytesString[charCount] = char; 12 | charCount++; 13 | } 14 | } 15 | bytes memory bytesStringTrimmed = new bytes(charCount); 16 | for (j = 0; j < charCount; j++) { 17 | bytesStringTrimmed[j] = bytesString[j]; 18 | } 19 | return string(bytesStringTrimmed); 20 | } 21 | 22 | 23 | 24 | 25 | } -------------------------------------------------------------------------------- /contracts/lib/IntLib.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.0; 2 | 3 | library IntLib{ 4 | 5 | uint constant day = 60*60*24; 6 | uint constant week = 60*60*24*7; 7 | uint constant month = 60*60*24*30; 8 | 9 | function uint2str(uint i) internal constant returns (string){ 10 | if (i == 0) return "0"; 11 | uint j = i; 12 | uint len; 13 | while (j != 0){ 14 | len++; 15 | j /= 10; 16 | } 17 | bytes memory bstr = new bytes(len); 18 | uint k = len - 1; 19 | while (i != 0){ 20 | bstr[k--] = byte(48 + i % 10); 21 | i /= 10; 22 | } 23 | return string(bstr); 24 | } 25 | 26 | 27 | } 28 | -------------------------------------------------------------------------------- /contracts/lib/JSONLib.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.8; 2 | 3 | library JSONLib { 4 | 5 | function getNextString(bytes _str, uint8 _pos) internal constant returns (string,uint8) { 6 | uint8 start = 0; 7 | uint8 end = 0; 8 | uint strl =_str.length; 9 | for (;strl > _pos; _pos++) { 10 | if (_str[_pos] == '"'){ //Found quotation mark 11 | if(_str[_pos-1] != '\\'){ //is not escaped 12 | end = start == 0 ? 0: _pos; 13 | start = start == 0 ? (_pos+1) : start; 14 | if(end > 0) break; 15 | } 16 | } 17 | } 18 | bytes memory str = new bytes(end-start); 19 | for(_pos=0; _pos _pos; _pos++) { 32 | byte bp = _str[_pos]; 33 | if (bp == ','){ //Find ends 34 | _pos++; break; 35 | }else if ((bp >= 48)&&(bp <= 57)){ //only ASCII numbers 36 | val *= 10; 37 | val += uint(bp) - 48; 38 | } 39 | } 40 | return (val,_pos); 41 | } 42 | 43 | function getNextAddr(bytes _str, uint8 _pos) internal constant returns (address, uint8){ 44 | uint160 iaddr = 0; 45 | uint strl =_str.length; 46 | for(;strl > _pos; _pos++){ 47 | byte bp = _str[_pos]; 48 | if (bp == '0'){ 49 | if (_str[_pos+1] == 'x'){ 50 | for (_pos=_pos+2; _pos<2+2*20; _pos+=2){ 51 | iaddr *= 256; 52 | iaddr += (uint160(hexVal(uint160(_str[_pos])))*16+uint160(hexVal(uint160(_str[_pos+1])))); 53 | } 54 | _pos++; 55 | break; 56 | } 57 | }else if (bp == ','){ 58 | _pos++; 59 | break; 60 | } 61 | } 62 | return (address(iaddr),_pos); 63 | } 64 | 65 | function hexVal(uint val) internal constant returns (uint){ 66 | //return val - (val < 58 ? 48 : 55); //uppercase 67 | //return val - (val < 58 ? 48 : 87); //lowercase 68 | return val - (val < 58 ? 48 : (val < 97 ? 55 : 87)); //both 69 | } 70 | } -------------------------------------------------------------------------------- /contracts/lib/StringLib.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.9; 2 | 3 | 4 | library StringLib { 5 | 6 | function hexVal(uint val) internal constant returns (uint){ 7 | //return val - (val < 58 ? 48 : 55); //uppercase 8 | //return val - (val < 58 ? 48 : 87); //lowercase 9 | return val - (val < 58 ? 48 : (val < 97 ? 55 : 87)); //both 10 | } 11 | 12 | function toBytes32(string memory source) constant returns (bytes32 result) { 13 | assembly { 14 | result := mload(add(source, 32)) 15 | } 16 | } 17 | function toBytes20(string memory source) constant returns (bytes20 result) { 18 | assembly { 19 | result := mload(add(source, 20)) 20 | } 21 | } 22 | function parseBytes20(string self) 23 | constant returns (bytes20 bs) { 24 | bytes memory h = bytes(self); 25 | if (h.length>>1 != 20) 26 | throw;// new Exception("The binary need 20 digits"); 27 | for (uint i = 0; i < 20; ++i) 28 | { 29 | bs |= bytes20((byte)((hexVal(uint(h[i << 1])) << 4) + (hexVal(uint(h[(i << 1) + 1])))))>>(8*i); 30 | } 31 | return bs; 32 | } 33 | function parseBytes32(string self) 34 | constant returns (bytes32 bs) { 35 | bytes memory h = bytes(self); 36 | if (h.length>>1 != 32) 37 | throw;// new Exception("The binary need 20 digits"); 38 | for (uint i = 0; i < 32; ++i) 39 | { 40 | bs |= bytes32((byte)((hexVal(uint(h[i << 1])) << 4) + (hexVal(uint(h[(i << 1) + 1])))))>>(8*i); 41 | } 42 | return bs; 43 | } 44 | function parseAddr(string self) constant returns (address){ 45 | bytes memory tmp = bytes(self); 46 | uint iaddr = 0; 47 | for (uint i=2; i<2+2*20; i+=2){ 48 | iaddr += hexVal(uint(tmp[i]))*16+hexVal(uint(tmp[i+1])); 49 | } 50 | return address(iaddr); 51 | } 52 | 53 | function compare(string self, string _b) constant returns (int) { 54 | bytes memory a = bytes(self); 55 | bytes memory b = bytes(_b); 56 | uint minLength = a.length; 57 | uint bLength = b.length; 58 | if (bLength < minLength) minLength = bLength; 59 | for (uint i = 0; i < minLength; i++) 60 | byte ai = a[i]; 61 | byte bi = b[i]; 62 | if (ai < bi) 63 | return -1; 64 | else if (ai > bi) 65 | return 1; 66 | if (minLength < bLength) 67 | return -1; 68 | else if (minLength > bLength) 69 | return 1; 70 | else 71 | return 0; 72 | } 73 | 74 | function indexOf(string _haystack, string _needle) constant returns (int) { 75 | bytes memory h = bytes(_haystack); 76 | bytes memory n = bytes(_needle); 77 | uint hlength = h.length; 78 | uint nlength = n.length; 79 | byte n0 = n[0]; 80 | if(hlength < 1 || nlength < 1 || (nlength > hlength)) 81 | return -1; 82 | else if(hlength > (2**128 -1)) 83 | return -1; 84 | else 85 | { 86 | uint subindex = 0; 87 | for (uint i = 0; i < hlength; i ++) 88 | { 89 | if (h[i] == n0) 90 | { 91 | subindex = 1; 92 | byte nsubindex = n[subindex]; 93 | while(subindex < nlength && (i + subindex) < hlength && h[i + subindex] == nsubindex) 94 | { 95 | subindex++; 96 | } 97 | if(subindex == nlength) 98 | return int(i); 99 | } 100 | } 101 | return -1; 102 | } 103 | } 104 | 105 | // parseInt 106 | function parseInt(string self) constant returns (uint) { 107 | return parseInt(self, 0); 108 | } 109 | 110 | // parseInt(parseFloat*10^_b) 111 | function parseInt(string self, uint _b) constant returns (uint) { 112 | bytes memory bresult = bytes(self); 113 | uint mint = 0; 114 | bool decimals = false; 115 | uint bresultlength = bresult.length; 116 | byte bresulti = bresult[i]; 117 | for (uint i=0; i< bresultlength; i++){ 118 | if ((bresulti >= 48)&&(bresulti <= 57)){ 119 | if (decimals){ 120 | if (_b == 0) break; 121 | else _b--; 122 | } 123 | mint *= 10; 124 | mint += uint(bresulti) - 48; 125 | } else if (bresulti == 46) decimals = true; 126 | } 127 | if (_b > 0) mint *= 10**_b; 128 | return mint; 129 | } 130 | 131 | 132 | function concat(string self, string _b, string _c, string _d, string _e) internal constant returns (string) { 133 | bytes memory _ba = bytes(self); 134 | bytes memory _bb = bytes(_b); 135 | bytes memory _bc = bytes(_c); 136 | bytes memory _bd = bytes(_d); 137 | bytes memory _be = bytes(_e); 138 | uint _balength = _ba.length; 139 | uint _bblength = _bb.length; 140 | uint _bclength = _bc.length; 141 | uint _bdlength = _bd.length; 142 | uint _belength = _be.length; 143 | string memory abcde = new string(_balength + _bblength + _bclength + _bdlength + _belength); 144 | bytes memory babcde = bytes(abcde); 145 | uint k = 0; 146 | for (uint i = 0; i < _balength; i++) babcde[k++] = _ba[i]; 147 | for (i = 0; i < _bblength; i++) babcde[k++] = _bb[i]; 148 | for (i = 0; i < _bclength; i++) babcde[k++] = _bc[i]; 149 | for (i = 0; i < _bdlength; i++) babcde[k++] = _bd[i]; 150 | for (i = 0; i < _belength; i++) babcde[k++] = _be[i]; 151 | return string(babcde); 152 | } 153 | 154 | function concat(string self, string _b, string _c, string _d) internal constant returns (string) { 155 | return concat(self, _b, _c, _d, ""); 156 | } 157 | 158 | function concat(string self, string _b, string _c) internal constant returns (string) { 159 | return concat(self, _b, _c, "", ""); 160 | } 161 | 162 | function concat(string self, string _b) internal constant returns (string) { 163 | return concat(self, _b, "", "", ""); 164 | } 165 | 166 | } -------------------------------------------------------------------------------- /contracts/lib/ethereans/bank/Bank.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.9; 2 | 3 | 4 | contract Bank { 5 | 6 | event Withdrawn(address reciever, uint256 amount); 7 | event Deposited(address sender,uint256 value); 8 | //allow deposit and call event 9 | function deposit() payable { 10 | Deposited(msg.sender, msg.value); 11 | } 12 | 13 | //withdraw if locked and not paid, updates epoch 14 | function withdrawal(address dest, uint amount) 15 | internal { 16 | if(!dest.send(amount)) throw; 17 | Withdrawn(msg.sender, amount); 18 | } 19 | } -------------------------------------------------------------------------------- /contracts/lib/ethereans/bank/CollaborationBank.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.0; 2 | 3 | /** 4 | * Abstract contract used for recieving donations or profits 5 | * Withdraw is divided by total tokens each account owns 6 | * Unlock period allows transfers 7 | * Lock period allow withdraws 8 | * Child contract that implement minting should use modifier not_locked in minting function 9 | * Inspired by ProfitContainer and Lockable by vDice 10 | * 11 | * By Ricardo Guilherme Schmidt 12 | * Released under GPLv3 License 13 | */ 14 | 15 | import "./Bank.sol"; 16 | import "../management/EpochLocker.sol"; 17 | import "../token/LockerToken.sol"; 18 | 19 | contract CollaborationBank is Bank, EpochLocker { 20 | 21 | LockerToken public token; 22 | //used for calculating balance and for checking if account withdrawn 23 | uint256 public currentPayEpoch; 24 | //stores the balance from the lock time 25 | uint256 public epochBalance; 26 | //used for checking if account withdrawn 27 | mapping (address => uint) lastPaidOutEpoch; 28 | //events 29 | event Withdrawn(address tokenHolder, uint256 amountPaidOut); 30 | event Deposited(address donator,uint256 value); 31 | 32 | function CollaborationBank(LockerToken _token) EpochLocker(8 minutes, 12 minutes){ 33 | token = _token; 34 | 35 | } 36 | 37 | //update the balance and payout epoch 38 | modifier update_epoch { 39 | if(currentPayEpoch < CURRENT_EPOCH) { 40 | currentPayEpoch = CURRENT_EPOCH; 41 | epochBalance = this.balance; 42 | } 43 | _; 44 | } 45 | 46 | //checks if user already withdrawn 47 | modifier not_paid { 48 | if (lastPaidOutEpoch[msg.sender] == currentPayEpoch) throw; 49 | _; 50 | } 51 | 52 | //check overflow in multiply 53 | function safeMultiply(uint256 _a, uint256 _b) private { 54 | if (!(_b == 0 || ((_a * _b) / _b) == _a)) throw; 55 | } 56 | 57 | //allow deposit and call event 58 | function () 59 | payable { 60 | deposit(); 61 | } 62 | 63 | //withdraw if locked and not paid, updates epoch 64 | function withdrawal() 65 | external 66 | check_lock(true) 67 | update_epoch 68 | not_paid { 69 | uint256 _tokenBalance = token.balanceOf(msg.sender); 70 | uint256 _tokenSupply = token.totalSupply(); 71 | safeMultiply(_tokenBalance, epochBalance); 72 | lastPaidOutEpoch[msg.sender] = currentPayEpoch; 73 | if (this.balance >= epochBalance || _tokenBalance == 0 || _tokenSupply == 0) throw; 74 | super.withdrawal(msg.sender, (_tokenBalance * epochBalance) / _tokenSupply); 75 | } 76 | 77 | //if this coin owns tokens of other CollaborationBank, allow withdraw 78 | function withdrawalFrom(CollaborationBank _otherCollaborationToken) { 79 | _otherCollaborationToken.withdrawal(); 80 | } 81 | 82 | //return expected payout in lock or estimated when not locked 83 | function expectedPayout(address _tokenHolder) 84 | external 85 | constant 86 | returns (uint256 payout) { 87 | if (now < NEXT_LOCK) //unlocked, estimate 88 | payout = (token.balanceOf(_tokenHolder) * this.balance) / token.totalSupply(); 89 | else 90 | payout = (token.balanceOf(_tokenHolder) * epochBalance) / token.totalSupply(); 91 | } 92 | 93 | 94 | } 95 | -------------------------------------------------------------------------------- /contracts/lib/ethereans/management/EpochLocker.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.8; 2 | 3 | /** 4 | * Abstract contract that locks and unlock in period of a time. 5 | * 6 | */ 7 | 8 | import "lib/ethereans/management/Lockable.sol"; 9 | 10 | contract EpochLocker is Lockable { 11 | 12 | uint256 public creationTime = now; 13 | uint256 public unlockedTime = 25 days; 14 | uint256 public lockedTime = 5 days; 15 | uint256 public constant EPOCH_LENGTH = unlockedTime + lockedTime; 16 | uint256 public constant CURRENT_EPOCH = (now - creationTime) / EPOCH_LENGTH + 1; 17 | uint256 public constant NEXT_LOCK = (creationTime + CURRENT_EPOCH * unlockedTime) + (CURRENT_EPOCH - 1) * lockedTime; 18 | 19 | 20 | function EpochLocker(uint256 _unlockedTime, uint256 _lockedTime){ 21 | unlockedTime = _unlockedTime; 22 | lockedTime = _lockedTime; 23 | } 24 | 25 | //update lock value if needed or throw if unexpected lock 26 | modifier check_lock(bool lockedOnly) { 27 | if(lockedOnly){ //method allowed when locked 28 | if (NEXT_LOCK < now) { //is locked! 29 | if (!lock) setLock(true); //storage says other thing, update it. 30 | _; //continue 31 | } 32 | else { //is not locked! 33 | if (!lock) throw; //unlocked and storage already say so, throw to prevent event flood. 34 | setLock(false); //update storage 35 | return; //prevent method from running post states. 36 | } 37 | }else{ //method allowed when unlocked. 38 | if (NEXT_LOCK < now) { //is locked! 39 | if (lock) throw; //no need to update storage. 40 | setLock(true); //update storage 41 | return; //prevent method from running post states. 42 | } 43 | else { //is not locked! 44 | if (lock) setLock(false); //storage says other thing, update it. 45 | _; //continue 46 | } 47 | } 48 | } 49 | 50 | 51 | } -------------------------------------------------------------------------------- /contracts/lib/ethereans/management/Lockable.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.8; 2 | 3 | import "./Owned.sol"; 4 | 5 | contract Lockable { 6 | bool public lock = true; 7 | event Locked(bool lock); 8 | 9 | function setLock(bool _lock) internal { 10 | Locked(_lock); 11 | lock = _lock; 12 | } 13 | 14 | } -------------------------------------------------------------------------------- /contracts/lib/ethereans/management/Owned.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.8; 2 | 3 | contract Owned { 4 | address public owner= msg.sender; 5 | event NewOwner(address owner); 6 | 7 | function Owned(){ 8 | NewOwner(owner); 9 | } 10 | 11 | modifier only_owner { 12 | if (msg.sender != owner) throw; 13 | _; 14 | } 15 | 16 | function setOwner(address _owner) 17 | only_owner { 18 | owner = _owner; 19 | NewOwner(_owner); 20 | } 21 | } -------------------------------------------------------------------------------- /contracts/lib/ethereans/management/Secret.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.8; 2 | 3 | contract Secret { 4 | 5 | /** 6 | * @var token (stores the current token) 7 | */ 8 | bytes32 private token; 9 | mapping (bytes32 => bool) tokens; 10 | /** 11 | * @param secret the revealed secret 12 | * @param _token the keccak256 hash of next secret 13 | */ 14 | modifier secret(bytes32 secret, bytes32 _token){ 15 | setToken(secret,_token); 16 | _; 17 | } 18 | 19 | /** 20 | * @param _token the keccak256 hash of next secret 21 | */ 22 | function Secret(bytes32 _token){ 23 | token = _token; 24 | } 25 | 26 | /** 27 | * @notice secret use current token to replace it by new _token 28 | * @param secret the revealed secret 29 | * @param _token the keccak256 hash of next secret 30 | */ 31 | function setToken(bytes32 secret, bytes32 _token){ 32 | if(tokens[_token] == true) throw; 33 | if(keccak256(secret) != token) throw; 34 | tokens[token] = true; 35 | token = _token; 36 | } 37 | 38 | 39 | } -------------------------------------------------------------------------------- /contracts/lib/ethereans/token/AbstractToken.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.8; 2 | 3 | /** 4 | * AbstractToken ECR20-compliant token contract 5 | * Child should implement initial supply or minting and overwite base 6 | * Based on BasicCoin by Parity Team (Ethcore), 2016. 7 | * By Ricardo Guilherme Schmidt 8 | * Released under the Apache Licence 2. 9 | */ 10 | 11 | import "./Token.sol"; 12 | 13 | // AbstractToken, ECR20 tokens that all belong to the owner for sending around 14 | contract AbstractToken is Token { 15 | 16 | uint256 private decimalBase = 0; 17 | mapping (bytes => bytes) private attributes; 18 | mapping (address => Account) private accounts; 19 | event Base(uint256 decimalBase); 20 | event SetAttribute(string name, string value); 21 | event Mint(address to, uint256 value); 22 | event Destroy(address from, uint256 value); 23 | 24 | 25 | struct Decimal { 26 | uint256 value; 27 | uint256 base; 28 | } 29 | 30 | struct Account { 31 | Decimal balance; 32 | mapping (address => Decimal) allowanceOf; 33 | } 34 | 35 | // the balance should be available 36 | modifier when_owns(address _owner, uint256 _amount) { 37 | if (balanceOf(_owner) < _amount) throw; 38 | _; 39 | } 40 | 41 | // an allowance should be available 42 | modifier when_has_allowance(address _owner, address _spender, uint256 _amount) { 43 | if (allowance(_owner,_spender) < _amount) throw; 44 | _; 45 | } 46 | 47 | //correct base and balance if needed 48 | function _safeDecimals(Decimal _decimal) 49 | internal 50 | constant returns(Decimal){ 51 | if(_decimal.base != decimalBase) { 52 | if(_decimal.value > 0){ 53 | int256 baseDiff = int256(_decimal.base) - int256(decimalBase); 54 | if(baseDiff > 0){ 55 | _decimal.value *= 10**uint256(baseDiff); 56 | }else if(baseDiff < 0){ 57 | uint256 oldv = _decimal.value; 58 | uint256 newv = _decimal.value/(10**uint256(baseDiff*-1)); 59 | _decimal.value = oldv > newv ? newv : 0; 60 | } 61 | } 62 | _decimal.base = decimalBase; //update base of account 63 | } 64 | return _decimal; 65 | } 66 | 67 | //_safeDecimals wrapper for safe add; 68 | function _safeDecimalsAdd(Decimal _decimal, uint256 _value) 69 | internal 70 | constant returns(Decimal){ 71 | _decimal = _safeDecimals(_decimal); 72 | _decimal.value += _value; 73 | return _decimal; 74 | } 75 | 76 | function _safeDecimalsSub(Decimal _decimal, uint256 _value) 77 | internal 78 | constant returns(Decimal){ 79 | _decimal = _safeDecimals(_decimal); 80 | _decimal.value -= _value; 81 | return _decimal; 82 | } 83 | //_safeDecimals wrapper for safe sub; 84 | function base() 85 | constant returns(uint256) { 86 | return decimalBase; 87 | } 88 | 89 | //child may override this function to trigger changes in balance dependent storage 90 | function _balanceUpdated(address _from) 91 | internal { 92 | 93 | } 94 | 95 | /** 96 | * changes the decimal base 97 | * lowereing base remove precision of most significant digits 98 | * rising base remove precision of last significant digits 99 | */ 100 | function setDecimalBase(uint256 _decimalBase) 101 | internal { 102 | Base(_decimalBase); 103 | decimalBase = _decimalBase; 104 | } 105 | 106 | //sets attributes for wallet usage 107 | function setAttribute(string _name, string _value) 108 | internal { 109 | SetAttribute(_name,_value); 110 | if (bytes(_value).length > 0) attributes[bytes(_name)] = bytes(_value); 111 | else delete attributes[bytes(_name)]; 112 | } 113 | 114 | //read an attribute from storage 115 | function getAttribute(string _name) 116 | constant returns (string){ 117 | return string(attributes[bytes(_name)]); 118 | } 119 | 120 | // add tokens to a balance 121 | function _mint(address _to, uint256 _value) 122 | internal { 123 | if (totalSupply + _value < totalSupply) throw; //overflow: maximum totalSupply in the current base; 124 | Mint(_to, _value); 125 | totalSupply += _value; 126 | accounts[_to].balance = _safeDecimalsAdd(accounts[_to].balance,_value); 127 | _balanceUpdated(_to); 128 | } 129 | 130 | // remove tokens from a balance 131 | function _destroy(address _from, uint256 _value) 132 | internal { 133 | Destroy(_from, _value); 134 | totalSupply -= _value; 135 | accounts[_from].balance = _safeDecimalsSub(accounts[_from].balance,_value); 136 | if(accounts[_from].balance.value == 0){ 137 | delete accounts[_from]; //to reduce gas in mapping accounts 138 | } 139 | _balanceUpdated(_from); 140 | } 141 | 142 | // balance of a specific address 143 | function balanceOf(address _who) 144 | constant 145 | returns (uint256) { 146 | return _safeDecimals(accounts[_who].balance).value; 147 | } 148 | 149 | // transfer 150 | function transfer(address _to, uint256 _value) 151 | when_owns(msg.sender, _value) 152 | returns (bool) { 153 | Transfer(msg.sender, _to, _value); 154 | accounts[msg.sender].balance = _safeDecimalsSub(accounts[msg.sender].balance, _value); 155 | accounts[_to].balance = _safeDecimalsAdd(accounts[_to].balance, _value); 156 | _balanceUpdated(msg.sender); 157 | _balanceUpdated(_to); 158 | return true; 159 | } 160 | 161 | // transfer via allowance 162 | function transferFrom(address _from, address _to, uint256 _value) 163 | when_owns(_from, _value) 164 | when_has_allowance(_from, msg.sender, _value) 165 | returns (bool) { 166 | Transfer(_from, _to, _value); 167 | accounts[_from].allowanceOf[msg.sender] = _safeDecimalsSub(accounts[_from].allowanceOf[msg.sender], _value); 168 | accounts[_from].balance = _safeDecimalsSub(accounts[msg.sender].balance, _value); 169 | accounts[_to].balance = _safeDecimalsAdd(accounts[_to].balance, _value); 170 | _balanceUpdated(_from); 171 | _balanceUpdated(_to); 172 | return true; 173 | } 174 | 175 | // set allowance 176 | function approve(address _spender, uint256 _totalAllowed) 177 | returns (bool) { 178 | Approval(msg.sender, _spender, _totalAllowed); 179 | accounts[msg.sender].allowanceOf[_spender].value = _totalAllowed; 180 | accounts[msg.sender].allowanceOf[_spender].base = decimalBase; 181 | if(_totalAllowed == 0){ 182 | delete accounts[msg.sender].allowanceOf[_spender]; //lower gas in interactions 183 | } 184 | return true; 185 | } 186 | 187 | // available allowance 188 | function allowance(address _owner, address _spender) 189 | constant 190 | returns (uint256) { 191 | return _safeDecimals(accounts[_owner].allowanceOf[_spender]).value; 192 | } 193 | 194 | } 195 | -------------------------------------------------------------------------------- /contracts/lib/ethereans/token/JustifiedCollaborationToken.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.1; 2 | 3 | /** 4 | * Mintable Collaboration coin with register of reason of minting 5 | * 6 | * By Ricardo Guilherme Schmidt 7 | * Released under GPLv3 License 8 | */ 9 | 10 | import "../management/Owned.sol"; 11 | import "./AbstractToken.sol"; 12 | 13 | contract JustifiedCollaborationToken is AbstractToken, Owned { 14 | event Claim(bytes32 _data); 15 | mapping (bytes32 => Receipt) public receipts; 16 | mapping (address => bool) public minters; 17 | 18 | // storage of minting reason 19 | struct Receipt { 20 | address beneficiary; 21 | uint256 value; 22 | bool claimed; 23 | } 24 | 25 | function claim(address _beneficiary, uint256 _value, bytes32 _data) 26 | only_owner { 27 | if(receipts[_data].claimed) throw; 28 | receipts[_data] = Receipt ({beneficiary: _beneficiary, value: _value, claimed: true}); 29 | _mint(_beneficiary,_value); 30 | Claim(_data); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /contracts/lib/ethereans/token/LockerToken.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.0; 2 | 3 | /** 4 | * Abstract contract to accept lock and linked locker. 5 | * 6 | * By Ricardo Guilherme Schmidt 7 | * Released under GPLv3 License 8 | */ 9 | 10 | import "./AbstractToken.sol"; 11 | import "../management/Lockable.sol"; 12 | 13 | contract LockerToken is AbstractToken, Lockable, Owned { 14 | Lockable public locker = this; 15 | 16 | function unlinkLocker() only_owner { 17 | locker = this; 18 | } 19 | function linkLocker(Lockable _locker) only_owner { 20 | locker = _locker; 21 | } 22 | function setlock(bool _lock) only_owner { 23 | setLock(_lock); 24 | } 25 | 26 | modifier when_locked(bool value){ 27 | if (lock != value && locker.lock() != value) throw; 28 | _; 29 | } 30 | 31 | //overwrite not allow transfer during lock 32 | function transfer(address _to, uint256 _value) when_locked(true) 33 | returns (bool ok) { 34 | return super.transfer(_to,_value); 35 | } 36 | 37 | //overwrite not allow transfer during lock 38 | function transferFrom(address _from, address _to, uint256 _value) when_locked(true) 39 | returns (bool ok) { 40 | return super.transferFrom(_from,_to,_value); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /contracts/lib/ethereans/token/Token.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.8; 2 | 3 | // ECR20 standard token interface 4 | 5 | contract Token { 6 | uint256 public totalSupply; 7 | function balanceOf(address who) constant returns (uint256); 8 | function allowance(address owner, address spender) constant returns (uint256); 9 | function transfer(address to, uint256 value) returns (bool ok); 10 | function transferFrom(address from, address to, uint256 value) returns (bool ok); 11 | function approve(address spender, uint256 value) returns (bool ok); 12 | event Transfer(address indexed from, address indexed to, uint256 value); 13 | event Approval(address indexed owner, address indexed spender, uint256 value); 14 | } -------------------------------------------------------------------------------- /contracts/lib/ethereans/token/WrappedEthToken.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.0; 2 | 3 | /** 4 | * WrappedEthToken is a contract that creates 1 token por eth deposited. 5 | * 6 | * By Ricardo Guilherme Schmidt 7 | * Released under GPLv3 License 8 | */ 9 | 10 | import "./AbstractToken.sol"; 11 | 12 | contract WrappedEthToken is AbstractToken { 13 | 14 | //Minting is by depositing in the contract 15 | function () 16 | payable { 17 | deposit(); 18 | } 19 | 20 | function deposit() 21 | payable { 22 | _mint(msg.sender,msg.value); 23 | } 24 | 25 | function withdraw(uint256 _amount) 26 | when_owns (msg.sender, _amount) { 27 | _destroy(msg.sender, _amount); 28 | if(!msg.sender.send(_amount)) throw; 29 | } 30 | 31 | function withdraw() { 32 | withdraw(balanceOf(msg.sender)); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /contracts/lib/oraclize/oraclizeAPI_0.4.sol: -------------------------------------------------------------------------------- 1 | // 2 | /* 3 | Copyright (c) 2015-2016 Oraclize SRL 4 | Copyright (c) 2016 Oraclize LTD 5 | 6 | 7 | 8 | Permission is hereby granted, free of charge, to any person obtaining a copy 9 | of this software and associated documentation files (the "Software"), to deal 10 | in the Software without restriction, including without limitation the rights 11 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | copies of the Software, and to permit persons to whom the Software is 13 | furnished to do so, subject to the following conditions: 14 | 15 | 16 | 17 | The above copyright notice and this permission notice shall be included in 18 | all copies or substantial portions of the Software. 19 | 20 | 21 | 22 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 23 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 24 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 25 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 26 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 27 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 28 | THE SOFTWARE. 29 | */ 30 | 31 | pragma solidity ^0.4.0;//please import oraclizeAPI_pre0.4.sol when solidity < 0.4.0 32 | 33 | contract OraclizeI { 34 | address public cbAddress; 35 | function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id); 36 | function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id); 37 | function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id); 38 | function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id); 39 | function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id); 40 | function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id); 41 | function getPrice(string _datasource) returns (uint _dsprice); 42 | function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); 43 | function useCoupon(string _coupon); 44 | function setProofType(byte _proofType); 45 | function setConfig(bytes32 _config); 46 | function setCustomGasPrice(uint _gasPrice); 47 | } 48 | contract OraclizeAddrResolverI { 49 | function getAddress() returns (address _addr); 50 | } 51 | contract usingOraclize { 52 | uint constant day = 60*60*24; 53 | uint constant week = 60*60*24*7; 54 | uint constant month = 60*60*24*30; 55 | byte constant proofType_NONE = 0x00; 56 | byte constant proofType_TLSNotary = 0x10; 57 | byte constant proofStorage_IPFS = 0x01; 58 | uint8 constant networkID_auto = 0; 59 | uint8 constant networkID_mainnet = 1; 60 | uint8 constant networkID_testnet = 2; 61 | uint8 constant networkID_morden = 2; 62 | uint8 constant networkID_consensys = 161; 63 | 64 | OraclizeAddrResolverI OAR; 65 | 66 | OraclizeI oraclize; 67 | modifier oraclizeAPI { 68 | if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); 69 | oraclize = OraclizeI(OAR.getAddress()); 70 | _; 71 | } 72 | modifier coupon(string code){ 73 | oraclize = OraclizeI(OAR.getAddress()); 74 | oraclize.useCoupon(code); 75 | _; 76 | } 77 | 78 | function oraclize_setNetwork(uint8 networkID) internal returns(bool){ 79 | if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet 80 | OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); 81 | return true; 82 | } 83 | if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet 84 | OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); 85 | return true; 86 | } 87 | if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet 88 | OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); 89 | return true; 90 | } 91 | if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge 92 | OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); 93 | return true; 94 | } 95 | if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide 96 | OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); 97 | return true; 98 | } 99 | if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity 100 | OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); 101 | return true; 102 | } 103 | return false; 104 | } 105 | 106 | function __callback(bytes32 myid, string result) { 107 | __callback(myid, result, new bytes(0)); 108 | } 109 | function __callback(bytes32 myid, string result, bytes proof) { 110 | } 111 | 112 | function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ 113 | return oraclize.getPrice(datasource); 114 | } 115 | 116 | function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ 117 | return oraclize.getPrice(datasource, gaslimit); 118 | } 119 | 120 | function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ 121 | uint price = oraclize.getPrice(datasource); 122 | if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price 123 | return oraclize.query.value(price)(0, datasource, arg); 124 | } 125 | function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ 126 | uint price = oraclize.getPrice(datasource); 127 | if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price 128 | return oraclize.query.value(price)(timestamp, datasource, arg); 129 | } 130 | function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ 131 | uint price = oraclize.getPrice(datasource, gaslimit); 132 | if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price 133 | return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); 134 | } 135 | function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ 136 | uint price = oraclize.getPrice(datasource, gaslimit); 137 | if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price 138 | return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); 139 | } 140 | function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ 141 | uint price = oraclize.getPrice(datasource); 142 | if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price 143 | return oraclize.query2.value(price)(0, datasource, arg1, arg2); 144 | } 145 | function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ 146 | uint price = oraclize.getPrice(datasource); 147 | if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price 148 | return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); 149 | } 150 | function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ 151 | uint price = oraclize.getPrice(datasource, gaslimit); 152 | if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price 153 | return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); 154 | } 155 | function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ 156 | uint price = oraclize.getPrice(datasource, gaslimit); 157 | if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price 158 | return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); 159 | } 160 | function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ 161 | uint price = oraclize.getPrice(datasource); 162 | if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price 163 | bytes memory args = stra2cbor(argN); 164 | return oraclize.queryN.value(price)(0, datasource, args); 165 | } 166 | function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ 167 | uint price = oraclize.getPrice(datasource); 168 | if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price 169 | bytes memory args = stra2cbor(argN); 170 | return oraclize.queryN.value(price)(timestamp, datasource, args); 171 | } 172 | function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ 173 | uint price = oraclize.getPrice(datasource, gaslimit); 174 | if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price 175 | bytes memory args = stra2cbor(argN); 176 | return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); 177 | } 178 | function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ 179 | uint price = oraclize.getPrice(datasource, gaslimit); 180 | if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price 181 | bytes memory args = stra2cbor(argN); 182 | return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); 183 | } 184 | function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { 185 | string[] memory dynargs = new string[](1); 186 | dynargs[0] = args[0]; 187 | return oraclize_query(datasource, dynargs); 188 | } 189 | function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { 190 | string[] memory dynargs = new string[](1); 191 | dynargs[0] = args[0]; 192 | return oraclize_query(timestamp, datasource, dynargs); 193 | } 194 | function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { 195 | string[] memory dynargs = new string[](1); 196 | dynargs[0] = args[0]; 197 | return oraclize_query(timestamp, datasource, dynargs, gaslimit); 198 | } 199 | function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { 200 | string[] memory dynargs = new string[](1); 201 | dynargs[0] = args[0]; 202 | return oraclize_query(datasource, dynargs, gaslimit); 203 | } 204 | 205 | function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { 206 | string[] memory dynargs = new string[](2); 207 | dynargs[0] = args[0]; 208 | dynargs[1] = args[1]; 209 | return oraclize_query(datasource, dynargs); 210 | } 211 | function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { 212 | string[] memory dynargs = new string[](2); 213 | dynargs[0] = args[0]; 214 | dynargs[1] = args[1]; 215 | return oraclize_query(timestamp, datasource, dynargs); 216 | } 217 | function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { 218 | string[] memory dynargs = new string[](2); 219 | dynargs[0] = args[0]; 220 | dynargs[1] = args[1]; 221 | return oraclize_query(timestamp, datasource, dynargs, gaslimit); 222 | } 223 | function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { 224 | string[] memory dynargs = new string[](2); 225 | dynargs[0] = args[0]; 226 | dynargs[1] = args[1]; 227 | return oraclize_query(datasource, dynargs, gaslimit); 228 | } 229 | function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { 230 | string[] memory dynargs = new string[](3); 231 | dynargs[0] = args[0]; 232 | dynargs[1] = args[1]; 233 | dynargs[2] = args[2]; 234 | return oraclize_query(datasource, dynargs); 235 | } 236 | function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { 237 | string[] memory dynargs = new string[](3); 238 | dynargs[0] = args[0]; 239 | dynargs[1] = args[1]; 240 | dynargs[2] = args[2]; 241 | return oraclize_query(timestamp, datasource, dynargs); 242 | } 243 | function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { 244 | string[] memory dynargs = new string[](3); 245 | dynargs[0] = args[0]; 246 | dynargs[1] = args[1]; 247 | dynargs[2] = args[2]; 248 | return oraclize_query(timestamp, datasource, dynargs, gaslimit); 249 | } 250 | function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { 251 | string[] memory dynargs = new string[](3); 252 | dynargs[0] = args[0]; 253 | dynargs[1] = args[1]; 254 | dynargs[2] = args[2]; 255 | return oraclize_query(datasource, dynargs, gaslimit); 256 | } 257 | 258 | function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { 259 | string[] memory dynargs = new string[](4); 260 | dynargs[0] = args[0]; 261 | dynargs[1] = args[1]; 262 | dynargs[2] = args[2]; 263 | dynargs[3] = args[3]; 264 | return oraclize_query(datasource, dynargs); 265 | } 266 | function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { 267 | string[] memory dynargs = new string[](4); 268 | dynargs[0] = args[0]; 269 | dynargs[1] = args[1]; 270 | dynargs[2] = args[2]; 271 | dynargs[3] = args[3]; 272 | return oraclize_query(timestamp, datasource, dynargs); 273 | } 274 | function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { 275 | string[] memory dynargs = new string[](4); 276 | dynargs[0] = args[0]; 277 | dynargs[1] = args[1]; 278 | dynargs[2] = args[2]; 279 | dynargs[3] = args[3]; 280 | return oraclize_query(timestamp, datasource, dynargs, gaslimit); 281 | } 282 | function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { 283 | string[] memory dynargs = new string[](4); 284 | dynargs[0] = args[0]; 285 | dynargs[1] = args[1]; 286 | dynargs[2] = args[2]; 287 | dynargs[3] = args[3]; 288 | return oraclize_query(datasource, dynargs, gaslimit); 289 | } 290 | function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { 291 | string[] memory dynargs = new string[](5); 292 | dynargs[0] = args[0]; 293 | dynargs[1] = args[1]; 294 | dynargs[2] = args[2]; 295 | dynargs[3] = args[3]; 296 | dynargs[4] = args[4]; 297 | return oraclize_query(datasource, dynargs); 298 | } 299 | function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { 300 | string[] memory dynargs = new string[](5); 301 | dynargs[0] = args[0]; 302 | dynargs[1] = args[1]; 303 | dynargs[2] = args[2]; 304 | dynargs[3] = args[3]; 305 | dynargs[4] = args[4]; 306 | return oraclize_query(timestamp, datasource, dynargs); 307 | } 308 | function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { 309 | string[] memory dynargs = new string[](5); 310 | dynargs[0] = args[0]; 311 | dynargs[1] = args[1]; 312 | dynargs[2] = args[2]; 313 | dynargs[3] = args[3]; 314 | dynargs[4] = args[4]; 315 | return oraclize_query(timestamp, datasource, dynargs, gaslimit); 316 | } 317 | function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { 318 | string[] memory dynargs = new string[](5); 319 | dynargs[0] = args[0]; 320 | dynargs[1] = args[1]; 321 | dynargs[2] = args[2]; 322 | dynargs[3] = args[3]; 323 | dynargs[4] = args[4]; 324 | return oraclize_query(datasource, dynargs, gaslimit); 325 | } 326 | 327 | function oraclize_cbAddress() oraclizeAPI internal returns (address){ 328 | return oraclize.cbAddress(); 329 | } 330 | function oraclize_setProof(byte proofP) oraclizeAPI internal { 331 | return oraclize.setProofType(proofP); 332 | } 333 | function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { 334 | return oraclize.setCustomGasPrice(gasPrice); 335 | } 336 | function oraclize_setConfig(bytes32 config) oraclizeAPI internal { 337 | return oraclize.setConfig(config); 338 | } 339 | 340 | function getCodeSize(address _addr) constant internal returns(uint _size) { 341 | assembly { 342 | _size := extcodesize(_addr) 343 | } 344 | } 345 | 346 | function parseAddr(string _a) internal returns (address){ 347 | bytes memory tmp = bytes(_a); 348 | uint160 iaddr = 0; 349 | uint160 b1; 350 | uint160 b2; 351 | for (uint i=2; i<2+2*20; i+=2){ 352 | iaddr *= 256; 353 | b1 = uint160(tmp[i]); 354 | b2 = uint160(tmp[i+1]); 355 | if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; 356 | else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; 357 | if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; 358 | else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; 359 | iaddr += (b1*16+b2); 360 | } 361 | return address(iaddr); 362 | } 363 | 364 | function strCompare(string _a, string _b) internal returns (int) { 365 | bytes memory a = bytes(_a); 366 | bytes memory b = bytes(_b); 367 | uint minLength = a.length; 368 | if (b.length < minLength) minLength = b.length; 369 | for (uint i = 0; i < minLength; i ++) 370 | if (a[i] < b[i]) 371 | return -1; 372 | else if (a[i] > b[i]) 373 | return 1; 374 | if (a.length < b.length) 375 | return -1; 376 | else if (a.length > b.length) 377 | return 1; 378 | else 379 | return 0; 380 | } 381 | 382 | function indexOf(string _haystack, string _needle) internal returns (int) { 383 | bytes memory h = bytes(_haystack); 384 | bytes memory n = bytes(_needle); 385 | if(h.length < 1 || n.length < 1 || (n.length > h.length)) 386 | return -1; 387 | else if(h.length > (2**128 -1)) 388 | return -1; 389 | else 390 | { 391 | uint subindex = 0; 392 | for (uint i = 0; i < h.length; i ++) 393 | { 394 | if (h[i] == n[0]) 395 | { 396 | subindex = 1; 397 | while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) 398 | { 399 | subindex++; 400 | } 401 | if(subindex == n.length) 402 | return int(i); 403 | } 404 | } 405 | return -1; 406 | } 407 | } 408 | 409 | function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) { 410 | bytes memory _ba = bytes(_a); 411 | bytes memory _bb = bytes(_b); 412 | bytes memory _bc = bytes(_c); 413 | bytes memory _bd = bytes(_d); 414 | bytes memory _be = bytes(_e); 415 | string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); 416 | bytes memory babcde = bytes(abcde); 417 | uint k = 0; 418 | for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; 419 | for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; 420 | for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; 421 | for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; 422 | for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; 423 | return string(babcde); 424 | } 425 | 426 | function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { 427 | return strConcat(_a, _b, _c, _d, ""); 428 | } 429 | 430 | function strConcat(string _a, string _b, string _c) internal returns (string) { 431 | return strConcat(_a, _b, _c, "", ""); 432 | } 433 | 434 | function strConcat(string _a, string _b) internal returns (string) { 435 | return strConcat(_a, _b, "", "", ""); 436 | } 437 | 438 | // parseInt 439 | function parseInt(string _a) internal returns (uint) { 440 | return parseInt(_a, 0); 441 | } 442 | 443 | // parseInt(parseFloat*10^_b) 444 | function parseInt(string _a, uint _b) internal returns (uint) { 445 | bytes memory bresult = bytes(_a); 446 | uint mint = 0; 447 | bool decimals = false; 448 | for (uint i=0; i= 48)&&(bresult[i] <= 57)){ 450 | if (decimals){ 451 | if (_b == 0) break; 452 | else _b--; 453 | } 454 | mint *= 10; 455 | mint += uint(bresult[i]) - 48; 456 | } else if (bresult[i] == 46) decimals = true; 457 | } 458 | if (_b > 0) mint *= 10**_b; 459 | return mint; 460 | } 461 | 462 | function uint2str(uint i) internal returns (string){ 463 | if (i == 0) return "0"; 464 | uint j = i; 465 | uint len; 466 | while (j != 0){ 467 | len++; 468 | j /= 10; 469 | } 470 | bytes memory bstr = new bytes(len); 471 | uint k = len - 1; 472 | while (i != 0){ 473 | bstr[k--] = byte(48 + i % 10); 474 | i /= 10; 475 | } 476 | return string(bstr); 477 | } 478 | 479 | function stra2cbor(string[] arr) internal returns (bytes) { 480 | uint arrlen = arr.length; 481 | 482 | // get correct cbor output length 483 | uint outputlen = 0; 484 | bytes[] memory elemArray = new bytes[](arrlen); 485 | for (uint i = 0; i < arrlen; i++) { 486 | elemArray[i] = (bytes(arr[i])); 487 | outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types 488 | } 489 | uint ctr = 0; 490 | uint cborlen = arrlen + 0x80; 491 | outputlen += byte(cborlen).length; 492 | bytes memory res = new bytes(outputlen); 493 | 494 | while (byte(cborlen).length > ctr) { 495 | res[ctr] = byte(cborlen)[ctr]; 496 | ctr++; 497 | } 498 | for (i = 0; i < arrlen; i++) { 499 | res[ctr] = 0x5F; 500 | ctr++; 501 | for (uint x = 0; x < elemArray[i].length; x++) { 502 | // if there's a bug with larger strings, this may be the culprit 503 | if (x % 23 == 0) { 504 | uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; 505 | elemcborlen += 0x40; 506 | uint lctr = ctr; 507 | while (byte(elemcborlen).length > ctr - lctr) { 508 | res[ctr] = byte(elemcborlen)[ctr - lctr]; 509 | ctr++; 510 | } 511 | } 512 | res[ctr] = elemArray[i][x]; 513 | ctr++; 514 | } 515 | res[ctr] = 0xFF; 516 | ctr++; 517 | } 518 | return res; 519 | } 520 | } 521 | // 522 | -------------------------------------------------------------------------------- /contracts/lib/strings.sol: -------------------------------------------------------------------------------- 1 | /* 2 | * @title String & slice utility library for Solidity contracts. 3 | * @author Nick Johnson 4 | * 5 | * @dev Functionality in this library is largely implemented using an 6 | * abstraction called a 'slice'. A slice represents a part of a string - 7 | * anything from the entire string to a single character, or even no 8 | * characters at all (a 0-length slice). Since a slice only has to specify 9 | * an offset and a length, copying and manipulating slices is a lot less 10 | * expensive than copying and manipulating the strings they reference. 11 | * 12 | * To further reduce gas costs, most functions on slice that need to return 13 | * a slice modify the original one instead of allocating a new one; for 14 | * instance, `s.split(".")` will return the text up to the first '.', 15 | * modifying s to only contain the remainder of the string after the '.'. 16 | * In situations where you do not want to modify the original slice, you 17 | * can make a copy first with `.copy()`, for example: 18 | * `s.copy().split(".")`. Try and avoid using this idiom in loops; since 19 | * Solidity has no memory management, it will result in allocating many 20 | * short-lived slices that are later discarded. 21 | * 22 | * Functions that return two slices come in two versions: a non-allocating 23 | * version that takes the second slice as an argument, modifying it in 24 | * place, and an allocating version that allocates and returns the second 25 | * slice; see `nextRune` for example. 26 | * 27 | * Functions that have to copy string data will return strings rather than 28 | * slices; these can be cast back to slices for further processing if 29 | * required. 30 | * 31 | * For convenience, some functions are provided with non-modifying 32 | * variants that create a new slice and return both; for instance, 33 | * `s.splitNew('.')` leaves s unmodified, and returns two values 34 | * corresponding to the left and right parts of the string. 35 | */ 36 | pragma solidity ^0.4.11; 37 | 38 | library strings { 39 | struct slice { 40 | uint _len; 41 | uint _ptr; 42 | } 43 | 44 | function memcpy(uint dest, uint src, uint len) private { 45 | // Copy word-length chunks while possible 46 | for(; len >= 32; len -= 32) { 47 | assembly { 48 | mstore(dest, mload(src)) 49 | } 50 | dest += 32; 51 | src += 32; 52 | } 53 | 54 | // Copy remaining bytes 55 | uint mask = 256 ** (32 - len) - 1; 56 | assembly { 57 | let srcpart := and(mload(src), not(mask)) 58 | let destpart := and(mload(dest), mask) 59 | mstore(dest, or(destpart, srcpart)) 60 | } 61 | } 62 | 63 | /* 64 | * @dev Returns a slice containing the entire string. 65 | * @param self The string to make a slice from. 66 | * @return A newly allocated slice containing the entire string. 67 | */ 68 | function toSlice(string self) internal returns (slice) { 69 | uint ptr; 70 | assembly { 71 | ptr := add(self, 0x20) 72 | } 73 | return slice(bytes(self).length, ptr); 74 | } 75 | 76 | /* 77 | * @dev Returns the length of a null-terminated bytes32 string. 78 | * @param self The value to find the length of. 79 | * @return The length of the string, from 0 to 32. 80 | */ 81 | function len(bytes32 self) internal returns (uint) { 82 | uint ret; 83 | if (self == 0) 84 | return 0; 85 | if (self & 0xffffffffffffffffffffffffffffffff == 0) { 86 | ret += 16; 87 | self = bytes32(uint(self) / 0x100000000000000000000000000000000); 88 | } 89 | if (self & 0xffffffffffffffff == 0) { 90 | ret += 8; 91 | self = bytes32(uint(self) / 0x10000000000000000); 92 | } 93 | if (self & 0xffffffff == 0) { 94 | ret += 4; 95 | self = bytes32(uint(self) / 0x100000000); 96 | } 97 | if (self & 0xffff == 0) { 98 | ret += 2; 99 | self = bytes32(uint(self) / 0x10000); 100 | } 101 | if (self & 0xff == 0) { 102 | ret += 1; 103 | } 104 | return 32 - ret; 105 | } 106 | 107 | /* 108 | * @dev Returns a slice containing the entire bytes32, interpreted as a 109 | * null-termintaed utf-8 string. 110 | * @param self The bytes32 value to convert to a slice. 111 | * @return A new slice containing the value of the input argument up to the 112 | * first null. 113 | */ 114 | function toSliceB32(bytes32 self) internal returns (slice ret) { 115 | // Allocate space for `self` in memory, copy it there, and point ret at it 116 | assembly { 117 | let ptr := mload(0x40) 118 | mstore(0x40, add(ptr, 0x20)) 119 | mstore(ptr, self) 120 | mstore(add(ret, 0x20), ptr) 121 | } 122 | ret._len = len(self); 123 | } 124 | 125 | /* 126 | * @dev Returns a new slice containing the same data as the current slice. 127 | * @param self The slice to copy. 128 | * @return A new slice containing the same data as `self`. 129 | */ 130 | function copy(slice self) internal returns (slice) { 131 | return slice(self._len, self._ptr); 132 | } 133 | 134 | /* 135 | * @dev Copies a slice to a new string. 136 | * @param self The slice to copy. 137 | * @return A newly allocated string containing the slice's text. 138 | */ 139 | function toString(slice self) internal returns (string) { 140 | var ret = new string(self._len); 141 | uint retptr; 142 | assembly { retptr := add(ret, 32) } 143 | 144 | memcpy(retptr, self._ptr, self._len); 145 | return ret; 146 | } 147 | 148 | /* 149 | * @dev Returns the length in runes of the slice. Note that this operation 150 | * takes time proportional to the length of the slice; avoid using it 151 | * in loops, and call `slice.empty()` if you only need to know whether 152 | * the slice is empty or not. 153 | * @param self The slice to operate on. 154 | * @return The length of the slice in runes. 155 | */ 156 | function len(slice self) internal returns (uint) { 157 | // Starting at ptr-31 means the LSB will be the byte we care about 158 | var ptr = self._ptr - 31; 159 | var end = ptr + self._len; 160 | for (uint len = 0; ptr < end; len++) { 161 | uint8 b; 162 | assembly { b := and(mload(ptr), 0xFF) } 163 | if (b < 0x80) { 164 | ptr += 1; 165 | } else if(b < 0xE0) { 166 | ptr += 2; 167 | } else if(b < 0xF0) { 168 | ptr += 3; 169 | } else if(b < 0xF8) { 170 | ptr += 4; 171 | } else if(b < 0xFC) { 172 | ptr += 5; 173 | } else { 174 | ptr += 6; 175 | } 176 | } 177 | return len; 178 | } 179 | 180 | /* 181 | * @dev Returns true if the slice is empty (has a length of 0). 182 | * @param self The slice to operate on. 183 | * @return True if the slice is empty, False otherwise. 184 | */ 185 | function empty(slice self) internal returns (bool) { 186 | return self._len == 0; 187 | } 188 | 189 | /* 190 | * @dev Returns a positive number if `other` comes lexicographically after 191 | * `self`, a negative number if it comes before, or zero if the 192 | * contents of the two slices are equal. Comparison is done per-rune, 193 | * on unicode codepoints. 194 | * @param self The first slice to compare. 195 | * @param other The second slice to compare. 196 | * @return The result of the comparison. 197 | */ 198 | function compare(slice self, slice other) internal returns (int) { 199 | uint shortest = self._len; 200 | if (other._len < self._len) 201 | shortest = other._len; 202 | 203 | var selfptr = self._ptr; 204 | var otherptr = other._ptr; 205 | for (uint idx = 0; idx < shortest; idx += 32) { 206 | uint a; 207 | uint b; 208 | assembly { 209 | a := mload(selfptr) 210 | b := mload(otherptr) 211 | } 212 | if (a != b) { 213 | // Mask out irrelevant bytes and check again 214 | uint mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); 215 | var diff = (a & mask) - (b & mask); 216 | if (diff != 0) 217 | return int(diff); 218 | } 219 | selfptr += 32; 220 | otherptr += 32; 221 | } 222 | return int(self._len) - int(other._len); 223 | } 224 | 225 | /* 226 | * @dev Returns true if the two slices contain the same text. 227 | * @param self The first slice to compare. 228 | * @param self The second slice to compare. 229 | * @return True if the slices are equal, false otherwise. 230 | */ 231 | function equals(slice self, slice other) internal returns (bool) { 232 | return compare(self, other) == 0; 233 | } 234 | 235 | /* 236 | * @dev Extracts the first rune in the slice into `rune`, advancing the 237 | * slice to point to the next rune and returning `self`. 238 | * @param self The slice to operate on. 239 | * @param rune The slice that will contain the first rune. 240 | * @return `rune`. 241 | */ 242 | function nextRune(slice self, slice rune) internal returns (slice) { 243 | rune._ptr = self._ptr; 244 | 245 | if (self._len == 0) { 246 | rune._len = 0; 247 | return rune; 248 | } 249 | 250 | uint len; 251 | uint b; 252 | // Load the first byte of the rune into the LSBs of b 253 | assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } 254 | if (b < 0x80) { 255 | len = 1; 256 | } else if(b < 0xE0) { 257 | len = 2; 258 | } else if(b < 0xF0) { 259 | len = 3; 260 | } else { 261 | len = 4; 262 | } 263 | 264 | // Check for truncated codepoints 265 | if (len > self._len) { 266 | rune._len = self._len; 267 | self._ptr += self._len; 268 | self._len = 0; 269 | return rune; 270 | } 271 | 272 | self._ptr += len; 273 | self._len -= len; 274 | rune._len = len; 275 | return rune; 276 | } 277 | 278 | /* 279 | * @dev Returns the first rune in the slice, advancing the slice to point 280 | * to the next rune. 281 | * @param self The slice to operate on. 282 | * @return A slice containing only the first rune from `self`. 283 | */ 284 | function nextRune(slice self) internal returns (slice ret) { 285 | nextRune(self, ret); 286 | } 287 | 288 | /* 289 | * @dev Returns the number of the first codepoint in the slice. 290 | * @param self The slice to operate on. 291 | * @return The number of the first codepoint in the slice. 292 | */ 293 | function ord(slice self) internal returns (uint ret) { 294 | if (self._len == 0) { 295 | return 0; 296 | } 297 | 298 | uint word; 299 | uint len; 300 | uint div = 2 ** 248; 301 | 302 | // Load the rune into the MSBs of b 303 | assembly { word:= mload(mload(add(self, 32))) } 304 | var b = word / div; 305 | if (b < 0x80) { 306 | ret = b; 307 | len = 1; 308 | } else if(b < 0xE0) { 309 | ret = b & 0x1F; 310 | len = 2; 311 | } else if(b < 0xF0) { 312 | ret = b & 0x0F; 313 | len = 3; 314 | } else { 315 | ret = b & 0x07; 316 | len = 4; 317 | } 318 | 319 | // Check for truncated codepoints 320 | if (len > self._len) { 321 | return 0; 322 | } 323 | 324 | for (uint i = 1; i < len; i++) { 325 | div = div / 256; 326 | b = (word / div) & 0xFF; 327 | if (b & 0xC0 != 0x80) { 328 | // Invalid UTF-8 sequence 329 | return 0; 330 | } 331 | ret = (ret * 64) | (b & 0x3F); 332 | } 333 | 334 | return ret; 335 | } 336 | 337 | /* 338 | * @dev Returns the keccak-256 hash of the slice. 339 | * @param self The slice to hash. 340 | * @return The hash of the slice. 341 | */ 342 | function keccak(slice self) internal returns (bytes32 ret) { 343 | assembly { 344 | ret := sha3(mload(add(self, 32)), mload(self)) 345 | } 346 | } 347 | 348 | /* 349 | * @dev Returns true if `self` starts with `needle`. 350 | * @param self The slice to operate on. 351 | * @param needle The slice to search for. 352 | * @return True if the slice starts with the provided text, false otherwise. 353 | */ 354 | function startsWith(slice self, slice needle) internal returns (bool) { 355 | if (self._len < needle._len) { 356 | return false; 357 | } 358 | 359 | if (self._ptr == needle._ptr) { 360 | return true; 361 | } 362 | 363 | bool equal; 364 | assembly { 365 | let len := mload(needle) 366 | let selfptr := mload(add(self, 0x20)) 367 | let needleptr := mload(add(needle, 0x20)) 368 | equal := eq(sha3(selfptr, len), sha3(needleptr, len)) 369 | } 370 | return equal; 371 | } 372 | 373 | /* 374 | * @dev If `self` starts with `needle`, `needle` is removed from the 375 | * beginning of `self`. Otherwise, `self` is unmodified. 376 | * @param self The slice to operate on. 377 | * @param needle The slice to search for. 378 | * @return `self` 379 | */ 380 | function beyond(slice self, slice needle) internal returns (slice) { 381 | if (self._len < needle._len) { 382 | return self; 383 | } 384 | 385 | bool equal = true; 386 | if (self._ptr != needle._ptr) { 387 | assembly { 388 | let len := mload(needle) 389 | let selfptr := mload(add(self, 0x20)) 390 | let needleptr := mload(add(needle, 0x20)) 391 | equal := eq(sha3(selfptr, len), sha3(needleptr, len)) 392 | } 393 | } 394 | 395 | if (equal) { 396 | self._len -= needle._len; 397 | self._ptr += needle._len; 398 | } 399 | 400 | return self; 401 | } 402 | 403 | /* 404 | * @dev Returns true if the slice ends with `needle`. 405 | * @param self The slice to operate on. 406 | * @param needle The slice to search for. 407 | * @return True if the slice starts with the provided text, false otherwise. 408 | */ 409 | function endsWith(slice self, slice needle) internal returns (bool) { 410 | if (self._len < needle._len) { 411 | return false; 412 | } 413 | 414 | var selfptr = self._ptr + self._len - needle._len; 415 | 416 | if (selfptr == needle._ptr) { 417 | return true; 418 | } 419 | 420 | bool equal; 421 | assembly { 422 | let len := mload(needle) 423 | let needleptr := mload(add(needle, 0x20)) 424 | equal := eq(sha3(selfptr, len), sha3(needleptr, len)) 425 | } 426 | 427 | return equal; 428 | } 429 | 430 | /* 431 | * @dev If `self` ends with `needle`, `needle` is removed from the 432 | * end of `self`. Otherwise, `self` is unmodified. 433 | * @param self The slice to operate on. 434 | * @param needle The slice to search for. 435 | * @return `self` 436 | */ 437 | function until(slice self, slice needle) internal returns (slice) { 438 | if (self._len < needle._len) { 439 | return self; 440 | } 441 | 442 | var selfptr = self._ptr + self._len - needle._len; 443 | bool equal = true; 444 | if (selfptr != needle._ptr) { 445 | assembly { 446 | let len := mload(needle) 447 | let needleptr := mload(add(needle, 0x20)) 448 | equal := eq(sha3(selfptr, len), sha3(needleptr, len)) 449 | } 450 | } 451 | 452 | if (equal) { 453 | self._len -= needle._len; 454 | } 455 | 456 | return self; 457 | } 458 | 459 | // Returns the memory address of the first byte of the first occurrence of 460 | // `needle` in `self`, or the first byte after `self` if not found. 461 | function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { 462 | uint ptr; 463 | uint idx; 464 | 465 | if (needlelen <= selflen) { 466 | if (needlelen <= 32) { 467 | // Optimized assembly for 68 gas per byte on short strings 468 | assembly { 469 | let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) 470 | let needledata := and(mload(needleptr), mask) 471 | let end := add(selfptr, sub(selflen, needlelen)) 472 | ptr := selfptr 473 | loop: 474 | jumpi(exit, eq(and(mload(ptr), mask), needledata)) 475 | ptr := add(ptr, 1) 476 | jumpi(loop, lt(sub(ptr, 1), end)) 477 | ptr := add(selfptr, selflen) 478 | exit: 479 | } 480 | return ptr; 481 | } else { 482 | // For long needles, use hashing 483 | bytes32 hash; 484 | assembly { hash := sha3(needleptr, needlelen) } 485 | ptr = selfptr; 486 | for (idx = 0; idx <= selflen - needlelen; idx++) { 487 | bytes32 testHash; 488 | assembly { testHash := sha3(ptr, needlelen) } 489 | if (hash == testHash) 490 | return ptr; 491 | ptr += 1; 492 | } 493 | } 494 | } 495 | return selfptr + selflen; 496 | } 497 | 498 | // Returns the memory address of the first byte after the last occurrence of 499 | // `needle` in `self`, or the address of `self` if not found. 500 | function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { 501 | uint ptr; 502 | 503 | if (needlelen <= selflen) { 504 | if (needlelen <= 32) { 505 | // Optimized assembly for 69 gas per byte on short strings 506 | assembly { 507 | let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) 508 | let needledata := and(mload(needleptr), mask) 509 | ptr := add(selfptr, sub(selflen, needlelen)) 510 | loop: 511 | jumpi(ret, eq(and(mload(ptr), mask), needledata)) 512 | ptr := sub(ptr, 1) 513 | jumpi(loop, gt(add(ptr, 1), selfptr)) 514 | ptr := selfptr 515 | jump(exit) 516 | ret: 517 | ptr := add(ptr, needlelen) 518 | exit: 519 | } 520 | return ptr; 521 | } else { 522 | // For long needles, use hashing 523 | bytes32 hash; 524 | assembly { hash := sha3(needleptr, needlelen) } 525 | ptr = selfptr + (selflen - needlelen); 526 | while (ptr >= selfptr) { 527 | bytes32 testHash; 528 | assembly { testHash := sha3(ptr, needlelen) } 529 | if (hash == testHash) 530 | return ptr + needlelen; 531 | ptr -= 1; 532 | } 533 | } 534 | } 535 | return selfptr; 536 | } 537 | 538 | /* 539 | * @dev Modifies `self` to contain everything from the first occurrence of 540 | * `needle` to the end of the slice. `self` is set to the empty slice 541 | * if `needle` is not found. 542 | * @param self The slice to search and modify. 543 | * @param needle The text to search for. 544 | * @return `self`. 545 | */ 546 | function find(slice self, slice needle) internal returns (slice) { 547 | uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); 548 | self._len -= ptr - self._ptr; 549 | self._ptr = ptr; 550 | return self; 551 | } 552 | 553 | /* 554 | * @dev Modifies `self` to contain the part of the string from the start of 555 | * `self` to the end of the first occurrence of `needle`. If `needle` 556 | * is not found, `self` is set to the empty slice. 557 | * @param self The slice to search and modify. 558 | * @param needle The text to search for. 559 | * @return `self`. 560 | */ 561 | function rfind(slice self, slice needle) internal returns (slice) { 562 | uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); 563 | self._len = ptr - self._ptr; 564 | return self; 565 | } 566 | 567 | /* 568 | * @dev Splits the slice, setting `self` to everything after the first 569 | * occurrence of `needle`, and `token` to everything before it. If 570 | * `needle` does not occur in `self`, `self` is set to the empty slice, 571 | * and `token` is set to the entirety of `self`. 572 | * @param self The slice to split. 573 | * @param needle The text to search for in `self`. 574 | * @param token An output parameter to which the first token is written. 575 | * @return `token`. 576 | */ 577 | function split(slice self, slice needle, slice token) internal returns (slice) { 578 | uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); 579 | token._ptr = self._ptr; 580 | token._len = ptr - self._ptr; 581 | if (ptr == self._ptr + self._len) { 582 | // Not found 583 | self._len = 0; 584 | } else { 585 | self._len -= token._len + needle._len; 586 | self._ptr = ptr + needle._len; 587 | } 588 | return token; 589 | } 590 | 591 | /* 592 | * @dev Splits the slice, setting `self` to everything after the first 593 | * occurrence of `needle`, and returning everything before it. If 594 | * `needle` does not occur in `self`, `self` is set to the empty slice, 595 | * and the entirety of `self` is returned. 596 | * @param self The slice to split. 597 | * @param needle The text to search for in `self`. 598 | * @return The part of `self` up to the first occurrence of `delim`. 599 | */ 600 | function split(slice self, slice needle) internal returns (slice token) { 601 | split(self, needle, token); 602 | } 603 | 604 | /* 605 | * @dev Splits the slice, setting `self` to everything before the last 606 | * occurrence of `needle`, and `token` to everything after it. If 607 | * `needle` does not occur in `self`, `self` is set to the empty slice, 608 | * and `token` is set to the entirety of `self`. 609 | * @param self The slice to split. 610 | * @param needle The text to search for in `self`. 611 | * @param token An output parameter to which the first token is written. 612 | * @return `token`. 613 | */ 614 | function rsplit(slice self, slice needle, slice token) internal returns (slice) { 615 | uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); 616 | token._ptr = ptr; 617 | token._len = self._len - (ptr - self._ptr); 618 | if (ptr == self._ptr) { 619 | // Not found 620 | self._len = 0; 621 | } else { 622 | self._len -= token._len + needle._len; 623 | } 624 | return token; 625 | } 626 | 627 | /* 628 | * @dev Splits the slice, setting `self` to everything before the last 629 | * occurrence of `needle`, and returning everything after it. If 630 | * `needle` does not occur in `self`, `self` is set to the empty slice, 631 | * and the entirety of `self` is returned. 632 | * @param self The slice to split. 633 | * @param needle The text to search for in `self`. 634 | * @return The part of `self` after the last occurrence of `delim`. 635 | */ 636 | function rsplit(slice self, slice needle) internal returns (slice token) { 637 | rsplit(self, needle, token); 638 | } 639 | 640 | /* 641 | * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. 642 | * @param self The slice to search. 643 | * @param needle The text to search for in `self`. 644 | * @return The number of occurrences of `needle` found in `self`. 645 | */ 646 | function count(slice self, slice needle) internal returns (uint count) { 647 | uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; 648 | while (ptr <= self._ptr + self._len) { 649 | count++; 650 | ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; 651 | } 652 | } 653 | 654 | /* 655 | * @dev Returns True if `self` contains `needle`. 656 | * @param self The slice to search. 657 | * @param needle The text to search for in `self`. 658 | * @return True if `needle` is found in `self`, false otherwise. 659 | */ 660 | function contains(slice self, slice needle) internal returns (bool) { 661 | return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; 662 | } 663 | 664 | /* 665 | * @dev Returns a newly allocated string containing the concatenation of 666 | * `self` and `other`. 667 | * @param self The first slice to concatenate. 668 | * @param other The second slice to concatenate. 669 | * @return The concatenation of the two strings. 670 | */ 671 | function concat(slice self, slice other) internal returns (string) { 672 | var ret = new string(self._len + other._len); 673 | uint retptr; 674 | assembly { retptr := add(ret, 32) } 675 | memcpy(retptr, self._ptr, self._len); 676 | memcpy(retptr + self._len, other._ptr, other._len); 677 | return ret; 678 | } 679 | 680 | /* 681 | * @dev Joins an array of slices, using `self` as a delimiter, returning a 682 | * newly allocated string. 683 | * @param self The delimiter to use. 684 | * @param parts A list of slices to join. 685 | * @return A newly allocated string containing all the slices in `parts`, 686 | * joined with `self`. 687 | */ 688 | function join(slice self, slice[] parts) internal returns (string) { 689 | if (parts.length == 0) 690 | return ""; 691 | 692 | uint len = self._len * (parts.length - 1); 693 | for(uint i = 0; i < parts.length; i++) 694 | len += parts[i]._len; 695 | 696 | var ret = new string(len); 697 | uint retptr; 698 | assembly { retptr := add(ret, 32) } 699 | 700 | for(i = 0; i < parts.length; i++) { 701 | memcpy(retptr, parts[i]._ptr, parts[i]._len); 702 | retptr += parts[i]._len; 703 | if (i < parts.length - 1) { 704 | memcpy(retptr, self._ptr, self._len); 705 | retptr += self._len; 706 | } 707 | } 708 | 709 | return ret; 710 | } 711 | } 712 | -------------------------------------------------------------------------------- /contracts/src/BountyBank.sol: -------------------------------------------------------------------------------- 1 | import "Owned.sol"; 2 | 3 | pragma solidity ^0.4.11; 4 | 5 | contract BountyBank is Owned { 6 | 7 | enum State {CLOSED, OPEN, CLAIMED} 8 | 9 | struct Bounty { 10 | State state; 11 | uint closedAt; 12 | mapping (address => uint) deposits; 13 | mapping (address => uint) claimers; 14 | uint balance; 15 | uint points; 16 | } 17 | 18 | mapping (uint => Bounty) bounties; 19 | uint count = 0; 20 | 21 | function deposit(uint num) payable { 22 | if(bounties[num].state != State.OPEN || msg.value == 0) throw; 23 | bounties[num].deposits[msg.sender] += msg.value; 24 | bounties[num].balance += msg.value; 25 | } 26 | 27 | function withdraw(uint num) { 28 | uint value = bounties[num].deposits[msg.sender]; 29 | if(bounties[num].state != State.OPEN || value == 0) throw; 30 | delete bounties[num].deposits[msg.sender]; 31 | if(!msg.sender.send(value)) throw; 32 | } 33 | 34 | function open(uint num) only_owner { 35 | if(bounties[num].state == State.CLAIMED) throw; 36 | bounties[num].state = State.OPEN; 37 | } 38 | 39 | function setClaimer(uint num, address claimer, uint points) only_owner { 40 | if(bounties[num].state == State.CLAIMED) throw; 41 | bounties[num].claimers[claimer] += points; 42 | bounties[num].points += points; 43 | } 44 | 45 | function close(uint num, uint _closedAt) only_owner { 46 | if(bounties[num].state == State.CLAIMED) throw; 47 | bounties[num].state = State.CLOSED; 48 | bounties[num].closedAt = _closedAt; 49 | } 50 | 51 | function claim(uint num){ 52 | if (bounties[num].state == State.OPEN) throw; 53 | uint totalPoints = bounties[num].points; 54 | if(totalPoints == 0) throw; 55 | uint points = bounties[num].claimers[msg.sender]; 56 | if (points == 0) throw; 57 | delete bounties[num].claimers[msg.sender]; 58 | uint award = (bounties[num].balance / totalPoints)*points; 59 | bounties[num].points -= points; 60 | bounties[num].balance -= award; 61 | if(!msg.sender.send(award)) throw; 62 | } 63 | 64 | } -------------------------------------------------------------------------------- /contracts/src/BountyBank2.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.8; 2 | 3 | /** 4 | * DO NOT USE: under development 5 | */ 6 | 7 | import "lib/ethereans/management/Owned.sol" ; 8 | 9 | contract GitBountyBank is Owned { 10 | 11 | mapping (uint => Bounty) bounties; 12 | uint lockPeriod = 30 days; 13 | struct Bounty { 14 | bool open; 15 | uint closedAt; 16 | uint stats; 17 | uint statsClaimed; 18 | 19 | mapping (uint=>Account) deposits; 20 | uint depositIndex; 21 | uint deposited; 22 | mapping (bytes20=>Account) claims; 23 | uint claimed; 24 | 25 | } 26 | 27 | struct Account { 28 | address owner; 29 | uint amount; 30 | } 31 | 32 | 33 | function balanceOf(uint num) constant returns(uint){ 34 | return bounties[num].deposited - bounties[num].claimed; 35 | } 36 | 37 | function setState(uint num, uint stats, bool open, uint closedAt){ 38 | if (bounties[num].stats >= stats) throw; 39 | bounties[num].stats = stats; 40 | bounties[num].open = open; 41 | bounties[num].closedAt = closedAt; 42 | } 43 | 44 | function deposit(uint num, address account) 45 | payable returns (uint reciept) { 46 | if (!bounties[num].open) throw; 47 | reciept = bounties[num].depositIndex; 48 | bounties[num].deposits[reciept] = Account({ owner: account, amount: msg.value }); 49 | bounties[num].depositIndex++; 50 | bounties[num].deposited += msg.value; 51 | return reciept; 52 | } 53 | 54 | function withdraw(uint num, uint reciept, address account) internal { 55 | if (!bounties[num].open || now < bounties[num].closedAt+lockPeriod) throw; 56 | if(bounties[num].deposits[reciept].owner != account) throw; 57 | uint avaliable = bounties[num].deposits[reciept].amount; 58 | delete bounties[num].deposits[reciept]; 59 | bounties[num].deposited -= avaliable; 60 | if(!account.send(avaliable)) throw; 61 | } 62 | 63 | function claim(uint num, uint stats, bytes20 commitid, address beneficiary) internal { 64 | if (bounties[num].open || now < bounties[num].closedAt+lockPeriod) throw; 65 | uint balance = bounties[num].deposited - bounties[num].claimed; 66 | uint remainingStats = bounties[num].stats - bounties[num].statsClaimed; 67 | bounties[num].claims[commitid] = Account({ owner: beneficiary, amount: stats }); 68 | //bounties[num].claimed+= 69 | 70 | } 71 | 72 | } -------------------------------------------------------------------------------- /contracts/src/DGitDB.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.4.8; 2 | 3 | /** 4 | * Contract that oracle github API 5 | * 6 | * GitHubRegistry is a storage contract 7 | * 8 | * By Ricardo Guilherme Schmidt 9 | * Released under GPLv3 License 10 | */ 11 | 12 | import "lib/ethereans/management/Owned.sol"; 13 | 14 | contract DGitDBI { 15 | function addRepository(uint256 _id, uint256 _owner, string _name, string _full_name, address _addr); 16 | function addUser(uint256 _id, string _login, uint8 _type, address _addr); 17 | function setRepositoryAddress(uint256 _repositoryId, address _repositoryAddress); 18 | function setRepositoryName(uint256 _repositoryId, string _full_name, string _name); 19 | function setUserAddress(uint userId, address account); 20 | function setUserName(uint256 _userId, string _name); 21 | function getRepositoryId(string _full_name) constant returns (uint256); 22 | function getRepositoryName(uint256 _id) constant returns (string); 23 | function getRepositoryAddress(uint256 _id) constant returns(address); 24 | function getRepositoryAddress(string _full_name) constant returns(address); 25 | function getUserAddress(uint256 _id) constant returns(address); 26 | function getUserAddress(string _login) constant returns(address); 27 | function getClaimedHead(uint256 _repoid) constant returns (bytes20); 28 | function getClaimedHead(string _full_name) constant returns (bytes20); 29 | function getClaimedTail(uint256 _repoid) constant returns (bytes20); 30 | function setClaimed(uint256 _repoid, bytes20 _head, bytes20 _tail, uint points); 31 | function setPending(uint256 _repoid, uint256 _userid, uint256 _points); 32 | function setPending(string _full_name, uint256 _userid, uint256 _points); 33 | function claimPending(uint256 _repoid, uint256 _userid) returns (uint256 points); 34 | } 35 | 36 | contract DGitDB is DGitDBI, Owned { 37 | 38 | mapping (string => uint256) repositoryNames; 39 | mapping (string => uint256) userNames; 40 | mapping (uint256 => Repository) repositories; 41 | mapping (uint256 => User) users; 42 | 43 | struct Repository { 44 | uint256 owner; 45 | string name; 46 | string full_name; 47 | address addr; 48 | uint points; 49 | bytes20 head; 50 | bytes20 tail; 51 | mapping (uint256 => uint256) pending; 52 | } 53 | 54 | 55 | struct User { 56 | string login; 57 | uint8 utype; 58 | address addr; 59 | } 60 | 61 | function setClaimed(uint256 _repoid, bytes20 _head, bytes20 _tail, uint _points) 62 | only_owner { 63 | repositories[_repoid].head = _head; 64 | repositories[_repoid].tail = _tail; 65 | repositories[_repoid].points += _points; 66 | } 67 | function setPending(uint256 _repoid, uint256 _userid, uint256 _points){ 68 | repositories[_repoid].pending[_userid] += _points; 69 | } 70 | function setPending(string _full_name, uint256 _userid, uint256 _points){ 71 | repositories[repositoryNames[_full_name]].pending[_userid] += _points; 72 | } 73 | function claimPending(uint256 _repoid, uint256 _userid) returns (uint256 points){ 74 | points = repositories[_repoid].pending[_userid]; 75 | delete repositories[_repoid].pending[_userid]; 76 | } 77 | 78 | function getClaimedHead(uint256 _repoid) constant returns (bytes20){ 79 | return repositories[_repoid].head; 80 | } 81 | function getClaimedHead(string _full_name) constant returns (bytes20){ 82 | return repositories[repositoryNames[_full_name]].head; 83 | } 84 | function getClaimedTail(uint256 _repoid) constant returns (bytes20){ 85 | return repositories[_repoid].tail; 86 | } 87 | 88 | function addRepository(uint256 _id, uint256 _owner, string _name, string _full_name, address _addr) only_owner { 89 | repositories[_id] = Repository({owner:_owner,name:_name,full_name:_full_name,addr:_addr,points:0,head:0,tail:0}); 90 | repositoryNames[_full_name] = _id; 91 | } 92 | 93 | function addUser(uint256 _id, string _login, uint8 _utype, address _addr) only_owner{ 94 | users[_id] = User({login:_login,utype:_utype,addr:_addr}); 95 | userNames[_login] = _id; 96 | } 97 | 98 | function setRepositoryAddress(uint256 _repositoryId, address _repositoryAddress) 99 | only_owner { 100 | repositories[_repositoryId].addr = _repositoryAddress; 101 | } 102 | 103 | function setUserAddress(uint userId, address account) 104 | only_owner{ 105 | users[userId].addr = account; 106 | } 107 | function setRepositoryName(uint256 _repositoryId, string _full_name, string _name) 108 | only_owner { 109 | delete repositoryNames[repositories[_repositoryId].full_name]; 110 | repositoryNames[_full_name] = _repositoryId; 111 | repositories[_repositoryId].full_name = _full_name; 112 | repositories[_repositoryId].name = _full_name; 113 | } 114 | 115 | function setUserName(uint256 _userId, string _name) 116 | only_owner { 117 | delete userNames[users[_userId].login]; 118 | userNames[_name] = _userId; 119 | users[_userId].login = _name; 120 | } 121 | 122 | function getUserAddress(uint256 _id) constant returns(address){ 123 | return users[_id].addr; 124 | } 125 | function getUserAddress(string _login) constant returns(address){ 126 | return users[userNames[_login]].addr; 127 | } 128 | function getRepositoryAddress(uint256 _id) constant returns(address){ 129 | return repositories[_id].addr; 130 | } 131 | function getRepositoryAddress(string _full_name) constant returns(address){ 132 | return repositories[repositoryNames[_full_name]].addr; 133 | } 134 | function getRepositoryId(string _full_name) constant returns (uint256){ 135 | return repositoryNames[_full_name]; 136 | } 137 | function getRepositoryName(uint256 _id) constant returns (string){ 138 | return repositories[_id].full_name; 139 | } 140 | 141 | } 142 | 143 | library DBFactory { 144 | function newStorage() returns (DGitDBI){ 145 | return new DGitDB(); 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /contracts/src/GitHubAPIReg.sol: -------------------------------------------------------------------------------- 1 | /** 2 | * GitHubAPIReg.sol 3 | * Abstract Logic for GitHubOracle Registries. 4 | * Ricardo Guilherme Schmidt <3esmit@gmail.com> 5 | */ 6 | import "Owned.sol"; 7 | import "oraclizeAPI_0.4.sol"; 8 | import "strings.sol"; 9 | 10 | pragma solidity ^0.4.11; 11 | 12 | contract GitHubAPIReg is Owned, usingOraclize { 13 | using strings for string; 14 | using strings for strings.slice; 15 | 16 | string cred = ""; 17 | 18 | event OracleEvent(bytes32 myid, string result, bytes proof); 19 | 20 | function GitHubAPIReg(){ 21 | oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS); 22 | } 23 | 24 | //owner management 25 | function setAPICredentials(string _client_id, string _client_secret) only_owner { 26 | strings.slice [] memory cm = new strings.slice[](5); 27 | cm[0] = strings.toSlice("?client_id="); 28 | cm[1] = _client_id.toSlice(); 29 | cm[2] = strings.toSlice("&client_secret="); 30 | cm[4] = _client_secret.toSlice(); 31 | cred = strings.toSlice("").join(cm); 32 | } 33 | 34 | function clearAPICredentials() only_owner { 35 | cred = ""; 36 | } 37 | 38 | function getNextString(bytes _str, uint8 _pos) internal constant returns (string, uint8) { 39 | uint8 start = 0; 40 | uint8 end = 0; 41 | uint strl =_str.length; 42 | for (;strl > _pos; _pos++) { 43 | if (_str[_pos] == '"'){ //Found quotation mark 44 | if(_str[_pos-1] != '\\'){ //is not escaped 45 | end = start == 0 ? 0: _pos; 46 | start = start == 0 ? (_pos+1) : start; 47 | if(end > 0) break; 48 | } 49 | } 50 | } 51 | bytes memory str = new bytes(end-start); 52 | for(_pos=0; _pos _pos; _pos++) { 64 | byte bp = _str[_pos]; 65 | if (bp == ','){ //Find ends 66 | _pos++; break; 67 | }else if ((bp >= 48)&&(bp <= 57)){ //only ASCII numbers 68 | val *= 10; 69 | val += uint(bp) - 48; 70 | } 71 | } 72 | return (val,_pos); 73 | } 74 | 75 | function getNextAddr(bytes _str, uint8 _pos) internal constant returns (address, uint8){ 76 | uint160 iaddr = 0; 77 | uint strl =_str.length; 78 | for(;strl > _pos; _pos++){ 79 | byte bp = _str[_pos]; 80 | if (bp == '0'){ 81 | if (_str[_pos+1] == 'x'){ 82 | for (_pos=_pos+2; _pos<2+2*20; _pos+=2){ 83 | iaddr *= 256; 84 | iaddr += (uint160(hexVal(uint160(_str[_pos])))*16+uint160(hexVal(uint160(_str[_pos+1])))); 85 | } 86 | _pos++; 87 | break; 88 | } 89 | }else if (bp == ','){ 90 | _pos++; 91 | break; 92 | } 93 | } 94 | return (address(iaddr),_pos); 95 | } 96 | 97 | function hexVal(uint val) internal constant returns (uint){ 98 | return val - (val < 58 ? 48 : (val < 97 ? 55 : 87)); 99 | } 100 | 101 | } -------------------------------------------------------------------------------- /contracts/src/GitHubOracle.sol: -------------------------------------------------------------------------------- 1 | /** 2 | * GitHubOracle.sol 3 | * Contract that oracle github API 4 | * GitHubOracle register users and create GitHubToken contracts 5 | * Registration requires user create a gist with only their account address 6 | * GitHubOracle will create one GitHubToken contract per repository 7 | * GitHubToken mint tokens by commit only for registered users in GitHubOracle 8 | * GitHubToken is a LockableCoin, that accept donatations and can be withdrawn by Token Holders 9 | * The lookups are done by Oraclize that charge a small fee 10 | * The contract itself will never charge any fee 11 | * 12 | * By Ricardo Guilherme Schmidt 13 | * Released under GPLv3 License 14 | */ 15 | 16 | import "oraclizeAPI_0.4.sol"; 17 | import "Owned.sol"; 18 | import "./GitHubUserReg.sol"; 19 | import "./GitHubRepositoryReg.sol"; 20 | import "./GitHubPoints.sol"; 21 | 22 | pragma solidity ^0.4.11; 23 | 24 | contract GitHubOracle is Owned, DGitI { 25 | 26 | GitHubUserReg public userReg; 27 | GitHubRepositoryReg public repositoryReg; 28 | GitHubPoints public gitHubPoints; 29 | 30 | mapping (uint256 => Repository) repositories; 31 | mapping (uint256 => mapping (uint256 => uint256)) pending; 32 | 33 | modifier oraclized { 34 | if(msg.sender != address(gitHubPoints)) throw; 35 | _; 36 | } 37 | 38 | struct Repository { 39 | string head; 40 | string tail; 41 | mapping (string => string) pending; 42 | } 43 | 44 | function initialize() only_owner { 45 | if(address(userReg) == 0x0){ 46 | userReg = GHUserReg.create(); 47 | }else if(address(repositoryReg) == 0x0){ 48 | repositoryReg = GHRepoReg.create(); 49 | }else if(address(gitHubPoints) == 0x0){ 50 | gitHubPoints = GHPoints.create(); 51 | }else throw; 52 | } 53 | 54 | function update(string _repository, string _token) payable { 55 | uint256 repoId = repositoryReg.getId(_repository); 56 | if(repoId == 0) throw; 57 | gitHubPoints.update.value(msg.value)(_repository, "master", repositories[repoId].head,_token); 58 | } 59 | 60 | function issue(string _repository, string _issue, string _token) payable { 61 | gitHubPoints.issue.value(msg.value)(_repository,_issue,_token); 62 | } 63 | 64 | function __pendingScan(uint256 _projectId, string _lastCommit, string _pendingTail) oraclized { 65 | repositories[_projectId].pending[_pendingTail] = _lastCommit; 66 | } 67 | 68 | function __setHead(uint256 _projectId, string _head) oraclized { 69 | repositories[_projectId].head = _head; 70 | } 71 | 72 | function __setTail(uint256 _projectId, string _tail) oraclized { 73 | repositories[_projectId].tail = _tail; 74 | } 75 | 76 | function __setIssue(uint256 _projectId, uint256 _issueId, bool _state, uint256 _closedAt) oraclized { 77 | GitRepositoryI repo = GitRepositoryI(repositoryReg.getAddr(_projectId)); 78 | repo.setBounty(_issueId, _state, _closedAt); 79 | } 80 | 81 | function __setIssuePoints(uint256 _projectId, uint256 _issueId, uint256 _userId, uint256 _points) oraclized { 82 | GitRepositoryI repo = GitRepositoryI(repositoryReg.getAddr(_projectId)); 83 | repo.setBountyPoints(_issueId, userReg.getAddr(_userId), _points); 84 | } 85 | 86 | event NewPoints(uint repoId, uint userId, uint total, bool claimed); 87 | 88 | function __newPoints(uint _repoId, uint _userId, uint _points) 89 | only_owner { 90 | GitRepositoryI repoaddr = GitRepositoryI(repositoryReg.getAddr(_repoId)); 91 | bool claimed = repoaddr.claim(userReg.getAddr(_userId), _points); 92 | if(!claimed){ //try to claim points 93 | pending[_userId][_repoId] += _points; //set as a pending points 94 | } 95 | NewPoints(_repoId, _userId, _points, claimed); 96 | } 97 | 98 | //claims pending points 99 | function claimPending(uint _repoId, uint _userId){ 100 | GitRepositoryI repoaddr = GitRepositoryI(repositoryReg.getAddr(_repoId)); 101 | uint total = pending[_userId][_repoId]; 102 | delete pending[_userId][_repoId]; 103 | if(repoaddr.claim(userReg.getAddr(_userId), total)) { 104 | NewPoints(_repoId,_userId,total,true); 105 | } else throw; 106 | } 107 | 108 | } -------------------------------------------------------------------------------- /contracts/src/GitHubPoints.sol: -------------------------------------------------------------------------------- 1 | import "oraclizeAPI_0.4.sol"; 2 | import "Owned.sol"; 3 | import "strings.sol"; 4 | 5 | pragma solidity ^0.4.11; 6 | 7 | contract DGitI { 8 | function __setHead(uint256 projectId, string head); 9 | function __setTail(uint256 projectId, string tail); 10 | function __newPoints(uint256 projectId, uint256 userId, uint total); 11 | function __pendingScan(uint256 projectId, string lastCommit, string pendingTail); 12 | function __setIssue(uint256 projectId, uint256 issueId, bool state, uint256 closedAt); 13 | function __setIssuePoints(uint256 projectId, uint256 issueId, uint256 userId, uint256 points); 14 | } 15 | 16 | contract GitHubPoints is Owned, usingOraclize{ 17 | 18 | using strings for string; 19 | using strings for strings.slice; 20 | 21 | string private cred = ""; 22 | string private script = ""; 23 | 24 | enum Command { UPDATE, RESUME, ISSUE } 25 | mapping (bytes32 => Command) command; //temporary db enumerating oraclize calls 26 | mapping (bytes32 => string) lastCommits; //temporary db for oraclize commit token claim calls 27 | 28 | //stores temporary data for oraclize repository commit claim 29 | struct CommitClaim { 30 | string repository; 31 | bytes20 commitid; 32 | } 33 | 34 | function update(string _repository, string _branch, string _lastCommit, string _cred) payable only_owner { 35 | if(bytes(_cred).length == 0) _cred = cred; 36 | bytes32 ocid = oraclize_query("nested", _query_update(_repository,_branch,_lastCommit,_cred)); 37 | command[ocid] = Command.UPDATE; 38 | lastCommits[ocid] = _lastCommit; 39 | } 40 | 41 | function resume(string _repository, string _branch, string _lastCommit, string _limitCommit, string _cred) 42 | payable only_owner { 43 | if(bytes(_cred).length == 0) _cred = cred; 44 | bytes32 ocid = oraclize_query("nested", _query_resume(_repository,_branch,_lastCommit,_limitCommit,_cred)); 45 | command[ocid] = Command.RESUME; 46 | lastCommits[ocid] = _lastCommit; 47 | } 48 | 49 | function issue(string _repository, string _issue, string _cred) 50 | payable only_owner { 51 | if(bytes(_cred).length == 0) _cred = cred; 52 | command[ocid] = Command.ISSUE; 53 | bytes32 ocid = oraclize_query("nested", _query_issue(_repository,_issue,_cred)); 54 | } 55 | 56 | event OracleEvent(bytes32 myid, string result, bytes proof); 57 | //oraclize response callback 58 | function __callback(bytes32 myid, string result, bytes proof) { 59 | OracleEvent(myid, result, proof); 60 | if (msg.sender != oraclize.cbAddress()) throw; 61 | Command comm = command[myid]; 62 | if(comm == Command.UPDATE) { 63 | _update(lastCommits[myid], result); 64 | }else if(comm == Command.ISSUE) { 65 | _issue(result); 66 | }else if (comm == Command.RESUME) { 67 | _resume(lastCommits[myid], result); 68 | delete lastCommits[myid]; 69 | } 70 | delete command[myid]; 71 | } 72 | 73 | function _update(string _lastCommit, string result) internal { 74 | DGitI dGit = DGitI(owner); 75 | bytes memory v = bytes(result); 76 | uint8 pos = 0; 77 | string memory temp; 78 | uint256 projectId; 79 | (projectId,pos) = getNextUInt(v,pos); 80 | (temp,pos) = getNextString(v,pos); //branch 81 | (temp,pos) = getNextString(v,pos); //head 82 | dGit.__setHead(projectId,temp); //head 83 | 84 | (temp,pos) = getNextString(v,pos); //tail 85 | if(bytes(_lastCommit).length == 0){ 86 | dGit.__setTail(projectId,temp); 87 | } 88 | if (sha3(_lastCommit) != sha3(temp)){ //update didn't reached _lastCommit 89 | dGit.__pendingScan(projectId,_lastCommit,temp); 90 | } 91 | uint numAuthors; 92 | (numAuthors,pos) = getNextUInt(v,pos); 93 | uint userId; 94 | uint points; 95 | for(uint i; i < numAuthors; i++){ 96 | (userId,pos) = getNextUInt(v,pos); 97 | (points,pos) = getNextUInt(v,pos); 98 | dGit.__newPoints(projectId,userId,points); 99 | } 100 | } 101 | 102 | function _resume(string _lastCommit, string result) internal { 103 | DGitI dGit = DGitI(owner); 104 | bytes memory v = bytes(result); 105 | uint8 pos = 0; 106 | string memory temp; 107 | uint256 projectId; 108 | (projectId,pos) = getNextUInt(v,pos); 109 | string memory branch; 110 | (branch,pos) = getNextString(v,pos); 111 | string memory head; 112 | (head,pos) = getNextString(v,pos); 113 | string memory tail; 114 | (tail,pos) = getNextString(v,pos); 115 | dGit.__setTail(projectId,tail); 116 | uint numAuthors; 117 | (numAuthors,pos) = getNextUInt(v,pos); 118 | uint userId; 119 | uint points; 120 | for(uint i; i < numAuthors; i++){ 121 | (userId,pos) = getNextUInt(v,pos); 122 | (points,pos) = getNextUInt(v,pos); 123 | dGit.__newPoints(projectId,userId,points); 124 | } 125 | } 126 | 127 | function _issue(string result) internal { 128 | DGitI dGit = DGitI(owner); 129 | bytes memory v = bytes(result); 130 | uint8 pos = 0; 131 | string memory temp; 132 | uint256 projectId; 133 | (projectId,pos) = getNextUInt(v,pos); 134 | uint256 issueId; 135 | (issueId,pos) = getNextUInt(v,pos); 136 | bool state; 137 | (temp,pos) = getNextString(v,pos); 138 | state = (sha3("open") == sha3(temp)); 139 | uint256 closedAt; 140 | (closedAt,pos) = getNextUInt(v,pos); 141 | uint numAuthors; 142 | (numAuthors,pos) = getNextUInt(v,pos); 143 | uint userId; 144 | uint points; 145 | dGit.__setIssue(projectId,issueId,state,closedAt); 146 | for(uint i; i < numAuthors; i++){ 147 | (userId,pos) = getNextUInt(v,pos); 148 | (points,pos) = getNextUInt(v,pos); 149 | dGit.__setIssuePoints(projectId,issueId,userId,points); 150 | } 151 | } 152 | 153 | //owner management 154 | function GitHubPoints(string _script){ 155 | script = _script; 156 | oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS); 157 | } 158 | 159 | function setAPICredentials(string _client_id_comma_client_secret) only_owner { 160 | cred = _client_id_comma_client_secret; 161 | } 162 | 163 | function setScript(string _script) only_owner{ 164 | script = _script; 165 | } 166 | 167 | function clearAPICredentials() only_owner { 168 | cred = ""; 169 | } 170 | 171 | function _query_script(string command, string args, string cred) internal returns (string) { 172 | strings.slice memory comma = strings.toSlice("', '"); 173 | strings.slice [] memory cm = new strings.slice[](4); 174 | cm[0] = script.toSlice(); 175 | cm[1] = command.toSlice(); 176 | cm[2] = args.toSlice(); 177 | cm[3] = cred.toSlice(); 178 | string memory array = comma.join(cm); 179 | cm = new strings.slice[](3); 180 | cm[0] = strings.toSlice("[computation] ['"); 181 | cm[1] = array.toSlice(); 182 | cm[2] = strings.toSlice("']"); 183 | return strings.toSlice("").join(cm); 184 | } 185 | 186 | function _query_update(string _repository, string _branch, string _lastCommit, string _cred) internal returns (string) { 187 | strings.slice memory comma = strings.toSlice(","); 188 | strings.slice [] memory cm = new strings.slice[](3); 189 | cm[0] = _repository.toSlice(); 190 | cm[1] = _branch.toSlice(); 191 | cm[2] = _lastCommit.toSlice(); 192 | return _query_script("update",comma.join(cm),_cred); 193 | } 194 | 195 | function _query_resume(string _repository, string _branch, string _lastCommit, string _limitCommit, string _cred) internal constant returns (string){ 196 | strings.slice memory comma = strings.toSlice(","); 197 | strings.slice [] memory cm = new strings.slice[](4); 198 | cm[0] = _repository.toSlice(); 199 | cm[1] = _branch.toSlice(); 200 | cm[2] = _lastCommit.toSlice(); 201 | cm[3] = _limitCommit.toSlice(); 202 | return _query_script("resume",comma.join(cm),_cred); 203 | } 204 | 205 | function _query_issue(string _repository, string _issue, string _cred) internal returns(string){ 206 | strings.slice memory comma = strings.toSlice(","); 207 | strings.slice [] memory cm = new strings.slice[](2); 208 | cm[0] = _repository.toSlice(); 209 | cm[1] = _issue.toSlice(); 210 | return _query_script("resume",comma.join(cm),_cred); 211 | } 212 | 213 | 214 | function toBytes20(string memory source) internal constant returns (bytes20 result) { 215 | assembly { 216 | result := mload(add(source, 20)) 217 | } 218 | } 219 | 220 | function toString(bytes20 self) internal constant returns (string) { 221 | bytes memory bytesString = new bytes(20); 222 | uint charCount = 0; 223 | for (uint j = 0; j < 20; j++) { 224 | byte char = byte(bytes20(uint(self) * 2 ** (8 * j))); 225 | if (char != 0) { 226 | bytesString[charCount] = char; 227 | charCount++; 228 | } 229 | } 230 | bytes memory bytesStringTrimmed = new bytes(charCount); 231 | for (j = 0; j < charCount; j++) { 232 | bytesStringTrimmed[j] = bytesString[j]; 233 | } 234 | return string(bytesStringTrimmed); 235 | } 236 | 237 | function getNextString(bytes _str, uint8 _pos) internal constant returns (string, uint8) { 238 | uint8 start = 0; 239 | uint8 end = 0; 240 | uint strl =_str.length; 241 | for (;strl > _pos; _pos++) { 242 | if (_str[_pos] == '"'){ //Found quotation mark 243 | if(_str[_pos-1] != '\\'){ //is not escaped 244 | end = start == 0 ? 0: _pos; 245 | start = start == 0 ? (_pos+1) : start; 246 | if(end > 0) break; 247 | } 248 | } 249 | } 250 | bytes memory str = new bytes(end-start); 251 | for(_pos=0; _pos _pos; _pos++) { 263 | byte bp = _str[_pos]; 264 | if (bp == ','){ //Find ends 265 | _pos++; break; 266 | }else if ((bp >= 48)&&(bp <= 57)){ //only ASCII numbers 267 | val *= 10; 268 | val += uint(bp) - 48; 269 | } 270 | } 271 | return (val,_pos); 272 | } 273 | } 274 | 275 | library GHPoints { 276 | 277 | function create() returns (GitHubPoints){ 278 | return new GitHubPoints(""); 279 | } 280 | 281 | } -------------------------------------------------------------------------------- /contracts/src/GitHubRepositoryReg.sol: -------------------------------------------------------------------------------- 1 | /** 2 | * GitHubRepositoryReg.sol 3 | * Registers the master branch of a Repository for GitHubOracle tracking. 4 | * Ricardo Guilherme Schmidt <3esmit@gmail.com> 5 | */ 6 | 7 | import "./GitHubAPIReg.sol"; 8 | import "./NameRegistry.sol"; 9 | import "./GitRepository.sol"; 10 | import "strings.sol"; 11 | 12 | pragma solidity ^0.4.11; 13 | 14 | contract GitHubRepositoryReg is NameRegistry, GitHubAPIReg { 15 | using strings for string; 16 | using strings for strings.slice; 17 | 18 | mapping (uint256 => Repository) public repositories; 19 | 20 | event NewRepository(address addr, uint256 projectId, string full_name, string default_branch); 21 | 22 | struct Repository { 23 | address addr; 24 | string name; 25 | string branch; 26 | } 27 | 28 | function register(string _repository, string _cred) payable { 29 | if(bytes(_cred).length == 0) _cred = cred; 30 | uint gas = getAddr(_repository) == 0x00? 4000000 : 1000000; 31 | oraclize_query("URL", _query_script(_repository,_cred), gas); 32 | } 33 | 34 | function getAddr(uint256 _id) public constant returns(address addr) { 35 | return repositories[_id].addr; 36 | } 37 | 38 | function getName(address _addr) public constant returns(string name){ 39 | return repositories[indexes[sha3(_addr)]].name; 40 | } 41 | 42 | function getAddr(string _name) public constant returns(address addr) { 43 | return repositories[indexes[sha3(_name)]].addr; 44 | } 45 | 46 | function getBranch(uint256 _id) public constant returns(string branch) { 47 | return repositories[_id].branch; 48 | } 49 | 50 | //oraclize response callback 51 | function __callback(bytes32 myid, string result, bytes proof) { 52 | OracleEvent(myid,result,proof); 53 | if (msg.sender != oraclize.cbAddress()){ 54 | throw; 55 | }else { 56 | _setRepository(result); 57 | } 58 | } 59 | 60 | function _setRepository(string result) internal //[85743750, "ethereans/TheEtherian", "master"] 61 | { 62 | bytes memory v = bytes(result); 63 | uint8 pos = 0; 64 | uint256 projectId; 65 | (projectId,pos) = getNextUInt(v,pos); 66 | string memory full_name; 67 | (full_name,pos) = getNextString(v,pos); 68 | string memory default_branch; 69 | (default_branch,pos) = getNextString(v,pos); 70 | address repoAddr = repositories[projectId].addr; 71 | if(repoAddr == 0x0){ 72 | GitRepositoryI repo = GitFactory.newGitRepository(projectId, full_name); 73 | repo.setOwner(owner); 74 | repoAddr = address(repo); 75 | indexes[sha3(repoAddr)] = projectId; 76 | indexes[sha3(full_name)] = projectId; 77 | NewRepository(repoAddr, projectId, full_name, default_branch); 78 | repositories[projectId] = Repository({addr: repoAddr, name: full_name, branch: default_branch}); 79 | }else{ 80 | bytes32 _new = sha3(full_name); 81 | bytes32 _old = sha3(repositories[projectId].name); 82 | if(_new != _old){ 83 | _updateIndex(_old, _new); 84 | } 85 | } 86 | } 87 | //internal helper functions 88 | function _query_script(string _repository, string _cred) internal returns (string) { 89 | strings.slice [] memory cm = new strings.slice[](5); 90 | cm[0] = strings.toSlice("json(https://api.github.com/repos/"); 91 | cm[1] = _repository.toSlice(); 92 | cm[2] = _cred.toSlice(); 93 | cm[4] = strings.toSlice(").$.id,full_name,default_branch"); 94 | return strings.toSlice("").join(cm); 95 | } 96 | } 97 | library GHRepoReg { 98 | 99 | function create() returns (GitHubRepositoryReg){ 100 | return new GitHubRepositoryReg(); 101 | } 102 | 103 | } -------------------------------------------------------------------------------- /contracts/src/GitHubUserReg.sol: -------------------------------------------------------------------------------- 1 | /** 2 | * GitHubUserReg.sol 3 | * Registers GitHub user login to an address 4 | * Ricardo Guilherme Schmidt <3esmit@gmail.com> 5 | */ 6 | import "GitHubAPIReg.sol"; 7 | import "NameRegistry.sol"; 8 | import "strings.sol"; 9 | 10 | pragma solidity ^0.4.11; 11 | 12 | contract GitHubUserReg is NameRegistry, GitHubAPIReg { 13 | using strings for string; 14 | using strings for strings.slice; 15 | 16 | mapping (bytes32 => UserClaim) userClaim; //temporary db for oraclize user register queries 17 | mapping (uint256 => User) users; 18 | 19 | event RegisterUpdated(string name); 20 | 21 | //stores temporary data for oraclize user register request 22 | struct UserClaim { 23 | address sender; 24 | string login; 25 | } 26 | 27 | struct User { 28 | address addr; 29 | string login; 30 | } 31 | 32 | function register(string _github_user, string _gistid, string _cred) payable { 33 | if(bytes(_cred).length == 0) _cred = cred; 34 | bytes32 ocid = oraclize_query("nested", _query_script(_github_user, _gistid,_cred)); 35 | userClaim[ocid] = UserClaim({sender: msg.sender, login: _github_user}); 36 | } 37 | 38 | function getAddr(uint256 _id) public constant returns(address addr) { 39 | return users[_id].addr; 40 | } 41 | 42 | function getName(address _addr) public constant returns(string name){ 43 | return users[indexes[sha3(_addr)]].login; 44 | } 45 | 46 | function getAddr(string _name) public constant returns(address addr) { 47 | return users[indexes[sha3(_name)]].addr; 48 | } 49 | 50 | //oraclize response callback 51 | function __callback(bytes32 myid, string result, bytes proof) { 52 | OracleEvent(myid, result, proof); 53 | if (msg.sender != oraclize.cbAddress()){ 54 | throw; 55 | }else { 56 | _register(myid, result); 57 | } 58 | } 59 | 60 | function _register(bytes32 myid, string result) internal { 61 | bytes memory v = bytes(result); 62 | uint8 pos = 0; 63 | address addrLoaded; 64 | string memory login; 65 | uint256 userId; 66 | (addrLoaded,pos) = getNextAddr(v,pos); 67 | (login,pos) = getNextString(v,pos); 68 | (userId,pos) = getNextUInt(v,pos); 69 | if(userClaim[myid].sender == addrLoaded && sha3(userClaim[myid].login) == sha3(login)){ 70 | RegisterUpdated(login); 71 | if(users[userId].addr != 0x0){ 72 | delete indexes[sha3(users[userId].login)]; 73 | delete indexes[sha3(users[userId].addr)]; 74 | } 75 | indexes[sha3(addrLoaded)] = userId; 76 | indexes[sha3(login)] = userId; 77 | users[userId].addr = addrLoaded; 78 | users[userId].login = login; 79 | } 80 | delete userClaim[myid]; //should always be deleted 81 | } 82 | 83 | function _query_script(string _github_user, string _gistid, string _cred) internal returns (string) { 84 | strings.slice [] memory cm = new strings.slice[](8); 85 | cm[0] = strings.toSlice("[identity] ${[URL] https://gist.githubusercontent.com/"); 86 | cm[1] = _github_user.toSlice(); 87 | cm[2] = strings.toSlice("/"); 88 | cm[3] = _gistid.toSlice(); 89 | cm[4] = strings.toSlice("/raw/register.txt}, ${[URL] json(https://api.github.com/gists/"); 90 | cm[5] = _gistid.toSlice(); 91 | cm[6] = _cred.toSlice(); 92 | cm[7] = strings.toSlice(").owner.[login,id]}"); 93 | return strings.toSlice("").join(cm); 94 | } 95 | 96 | } 97 | 98 | library GHUserReg{ 99 | 100 | function create() returns (GitHubUserReg){ 101 | return new GitHubUserReg(); 102 | } 103 | 104 | } -------------------------------------------------------------------------------- /contracts/src/GitRepository.sol: -------------------------------------------------------------------------------- 1 | /** 2 | * Contract that mint tokens by github commit stats 3 | * 4 | * GitHubOracle register users and create GitHubToken contracts 5 | * Registration requires user create a gist with only their account address 6 | * GitHubOracle will create one GitHubToken contract per repository 7 | * GitHubToken mint tokens by commit only for registered users in GitHubOracle 8 | * GitHubToken is a LockableCoin, that accept donatations and can be withdrawn by Token Holders 9 | * The lookups are done by Oraclize that charge a small fee 10 | * The contract itself will never charge any fee 11 | * 12 | * By Ricardo Guilherme Schmidt 13 | * Released under GPLv3 License 14 | */ 15 | 16 | import "CollaborationBank.sol"; 17 | import "Owned.sol"; 18 | import "./BountyBank.sol"; 19 | import "./GitRepositoryToken.sol"; 20 | 21 | pragma solidity ^0.4.11; 22 | 23 | contract GitRepositoryI is Owned{ 24 | function claim(address _user, uint _total) returns (bool) ; 25 | function setBounty(uint256 _issueId, bool _state, uint256 _closedAt); 26 | function setBountyPoints(uint256 _issueId, address _claimer, uint256 _points); 27 | } 28 | 29 | contract GitRepository is GitRepositoryI { 30 | 31 | GitRepositoryToken public token; 32 | CollaborationBank public donationBank; 33 | BountyBank public bountyBank; 34 | mapping (address=>uint) donators; 35 | 36 | string public name; 37 | uint256 public uid; 38 | 39 | function () payable { 40 | donationBank.deposit(); 41 | donators[msg.sender] += msg.value; 42 | } 43 | 44 | function GitRepository(uint256 _uid, string _name) { 45 | uid = _uid; 46 | name = _name; 47 | token = new GitRepositoryToken(_name); 48 | donationBank = new CollaborationBank(token); 49 | token.linkLocker(donationBank); 50 | bountyBank = new BountyBank(); 51 | } 52 | 53 | //oracle claim request 54 | function claim(address _user, uint _total) 55 | only_owner returns (bool) { 56 | if(!token.lock() && _user != 0x0){ 57 | token.mint(_user, _total); 58 | return true; 59 | }else{ 60 | return false; 61 | } 62 | } 63 | 64 | function setBounty(uint256 _issueId, bool _state, uint256 _closedAt) only_owner { 65 | if (_state) bountyBank.open(_issueId); 66 | else bountyBank.close(_issueId,_closedAt); 67 | } 68 | 69 | function setBountyPoints(uint256 _issueId, address _claimer, uint256 _points) only_owner { 70 | bountyBank.setClaimer(_issueId,_claimer,_points); 71 | } 72 | 73 | } 74 | 75 | library GitFactory { 76 | 77 | function newGitRepository(uint256 _uid, string _name) returns (GitRepositoryI){ 78 | GitRepository repo = new GitRepository(_uid,_name); 79 | return repo; 80 | } 81 | 82 | } -------------------------------------------------------------------------------- /contracts/src/GitRepositoryToken.sol: -------------------------------------------------------------------------------- 1 | /** 2 | * Contract that mint tokens by github commit stats 3 | * 4 | * GitHubOracle register users and create GitHubToken contracts 5 | * Registration requires user create a gist with only their account address 6 | * GitHubOracle will create one GitHubToken contract per repository 7 | * GitHubToken mint tokens by commit only for registered users in GitHubOracle 8 | * GitHubToken is a LockableCoin, that accept donatations and can be withdrawn by Token Holders 9 | * The lookups are done by Oraclize that charge a small fee 10 | * The contract itself will never charge any fee 11 | * 12 | * By Ricardo Guilherme Schmidt 13 | * Released under GPLv3 License 14 | */ 15 | 16 | import "LockerToken.sol"; 17 | import "Owned.sol"; 18 | 19 | pragma solidity ^0.4.11; 20 | 21 | contract GitRepositoryToken is LockerToken { 22 | 23 | function GitRepositoryToken(string _repository) { 24 | setAttribute("name", _repository); 25 | setAttribute("symbol", "GIT"); 26 | setDecimalBase(0); 27 | } 28 | 29 | function mint(address _who, uint256 _value) 30 | only_owner when_locked(false) { 31 | _mint(_who,_value); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /contracts/src/NameRegistry.sol: -------------------------------------------------------------------------------- 1 | /** 2 | * NameRegistry.sol 3 | * Interface for Name Registries. 4 | * Ricardo Guilherme Schmidt <3esmit@gmail.com> 5 | */ 6 | pragma solidity ^0.4.11; 7 | 8 | contract NameRegistry { 9 | function getAddr(uint256 _id) public constant returns(address addr); 10 | function getAddr(string _name) public constant returns(address addr); 11 | function getName(address _addr) public constant returns(string name); 12 | 13 | mapping (bytes32 => uint256) indexes; 14 | 15 | function getId(address _addr) public constant returns(uint256 id){ 16 | return indexes[sha3(_addr)]; 17 | } 18 | 19 | function getId(string _name) public constant returns(uint256 id) { 20 | return indexes[sha3(_name)]; 21 | } 22 | 23 | function _updateIndex(bytes32 _old, bytes32 _new) internal { 24 | indexes[_new] = indexes[_old]; 25 | delete indexes[_old]; 26 | } 27 | } -------------------------------------------------------------------------------- /contracts/src/oraclize/oraclizeAPI_0.4.sol: -------------------------------------------------------------------------------- 1 | // 2 | /* 3 | Copyright (c) 2015-2016 Oraclize SRL 4 | Copyright (c) 2016 Oraclize LTD 5 | 6 | 7 | 8 | Permission is hereby granted, free of charge, to any person obtaining a copy 9 | of this software and associated documentation files (the "Software"), to deal 10 | in the Software without restriction, including without limitation the rights 11 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | copies of the Software, and to permit persons to whom the Software is 13 | furnished to do so, subject to the following conditions: 14 | 15 | 16 | 17 | The above copyright notice and this permission notice shall be included in 18 | all copies or substantial portions of the Software. 19 | 20 | 21 | 22 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 23 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 24 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 25 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 26 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 27 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 28 | THE SOFTWARE. 29 | */ 30 | 31 | pragma solidity ^0.4.0;//please import oraclizeAPI_pre0.4.sol when solidity < 0.4.0 32 | 33 | contract OraclizeI { 34 | address public cbAddress; 35 | function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id); 36 | function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id); 37 | function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id); 38 | function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id); 39 | function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id); 40 | function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id); 41 | function getPrice(string _datasource) returns (uint _dsprice); 42 | function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); 43 | function useCoupon(string _coupon); 44 | function setProofType(byte _proofType); 45 | function setConfig(bytes32 _config); 46 | function setCustomGasPrice(uint _gasPrice); 47 | } 48 | contract OraclizeAddrResolverI { 49 | function getAddress() returns (address _addr); 50 | } 51 | contract usingOraclize { 52 | uint constant day = 60*60*24; 53 | uint constant week = 60*60*24*7; 54 | uint constant month = 60*60*24*30; 55 | byte constant proofType_NONE = 0x00; 56 | byte constant proofType_TLSNotary = 0x10; 57 | byte constant proofStorage_IPFS = 0x01; 58 | uint8 constant networkID_auto = 0; 59 | uint8 constant networkID_mainnet = 1; 60 | uint8 constant networkID_testnet = 2; 61 | uint8 constant networkID_morden = 2; 62 | uint8 constant networkID_consensys = 161; 63 | 64 | OraclizeAddrResolverI OAR; 65 | 66 | OraclizeI oraclize; 67 | modifier oraclizeAPI { 68 | if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); 69 | oraclize = OraclizeI(OAR.getAddress()); 70 | _; 71 | } 72 | modifier coupon(string code){ 73 | oraclize = OraclizeI(OAR.getAddress()); 74 | oraclize.useCoupon(code); 75 | _; 76 | } 77 | 78 | function oraclize_setNetwork(uint8 networkID) internal returns(bool){ 79 | if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet 80 | OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); 81 | return true; 82 | } 83 | if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet 84 | OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); 85 | return true; 86 | } 87 | if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet 88 | OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); 89 | return true; 90 | } 91 | if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge 92 | OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); 93 | return true; 94 | } 95 | if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide 96 | OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); 97 | return true; 98 | } 99 | if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity 100 | OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); 101 | return true; 102 | } 103 | return false; 104 | } 105 | 106 | function __callback(bytes32 myid, string result) { 107 | __callback(myid, result, new bytes(0)); 108 | } 109 | function __callback(bytes32 myid, string result, bytes proof) { 110 | } 111 | 112 | function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ 113 | return oraclize.getPrice(datasource); 114 | } 115 | 116 | function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ 117 | return oraclize.getPrice(datasource, gaslimit); 118 | } 119 | 120 | function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ 121 | uint price = oraclize.getPrice(datasource); 122 | if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price 123 | return oraclize.query.value(price)(0, datasource, arg); 124 | } 125 | function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ 126 | uint price = oraclize.getPrice(datasource); 127 | if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price 128 | return oraclize.query.value(price)(timestamp, datasource, arg); 129 | } 130 | function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ 131 | uint price = oraclize.getPrice(datasource, gaslimit); 132 | if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price 133 | return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); 134 | } 135 | function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ 136 | uint price = oraclize.getPrice(datasource, gaslimit); 137 | if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price 138 | return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); 139 | } 140 | function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ 141 | uint price = oraclize.getPrice(datasource); 142 | if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price 143 | return oraclize.query2.value(price)(0, datasource, arg1, arg2); 144 | } 145 | function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ 146 | uint price = oraclize.getPrice(datasource); 147 | if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price 148 | return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); 149 | } 150 | function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ 151 | uint price = oraclize.getPrice(datasource, gaslimit); 152 | if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price 153 | return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); 154 | } 155 | function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ 156 | uint price = oraclize.getPrice(datasource, gaslimit); 157 | if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price 158 | return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); 159 | } 160 | function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ 161 | uint price = oraclize.getPrice(datasource); 162 | if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price 163 | bytes memory args = stra2cbor(argN); 164 | return oraclize.queryN.value(price)(0, datasource, args); 165 | } 166 | function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ 167 | uint price = oraclize.getPrice(datasource); 168 | if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price 169 | bytes memory args = stra2cbor(argN); 170 | return oraclize.queryN.value(price)(timestamp, datasource, args); 171 | } 172 | function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ 173 | uint price = oraclize.getPrice(datasource, gaslimit); 174 | if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price 175 | bytes memory args = stra2cbor(argN); 176 | return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); 177 | } 178 | function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ 179 | uint price = oraclize.getPrice(datasource, gaslimit); 180 | if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price 181 | bytes memory args = stra2cbor(argN); 182 | return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); 183 | } 184 | function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { 185 | string[] memory dynargs = new string[](1); 186 | dynargs[0] = args[0]; 187 | return oraclize_query(datasource, dynargs); 188 | } 189 | function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { 190 | string[] memory dynargs = new string[](1); 191 | dynargs[0] = args[0]; 192 | return oraclize_query(timestamp, datasource, dynargs); 193 | } 194 | function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { 195 | string[] memory dynargs = new string[](1); 196 | dynargs[0] = args[0]; 197 | return oraclize_query(timestamp, datasource, dynargs, gaslimit); 198 | } 199 | function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { 200 | string[] memory dynargs = new string[](1); 201 | dynargs[0] = args[0]; 202 | return oraclize_query(datasource, dynargs, gaslimit); 203 | } 204 | 205 | function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { 206 | string[] memory dynargs = new string[](2); 207 | dynargs[0] = args[0]; 208 | dynargs[1] = args[1]; 209 | return oraclize_query(datasource, dynargs); 210 | } 211 | function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { 212 | string[] memory dynargs = new string[](2); 213 | dynargs[0] = args[0]; 214 | dynargs[1] = args[1]; 215 | return oraclize_query(timestamp, datasource, dynargs); 216 | } 217 | function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { 218 | string[] memory dynargs = new string[](2); 219 | dynargs[0] = args[0]; 220 | dynargs[1] = args[1]; 221 | return oraclize_query(timestamp, datasource, dynargs, gaslimit); 222 | } 223 | function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { 224 | string[] memory dynargs = new string[](2); 225 | dynargs[0] = args[0]; 226 | dynargs[1] = args[1]; 227 | return oraclize_query(datasource, dynargs, gaslimit); 228 | } 229 | function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { 230 | string[] memory dynargs = new string[](3); 231 | dynargs[0] = args[0]; 232 | dynargs[1] = args[1]; 233 | dynargs[2] = args[2]; 234 | return oraclize_query(datasource, dynargs); 235 | } 236 | function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { 237 | string[] memory dynargs = new string[](3); 238 | dynargs[0] = args[0]; 239 | dynargs[1] = args[1]; 240 | dynargs[2] = args[2]; 241 | return oraclize_query(timestamp, datasource, dynargs); 242 | } 243 | function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { 244 | string[] memory dynargs = new string[](3); 245 | dynargs[0] = args[0]; 246 | dynargs[1] = args[1]; 247 | dynargs[2] = args[2]; 248 | return oraclize_query(timestamp, datasource, dynargs, gaslimit); 249 | } 250 | function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { 251 | string[] memory dynargs = new string[](3); 252 | dynargs[0] = args[0]; 253 | dynargs[1] = args[1]; 254 | dynargs[2] = args[2]; 255 | return oraclize_query(datasource, dynargs, gaslimit); 256 | } 257 | 258 | function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { 259 | string[] memory dynargs = new string[](4); 260 | dynargs[0] = args[0]; 261 | dynargs[1] = args[1]; 262 | dynargs[2] = args[2]; 263 | dynargs[3] = args[3]; 264 | return oraclize_query(datasource, dynargs); 265 | } 266 | function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { 267 | string[] memory dynargs = new string[](4); 268 | dynargs[0] = args[0]; 269 | dynargs[1] = args[1]; 270 | dynargs[2] = args[2]; 271 | dynargs[3] = args[3]; 272 | return oraclize_query(timestamp, datasource, dynargs); 273 | } 274 | function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { 275 | string[] memory dynargs = new string[](4); 276 | dynargs[0] = args[0]; 277 | dynargs[1] = args[1]; 278 | dynargs[2] = args[2]; 279 | dynargs[3] = args[3]; 280 | return oraclize_query(timestamp, datasource, dynargs, gaslimit); 281 | } 282 | function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { 283 | string[] memory dynargs = new string[](4); 284 | dynargs[0] = args[0]; 285 | dynargs[1] = args[1]; 286 | dynargs[2] = args[2]; 287 | dynargs[3] = args[3]; 288 | return oraclize_query(datasource, dynargs, gaslimit); 289 | } 290 | function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { 291 | string[] memory dynargs = new string[](5); 292 | dynargs[0] = args[0]; 293 | dynargs[1] = args[1]; 294 | dynargs[2] = args[2]; 295 | dynargs[3] = args[3]; 296 | dynargs[4] = args[4]; 297 | return oraclize_query(datasource, dynargs); 298 | } 299 | function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { 300 | string[] memory dynargs = new string[](5); 301 | dynargs[0] = args[0]; 302 | dynargs[1] = args[1]; 303 | dynargs[2] = args[2]; 304 | dynargs[3] = args[3]; 305 | dynargs[4] = args[4]; 306 | return oraclize_query(timestamp, datasource, dynargs); 307 | } 308 | function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { 309 | string[] memory dynargs = new string[](5); 310 | dynargs[0] = args[0]; 311 | dynargs[1] = args[1]; 312 | dynargs[2] = args[2]; 313 | dynargs[3] = args[3]; 314 | dynargs[4] = args[4]; 315 | return oraclize_query(timestamp, datasource, dynargs, gaslimit); 316 | } 317 | function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { 318 | string[] memory dynargs = new string[](5); 319 | dynargs[0] = args[0]; 320 | dynargs[1] = args[1]; 321 | dynargs[2] = args[2]; 322 | dynargs[3] = args[3]; 323 | dynargs[4] = args[4]; 324 | return oraclize_query(datasource, dynargs, gaslimit); 325 | } 326 | 327 | function oraclize_cbAddress() oraclizeAPI internal returns (address){ 328 | return oraclize.cbAddress(); 329 | } 330 | function oraclize_setProof(byte proofP) oraclizeAPI internal { 331 | return oraclize.setProofType(proofP); 332 | } 333 | function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { 334 | return oraclize.setCustomGasPrice(gasPrice); 335 | } 336 | function oraclize_setConfig(bytes32 config) oraclizeAPI internal { 337 | return oraclize.setConfig(config); 338 | } 339 | 340 | function getCodeSize(address _addr) constant internal returns(uint _size) { 341 | assembly { 342 | _size := extcodesize(_addr) 343 | } 344 | } 345 | 346 | function parseAddr(string _a) internal returns (address){ 347 | bytes memory tmp = bytes(_a); 348 | uint160 iaddr = 0; 349 | uint160 b1; 350 | uint160 b2; 351 | for (uint i=2; i<2+2*20; i+=2){ 352 | iaddr *= 256; 353 | b1 = uint160(tmp[i]); 354 | b2 = uint160(tmp[i+1]); 355 | if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; 356 | else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; 357 | if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; 358 | else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; 359 | iaddr += (b1*16+b2); 360 | } 361 | return address(iaddr); 362 | } 363 | 364 | function strCompare(string _a, string _b) internal returns (int) { 365 | bytes memory a = bytes(_a); 366 | bytes memory b = bytes(_b); 367 | uint minLength = a.length; 368 | if (b.length < minLength) minLength = b.length; 369 | for (uint i = 0; i < minLength; i ++) 370 | if (a[i] < b[i]) 371 | return -1; 372 | else if (a[i] > b[i]) 373 | return 1; 374 | if (a.length < b.length) 375 | return -1; 376 | else if (a.length > b.length) 377 | return 1; 378 | else 379 | return 0; 380 | } 381 | 382 | function indexOf(string _haystack, string _needle) internal returns (int) { 383 | bytes memory h = bytes(_haystack); 384 | bytes memory n = bytes(_needle); 385 | if(h.length < 1 || n.length < 1 || (n.length > h.length)) 386 | return -1; 387 | else if(h.length > (2**128 -1)) 388 | return -1; 389 | else 390 | { 391 | uint subindex = 0; 392 | for (uint i = 0; i < h.length; i ++) 393 | { 394 | if (h[i] == n[0]) 395 | { 396 | subindex = 1; 397 | while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) 398 | { 399 | subindex++; 400 | } 401 | if(subindex == n.length) 402 | return int(i); 403 | } 404 | } 405 | return -1; 406 | } 407 | } 408 | 409 | function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) { 410 | bytes memory _ba = bytes(_a); 411 | bytes memory _bb = bytes(_b); 412 | bytes memory _bc = bytes(_c); 413 | bytes memory _bd = bytes(_d); 414 | bytes memory _be = bytes(_e); 415 | string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); 416 | bytes memory babcde = bytes(abcde); 417 | uint k = 0; 418 | for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; 419 | for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; 420 | for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; 421 | for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; 422 | for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; 423 | return string(babcde); 424 | } 425 | 426 | function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { 427 | return strConcat(_a, _b, _c, _d, ""); 428 | } 429 | 430 | function strConcat(string _a, string _b, string _c) internal returns (string) { 431 | return strConcat(_a, _b, _c, "", ""); 432 | } 433 | 434 | function strConcat(string _a, string _b) internal returns (string) { 435 | return strConcat(_a, _b, "", "", ""); 436 | } 437 | 438 | // parseInt 439 | function parseInt(string _a) internal returns (uint) { 440 | return parseInt(_a, 0); 441 | } 442 | 443 | // parseInt(parseFloat*10^_b) 444 | function parseInt(string _a, uint _b) internal returns (uint) { 445 | bytes memory bresult = bytes(_a); 446 | uint mint = 0; 447 | bool decimals = false; 448 | for (uint i=0; i= 48)&&(bresult[i] <= 57)){ 450 | if (decimals){ 451 | if (_b == 0) break; 452 | else _b--; 453 | } 454 | mint *= 10; 455 | mint += uint(bresult[i]) - 48; 456 | } else if (bresult[i] == 46) decimals = true; 457 | } 458 | if (_b > 0) mint *= 10**_b; 459 | return mint; 460 | } 461 | 462 | function uint2str(uint i) internal returns (string){ 463 | if (i == 0) return "0"; 464 | uint j = i; 465 | uint len; 466 | while (j != 0){ 467 | len++; 468 | j /= 10; 469 | } 470 | bytes memory bstr = new bytes(len); 471 | uint k = len - 1; 472 | while (i != 0){ 473 | bstr[k--] = byte(48 + i % 10); 474 | i /= 10; 475 | } 476 | return string(bstr); 477 | } 478 | 479 | function stra2cbor(string[] arr) internal returns (bytes) { 480 | uint arrlen = arr.length; 481 | 482 | // get correct cbor output length 483 | uint outputlen = 0; 484 | bytes[] memory elemArray = new bytes[](arrlen); 485 | for (uint i = 0; i < arrlen; i++) { 486 | elemArray[i] = (bytes(arr[i])); 487 | outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types 488 | } 489 | uint ctr = 0; 490 | uint cborlen = arrlen + 0x80; 491 | outputlen += byte(cborlen).length; 492 | bytes memory res = new bytes(outputlen); 493 | 494 | while (byte(cborlen).length > ctr) { 495 | res[ctr] = byte(cborlen)[ctr]; 496 | ctr++; 497 | } 498 | for (i = 0; i < arrlen; i++) { 499 | res[ctr] = 0x5F; 500 | ctr++; 501 | for (uint x = 0; x < elemArray[i].length; x++) { 502 | // if there's a bug with larger strings, this may be the culprit 503 | if (x % 23 == 0) { 504 | uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; 505 | elemcborlen += 0x40; 506 | uint lctr = ctr; 507 | while (byte(elemcborlen).length > ctr - lctr) { 508 | res[ctr] = byte(elemcborlen)[ctr - lctr]; 509 | ctr++; 510 | } 511 | } 512 | res[ctr] = elemArray[i][x]; 513 | ctr++; 514 | } 515 | res[ctr] = 0xFF; 516 | ctr++; 517 | } 518 | return res; 519 | } 520 | } 521 | // 522 | -------------------------------------------------------------------------------- /ethereum.json: -------------------------------------------------------------------------------- 1 | { 2 | "contracts": "contracts", 3 | 4 | "deploy": ["DGit"], 5 | 6 | "plugins": { 7 | "oraclize": { 8 | "networkID": 161, 9 | "loadRealData": true 10 | } 11 | }, 12 | 13 | "env": { 14 | "block": { 15 | "coinbase" : "0xdedb49385ad5b94a16f236a6890cf9e0b1e30392", 16 | "difficulty" : "0x0100", 17 | "gasLimit" : 6061924 , 18 | "gasPrice": 40000000000 19 | }, 20 | "accounts": { 21 | "0xdedb49385ad5b94a16f236a6890cf9e0b1e30392": { 22 | "balance": 100000000000000000000000000000000000000000000000000000000000000 , 23 | "nonce": "0x1cf", 24 | "pkey": "0x974f963ee4571e86e5f9bc3b493e453db9c15e5bd19829a4ef9a790de0da0015", 25 | "default": true 26 | }, 27 | "0x1081108d14493ead0d4071cc757688ed7b111c32": { 28 | "balance": 1000000000000000000000000000000000000000000000000000000 , 29 | "nonce": "0x1cf", 30 | "pkey": "0x6321991cf5102acf1efd6085da03b398a56cdc887b38acb1ba1452a50bc79343", 31 | "default": false 32 | } 33 | } 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /scenarios/InitRegAddClaim.yaml: -------------------------------------------------------------------------------- 1 | # 2 | # Scenario1 3 | # 4 | # Created on: 27/03/2017 03:30:55 5 | # 6 | 7 | # Call method initialize() 8 | - from: '0xdedb49385ad5b94a16f236a6890cf9e0b1e30392' 9 | to: '0x086ca7abad7f9773db72e2efd83dd22f5f408862' 10 | value: '0x0' 11 | call: initialize() 12 | args: [] 13 | 14 | # Call method register(string,string) 15 | - from: '0xdedb49385ad5b94a16f236a6890cf9e0b1e30392' 16 | to: '0x086ca7abad7f9773db72e2efd83dd22f5f408862' 17 | value: '0x0' 18 | call: 'register(string,string)' 19 | args: 20 | - 3esmit 21 | - 31a58f2ddf2258697cce1b969e7c298b 22 | 23 | # Call method addRepository(string) 24 | - from: '0xdedb49385ad5b94a16f236a6890cf9e0b1e30392' 25 | to: '0x086ca7abad7f9773db72e2efd83dd22f5f408862' 26 | value: '0x8ac7230489e80000' 27 | call: addRepository(string) 28 | args: 29 | - status-im/github-oracle 30 | 31 | # Call method claimCommit(string,string) 32 | - from: '0xdedb49385ad5b94a16f236a6890cf9e0b1e30392' 33 | to: '0x086ca7abad7f9773db72e2efd83dd22f5f408862' 34 | value: '0x0' 35 | call: 'claimCommit(string,string)' 36 | args: 37 | - status-im/github-oracle 38 | - 3c461c5bfe3107923a13270f7037854f1ae8ca36 39 | -------------------------------------------------------------------------------- /scripts/github-oracle/.Dockerfile.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/status-im/github-oracle/c1555916f6b152b84448745728bd38c04440bc22/scripts/github-oracle/.Dockerfile.swp -------------------------------------------------------------------------------- /scripts/github-oracle/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:14.04 2 | RUN apt-get update && apt-get install -y python 3 | ADD github_oracle.py github_oracle.py 4 | MAINTAINER Ricardo “3esmit@gmail.com” 5 | CMD python github_oracle.py -------------------------------------------------------------------------------- /scripts/github-oracle/github_oracle.py: -------------------------------------------------------------------------------- 1 | """Process information from GitHubAPI""" 2 | import sys 3 | import os 4 | import json 5 | import urllib2 6 | import datetime 7 | from collections import defaultdict 8 | 9 | def logmsg(msg): 10 | """Logs a message into proof.""" 11 | sys.stderr.write("[GitHubOracle] "+msg+" \n") 12 | 13 | class GitHubAPI: 14 | """Authentication and API Requests.""" 15 | auth = 0 16 | 17 | def oauth(self, code): 18 | """Exchanges code for token.""" 19 | req = urllib2.Request("https://github.com/login/oauth/access_token") 20 | req.add_header("Accept", "application/json") 21 | req.add_header("client_id", self.client) 22 | req.add_header("client_secret", self.secret) 23 | req.add_header("code", code) 24 | response = urllib2.urlopen(req) 25 | rjs = json.load(response) 26 | try: 27 | logmsg("OAuth success:" + rjs['scope'] + "/" + rjs['token_type']) 28 | return rjs['access_token'] 29 | except KeyError: 30 | logmsg("OAuth error " + rjs['error'] + ":" + rjs['error_description']) 31 | logmsg(rjs['error_uri']) 32 | sys.exit("403 Forbidden") 33 | 34 | def __init__(self): 35 | self.argn = int(os.environ['ARGN']) 36 | if self.argn > 2: 37 | autharg = [x.strip() for x in os.environ['ARG2'].split(',')] 38 | if len(autharg) == 3: #is token 39 | logmsg("Using OAuth") 40 | self.client = autharg[0] 41 | self.secret = autharg[1] 42 | self.token = self.oauth(autharg[2]) 43 | self.auth = 2 44 | elif len(autharg) == 2: #is secret 45 | logmsg("Using Secret Mode") 46 | self.client = autharg[0] 47 | self.secret = autharg[1] 48 | self.auth = 1 49 | elif len(autharg) == 1 and len(autharg[0]) > 0: 50 | logmsg("Using Token") 51 | self.token = autharg[0] 52 | self.auth = 2 53 | else: 54 | logmsg("Anonymous API") 55 | self.auth = 0 56 | api_link = "https://api.github.com/rate_limit" 57 | if self.auth == 1: 58 | req = urllib2.Request(api_link+"?client_id="+self.client+"&client_secret="+self.secret) 59 | elif self.auth == 2: 60 | req = urllib2.Request(api_link) 61 | req.add_header("Access-Token", self.token) 62 | else: 63 | req = urllib2.Request(api_link) 64 | res = json.load(urllib2.urlopen(req)) 65 | self.api = defaultdict(int) 66 | self.api['rate_limit'] = int(res['rate']['limit']) 67 | self.api['rate_remaining'] = int(res['rate']['remaining']) 68 | self.api['rate_reset'] = int(res['rate']['reset']) 69 | 70 | def check_limit(self, more_than=0): 71 | """Returns True if under limit, else log and return False.""" 72 | if self.api['rate_remaining'] > more_than: 73 | return True 74 | else: 75 | logmsg("X-RateLimit reached. Try again in "+self.api['rate_reset']+".") 76 | return False 77 | 78 | def request(self, api_link, arguments_get=None, arguments_post=None): 79 | """Request something to API using authentication.""" 80 | if arguments_get is None: 81 | arguments_get = [] 82 | if self.auth == 1: 83 | arguments_get += [["client_id", self.client], ["client_secret", self.secret]] 84 | if self.auth == 2: 85 | arguments_post += [["Access-Token", self.token]] 86 | if len(arguments_get) > 0: 87 | api_link += "?" 88 | for argument in arguments_get: 89 | api_link += argument[0]+"="+argument[1]+"&" 90 | api_link = api_link[0:-1] 91 | req = urllib2.Request(api_link) 92 | if arguments_post is not None and len(arguments_post) > 0: 93 | for argument in arguments_post: 94 | req.add_header(argument[0], argument[1]) 95 | response = urllib2.urlopen(req) 96 | self.api['rate_limit'] = int(response.headers.get("X-RateLimit-Limit")) 97 | self.api['rate_remaining'] = int(response.headers.get("X-RateLimit-Remaining")) 98 | self.api['rate_reset'] = int(response.headers.get("X-RateLimit-Reset")) 99 | return response 100 | 101 | class GitRepository: 102 | """Uses API to load Repository Data""" 103 | branch = None 104 | head = "" 105 | tail = "" 106 | repo_link = "" 107 | points = defaultdict(int) 108 | count = 0 109 | 110 | def __init__(self, api, repository, name=True): 111 | self.api = api 112 | if name: 113 | self.repo_link = "https://api.github.com/repos/" 114 | else: 115 | self.repo_link = "https://api.github.com/repositories/" 116 | self.repo_link += repository 117 | self.data = json.load(api.request(self.repo_link)) 118 | self.branch_name = self.data['default_branch'] 119 | 120 | def set_branch(self, branch_name): 121 | """Sets the working branch.""" 122 | self.branch = None 123 | self.branch_name = branch_name 124 | 125 | def set_head(self, head): 126 | """Set the latest head.""" 127 | self.head = head 128 | 129 | def set_tail(self, tail): 130 | """Set the further tail""" 131 | self.tail = tail 132 | 133 | def get_branch(self): 134 | """Get branch data.""" 135 | logmsg("Loaded branch " + self.branch_name) 136 | if self.branch is None: 137 | branches_link = self.repo_link + "/branches/" + self.branch_name 138 | self.branch = json.load(api.request(branches_link)) 139 | return self.branch 140 | 141 | def __parse_link_header(self, headers): 142 | links = {} 143 | if "Link" in headers: 144 | link_headers = headers["Link"].split(", ") 145 | for link_header in link_headers: 146 | (url, rel) = link_header.split("; ") 147 | url = url[1:-1] 148 | rel = rel[5:-1] 149 | links[rel] = url 150 | return links 151 | 152 | def update_commits(self): 153 | branch_head = self.get_branch()['commit']['sha'] 154 | logmsg("Loading from "+branch_head+ (" up to "+self.head if len(self.head) > 0 else "") + ".") 155 | page = '1' 156 | while self.api.check_limit(): 157 | response = self.api.request(self.repo_link + "/commits", [['per_page', '100'], ['sha', branch_head], ['page', page]]) 158 | commits = json.load(response) 159 | logmsg("page "+page+" contains " + str(len(commits)) +" commits.") 160 | for commit in commits: 161 | if commit['sha'] != self.head: 162 | author = commit['author']['id'] 163 | if self.api.check_limit() and not (len(self.points) > 10 and self.points[author] == 0): 164 | self.tail = self.__claim_commit(commit)['sha'] 165 | else: 166 | self.head = branch_head 167 | return self.tail 168 | else: 169 | logmsg(commit['sha']+": ") 170 | self.tail = commit['sha'] 171 | self.head = branch_head 172 | return self.tail 173 | try: 174 | links = self.__parse_link_header(response.headers) 175 | page = links['next'].split('&page=')[1].split('&')[0] 176 | except KeyError: 177 | logmsg("Reached end of pagination.") 178 | break 179 | self.head = branch_head 180 | return self.tail 181 | 182 | def continue_loading(self, old_tail, limit=""): 183 | logmsg("Continuing from "+self.head+ (" up to "+limit if len(limit) > 0 else "") +".") 184 | page = '1' 185 | claim = False 186 | while self.api.check_limit(): 187 | response = self.api.request(self.repo_link + "/commits", [['per_page', '100'], ['sha', self.head], ['page', page]]) 188 | commits = json.load(response) 189 | logmsg("page "+page+" contains " + str(len(commits)) +" commits.") 190 | for commit in commits: 191 | if commit['sha'] != limit: 192 | if commit['sha'] == old_tail: 193 | logmsg(commit['sha']+": ") 194 | claim = True 195 | elif claim: 196 | author = commit['author']['id'] 197 | if self.api.check_limit() and not (len(self.points) > 10 and self.points[author] == 0): 198 | self.tail = self.__claim_commit(commit)['sha'] 199 | else: 200 | return self.tail 201 | else: 202 | logmsg(commit['sha']+": ") 203 | self.tail = limit 204 | return self.tail 205 | try: 206 | links = self.__parse_link_header(response.headers) 207 | page = links['next'].split('&page=')[1].split('&')[0] 208 | except KeyError: 209 | logmsg("Reached end of pagination.") 210 | break 211 | return self.tail 212 | 213 | def __claim_commit(self, commit): 214 | self.count += 1 215 | if len(commit['parents']) < 2 and commit['author'] is not None: 216 | commit = json.load(self.api.request(commit['url'])) 217 | author = commit['author']['id'] 218 | self.points[author] += int(commit['stats']['additions']) 219 | if len(commit['parents']) == 0: 220 | parent = "" 221 | else: 222 | parent = "<"+commit['parents'][0]['sha']+">" 223 | logmsg(commit['sha']+": "+ commit['author']['login'] + " ("+str(author) + ") +" + str(commit['stats']['additions']) + " -"+ str(commit['stats']['deletions']) + " |= " + str(commit['stats']['total']) + " " + parent) 224 | else: 225 | if len(commit['parents']) >= 2: 226 | parents = "" 227 | for parent in commit['parents']: 228 | parents += parent['sha']+", " 229 | logmsg(commit['sha'] +": ") 230 | elif commit['author'] is None: 231 | logmsg(commit['sha'] +": ") 232 | else: 233 | logmsg(commit['sha'] +": ") 234 | return commit 235 | 236 | def issue_points(self, issueid): 237 | link_issue = self.repo_link + "/issues/" + issueid 238 | issue = json.load(api.request(link_issue)) 239 | link_issue = self.repo_link + "/issues/" + issueid + "/timeline" 240 | issue_timeline = self.api.request(link_issue, None, ["Accept", "application/vnd.github.mockingbird-preview"]) 241 | for elem in issue_timeline: 242 | if elem["event"] == "cross-referenced": 243 | if elem["source"]["type"] == "issue": 244 | pr = str(elem["source"]["issue"]["number"]) 245 | #print pr 246 | link_pull = self.repo_link + "/pulls/" + pr 247 | pull = json.load(self.api.request(link_pull)) 248 | if pull['merged_at']: 249 | link_pulls_commits = self.repo_link + "/pulls/" + pr + "/commits" 250 | commits = json.load(api.request(link_pulls_commits)) 251 | for commit in commits: 252 | if commit['url']: 253 | _commit = json.load(self.api.request(commit['url'])) 254 | author = _commit['author']['login'] 255 | self.points[author] += int(json.dumps(_commit['stats']['total'])) 256 | return issue 257 | 258 | def user_register(github_user,gistid): 259 | logmsg("Reading Gist "+gistid+" from "+github_user+".") 260 | value = json.load(api.request("https://api.github.com/gists/" + gistid)) 261 | login = value['owner']['login'] 262 | logmsg("Gist owner is "+login+".") 263 | if login == github_user: 264 | content = urllib2.urlopen("https://gist.githubusercontent.com/" + github_user + "/" + gistid + "/raw/").read(42) 265 | logmsg("Address is " + content) 266 | print "["+json.dumps(content)+",", 267 | print json.dumps(value['owner']['id'])+", "+json.dumps(login)+"]" 268 | else: 269 | logmsg("Wrong condition: "+github_user+" != "+login) 270 | sys.exit("403 Forbidden") 271 | 272 | 273 | 274 | #Script start 275 | try: 276 | argn = int(os.environ['ARGN']) 277 | except KeyError: 278 | sys.exit("400 Error") #bad call 279 | if argn < 2: 280 | sys.exit("404 Error") #no default function 281 | if argn > 3: 282 | sys.exit("400 Error") #bad call 283 | 284 | logmsg("Started " + os.environ['ARG0'] + "(" + os.environ['ARG1']+")") 285 | 286 | script = os.environ['ARG0'] 287 | args = [x.strip() for x in os.environ['ARG1'].split(',')] 288 | api = GitHubAPI() 289 | 290 | if api.check_limit(5): 291 | if script == 'update-new': 292 | repository = GitRepository(api, args[0]) 293 | if len(args) > 1: 294 | repository.set_branch(args[1]) 295 | if len(args) > 2: 296 | repository.set_head(args[2]) 297 | repository.update_commits() 298 | print "["+json.dumps(repository.data['id'])+"," + json.dumps(repository.branch['name']) + ",", 299 | print json.dumps(repository.head) + "," + json.dumps(repository.tail) + ",", 300 | print str(len(repository.points)) + ",", 301 | print json.dumps(repository.points.items()), 302 | print "]" 303 | elif script == 'update-old': 304 | repository = GitRepository(api, args[0]) 305 | repository.set_branch(args[1]) 306 | repository.set_head(args[2]) 307 | try: 308 | repository.continue_loading(args[3], args[4]) 309 | except IndexError: 310 | repository.continue_loading(args[3]) 311 | print "["+json.dumps(repository.data['id'])+"," + json.dumps(repository.get_branch()['name']) + ",", 312 | print json.dumps(repository.head) + "," + json.dumps(repository.tail) + ",", 313 | print str(len(repository.points)) + ",", 314 | print json.dumps(repository.points.items()), 315 | print "]" 316 | elif script == 'repository-add': 317 | repository = GitRepository(api, args[0]) 318 | print "["+json.dumps(repository.data['id'])+",", 319 | print json.dumps(repository.data['full_name'])+",", 320 | print json.dumps(repository.data['watchers_count'])+",", 321 | print json.dumps(repository.data['stargazers_count'])+"]" 322 | elif script == "user-add": 323 | user_register(args[0], args[1]) 324 | elif script == "issue-update": 325 | repository = GitRepository(api, args[0]) 326 | issue = repository.issue_points(args[1]) 327 | print "["+json.dumps(repository.data['id'])+"," + json.dumps(issue['id']), 328 | print json.dumps(issue['state']) + ", " + datetime.datetime.strptime(issue['closed_at'], "%Y-%m-%dT%H:%M:%SZ").strftime('%s') + ", ", 329 | print str(len(repository.points)) + ",", 330 | print json.dumps(repository.points.items()), 331 | print "]" 332 | else: 333 | sys.exit("501 Not implemented") 334 | else: 335 | sys.exit("503 Service Unavailable") 336 | -------------------------------------------------------------------------------- /scripts/issue_claim/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:14.04 2 | RUN apt-get update && apt-get install -y python 3 | ADD issue_status.py issue_status.py 4 | MAINTAINER Ricardo “3esmit@gmail.com” 5 | CMD python issue_status.py -------------------------------------------------------------------------------- /scripts/issue_claim/issue_status.py: -------------------------------------------------------------------------------- 1 | import os, sys, json, urllib, datetime 2 | 3 | print os.environ['ARG0'] 4 | 5 | if(len(sys.argv) < 3): 6 | print "too few arguments" 7 | sys.exit() 8 | 9 | repo = sys.argv[1] 10 | issue = sys.argv[2] 11 | if(len(sys.argv) < 5): 12 | auth = "" 13 | else: 14 | client_id = sys.argv[3] 15 | client_secret = sys.argv[4] 16 | auth = "?client_id="+client_id+"&client_secret="+client_secret 17 | 18 | link_issue = "https://api.github.com/repos/" + repo + "/issues/" + issue + auth 19 | issue = json.load(urllib.urlopen(link_issue)) 20 | 21 | if(issue['state'] == "closed"): 22 | print datetime.datetime.strptime( json.dumps(issue['closed_at'])[1:-1], "%Y-%m-%dT%H:%M:%SZ" ).strftime('%s') +","+ json.dumps(issue['closed_by']['login']) 23 | else: 24 | print "open" -------------------------------------------------------------------------------- /scripts/issue_claim/pullrequest_contributors.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import json 3 | import urllib 4 | import argparse 5 | from collections import defaultdict 6 | 7 | 8 | auth = "?client_id=&client_secret=" 9 | 10 | 11 | repo = sys.argv[1] 12 | pr = sys.argv[2] 13 | link_pulls_commits = "https://api.github.com/repos/" + repo + "/pulls/" + pr + "/commits" +auth 14 | points = defaultdict(int) 15 | commits = json.load(urllib.urlopen(link_pulls_commits)) 16 | for commit in commits: 17 | if(commit['url']): 18 | link_commit = json.dumps(commit['url'])[1:-1] +auth 19 | _commit = json.load(urllib.urlopen(link_commit)) 20 | author = json.dumps(_commit['author']['login'])[1:-1] 21 | points[author] += int(json.dumps(_commit['stats']['total'])) 22 | print points.items() -------------------------------------------------------------------------------- /scripts/oraclize-args/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:14.04 2 | RUN apt-get update && apt-get install -y python 3 | ADD testarg.py testarg.py 4 | MAINTAINER Ricardo “3esmit@gmail.com” 5 | CMD python testarg.py -------------------------------------------------------------------------------- /scripts/oraclize-args/README.md: -------------------------------------------------------------------------------- 1 | # TheEtherian 2 | -------------------------------------------------------------------------------- /scripts/oraclize-args/testarg.py: -------------------------------------------------------------------------------- 1 | import os, argparse 2 | import json, urllib2, datetime 3 | from collections import defaultdict 4 | start = '' 5 | 6 | parser = argparse.ArgumentParser() 7 | parser.add_argument('-S','--script') 8 | 9 | parser.add_argument('-U','--username') 10 | parser.add_argument('-u','--userid') 11 | 12 | parser.add_argument('-R','--repoid') 13 | parser.add_argument('-r','--reponame') 14 | 15 | parser.add_argument('-C','--commitid') 16 | 17 | parser.add_argument('-B','--branch') 18 | parser.add_argument('-T','--tail') 19 | parser.add_argument('-H','--head') 20 | 21 | parser.add_argument('-I','--issueid') 22 | parser.add_argument('-P','--pullid') 23 | 24 | parser.add_argument('-c','--client') 25 | parser.add_argument('-s','--secret') 26 | 27 | 28 | args = parser.parse_args() 29 | 30 | if(args.client is not None and args.secret is not None): 31 | client_id = args.client 32 | client_secret = args.secret 33 | auth = "?client_id="+client_id+"&client_secret="+client_secret 34 | else: 35 | auth = "" 36 | count = 0 37 | repo_link = "" 38 | if(args.reponame is not None): 39 | repo_link = "https://api.github.com/repos/" + args.reponame 40 | else: 41 | repo_link = "https://api.github.com/repositories/" + args.repoid 42 | 43 | 44 | points = defaultdict(int) 45 | claimed = defaultdict(bool) 46 | 47 | def relatedIssues(issue): 48 | link_issue = repo_link + "/issues/" + issue + "/timeline" + auth 49 | print link_issue 50 | req = urllib2.Request(link_issue) 51 | req.add_header("Accept", "application/vnd.github.mockingbird-preview") 52 | issue = json.load(urllib2.urlopen(req)) 53 | for elem in issue: 54 | if(elem["event"] == "cross-referenced"): 55 | if(elem["source"]["type"] == "issue"): 56 | #print elem["source"]["issue"]["number"]; 57 | pullCommitPoints(json.dumps(elem["source"]["issue"]["number"])) 58 | 59 | 60 | 61 | def issueStatus(issue): 62 | link_issue = repo_link + "/issues/" + issue + auth 63 | issue = json.load(urllib2.urlopen(link_issue)) 64 | if(issue['state'] == "closed"): 65 | print datetime.datetime.strptime( json.dumps(issue['closed_at'])[1:-1], "%Y-%m-%dT%H:%M:%SZ" ).strftime('%s') +","+ json.dumps(issue['closed_by']['login']) 66 | else: 67 | print "open" 68 | 69 | 70 | def pullCommitPoints(pr): 71 | link_pull = repo_link + "/pulls/" + pr + auth 72 | pull = json.load(urllib2.urlopen(link_pull)) 73 | if(pull['merged_at']): 74 | link_pulls_commits = repo_link + "/pulls/" + pr + "/commits" +auth 75 | points = defaultdict(int) 76 | commits = json.load(urllib2.urlopen(link_pulls_commits)) 77 | for commit in commits: 78 | if(commit['url']): 79 | link_commit = json.dumps(commit['url'])[1:-1] +auth 80 | _commit = json.load(urllib2.urlopen(link_commit)) 81 | #print _commit['sha'], 82 | author = json.dumps(_commit['author']['login'])[1:-1] 83 | points[author] += int(json.dumps(_commit['stats']['total'])) 84 | print points.items(), 85 | 86 | 87 | def issueCommits(issueid): 88 | link_issue = repo_link + "/issues/" + issueid + "/timeline" + auth 89 | req = urllib2.Request(link_issue) 90 | req.add_header("Accept", "application/vnd.github.mockingbird-preview") 91 | issue = json.load(urllib2.urlopen(req)) 92 | for elem in issue: 93 | if(elem["event"] == "cross-referenced"): 94 | if(elem["source"]["type"] == "issue"): 95 | #print elem["source"]["issue"]["number"]; 96 | pullCommitPoints(json.dumps(elem["source"]["issue"]["number"])) 97 | 98 | def commitData(commit): 99 | link_commit = repo_link +"/commits/"+ commit; 100 | req = urllib2.Request(link_commit) 101 | req.add_header("Accept", "application/vnd.github.mockingbird-preview") 102 | commit = json.load(urllib2.urlopen(req)) 103 | print json.dumps(commit) 104 | 105 | 106 | 107 | def updateIssue(issueid): 108 | link_issue = repo_link + "/issues/" + issueid + auth 109 | issue = json.load(urllib2.urlopen(link_issue)) 110 | print issue['state'] + ", " + datetime.datetime.strptime( json.dumps(issue['closed_at'])[1:-1], "%Y-%m-%dT%H:%M:%SZ" ).strftime('%s') + ", ", 111 | 112 | link_issue = repo_link + "/issues/" + issueid + "/timeline" + auth 113 | req = urllib2.Request(link_issue) 114 | req.add_header("Accept", "application/vnd.github.mockingbird-preview") 115 | issue = json.load(urllib2.urlopen(req)) 116 | 117 | for elem in issue: 118 | if(elem["event"] == "cross-referenced"): 119 | if(elem["source"]["type"] == "issue"): 120 | #print elem["source"]["issue"]["number"]; 121 | pr = json.dumps(elem["source"]["issue"]["number"]) 122 | link_pull = repo_link + "/pulls/" + pr + auth 123 | pull = json.load(urllib2.urlopen(link_pull)) 124 | if(pull['merged_at']): 125 | link_pulls_commits = repo_link + "/pulls/" + pr + "/commits" +auth 126 | commits = json.load(urllib2.urlopen(link_pulls_commits)) 127 | for commit in commits: 128 | if(commit['url']): 129 | link_commit = json.dumps(commit['url'])[1:-1] + auth 130 | _commit = json.load(urllib2.urlopen(link_commit)) 131 | author = _commit['author']['login'] 132 | points[author] += int(json.dumps(_commit['stats']['total'])) 133 | print points.items() 134 | 135 | #branchname required 136 | 137 | 138 | 139 | 140 | 141 | def updateCommits(branchname, head, tail): 142 | if(branchname is None): 143 | req = urllib2.Request(repo_link+auth) 144 | repo = json.load(urllib2.urlopen(req)) 145 | branchname = json.dumps(repo['default_branch'])[1:-1] 146 | if(head is None and tail is not None): #tail only = error 147 | print "bad call" 148 | return 149 | elif(head is None and tail is None): #no head and no tail (new) = from latest head to reachable tails 150 | branches_link = repo_link + "/branches/" + branchname + auth 151 | req = urllib2.Request(branches_link) 152 | branch = json.load(urllib2.urlopen(req)) 153 | _head = json.dumps(branch['commit']['sha'])[1:-1] 154 | head = _head 155 | elif(head is not None and tail is None): #head only (sync) = from latestHead to head 156 | setClaimedChunk(head, "") 157 | branches_link = repo_link + "/branches/" + branchname + auth 158 | req = urllib2.Request(branches_link) 159 | branch = json.load(urllib2.urlopen(req)) 160 | _head = json.dumps(branch['commit']['sha'])[1:-1] 161 | head = _head 162 | elif(tail is not None and head is not None): #head and tail (continue) = continue from tail 163 | _head = tail 164 | 165 | commit_link = repo_link + "/commits/" + _head + auth 166 | #print commit_link 167 | req = urllib2.Request(commit_link) 168 | _head = json.load(urllib2.urlopen(req)) 169 | ntail = loadPoints(_head) 170 | 171 | print json.dumps(head) + "," + json.dumps(ntail['sha']) + ", ", 172 | print str(len(points)) + ", ", 173 | print json.dumps(points.items()), 174 | 175 | 176 | #https://api.github.com/repos/status-im/github-oracle/compare/master...6e2528a9eb3fec21ca0679ec0c2a0935c2aa6656 COMPARE IF COMMIT IS IN `master` 177 | #https://api.github.com/repos/status-im/github-oracle/commits?per_page=100&sha=e0a340e72784b1322929d6803773b31a2b6b5707 178 | #https://api.github.com/repos/status-im/github-oracle/git/refs/heads BRANCHES 179 | #https://developer.github.com/v3/#conditional-requests 180 | 181 | def setCommittedTree(commit): 182 | if(claimed[commit['sha']] == False): 183 | claimed[commit['sha']] = True; 184 | for parent in commit['parents']: 185 | link_commit = json.dumps(parent['url'])[1:-1] + auth 186 | _commit = json.load(urllib2.urlopen(link_commit)) 187 | setCommittedTree(_commit); 188 | 189 | 190 | def setClaimedChunk(head, tail): 191 | global count 192 | while (tail != head): 193 | commit_link = repo_link + "/commits" + auth + "&per_page=100&sha=" + head 194 | req = urllib2.Request(commit_link) 195 | commits = json.load(urllib2.urlopen(req)); 196 | for commit in commits: 197 | if(claimed[commit['sha']] != True): 198 | claimed[commit['sha']] = True 199 | #print "claimed "+str(count)+": "+commit['sha'] 200 | count += 1 201 | head = commit['sha'] 202 | if(len(commit['parents']) == 2): 203 | setClaimedChunk("", json.dumps(commit['parents'])[1][1:-1]) 204 | if (tail == head): 205 | break 206 | if(len(commits) < 100): 207 | break 208 | return head 209 | 210 | def loadPoints(head): 211 | global count 212 | 213 | while (claimed[head['sha']] == False and count < 1000): 214 | claimed[head['sha']] = True 215 | count += 1 216 | if (head['author'] is not None): 217 | author = json.dumps(head['author']['login'])[1:-1] 218 | if (len(points) > 5 and points[author] == 0): break; 219 | if (len(head['parents']) < 2): 220 | points[author] += int(json.dumps(head['stats']['total'])) 221 | #print str(count) + ": " + head['sha'] +" +"+ str(head['stats']['total']) 222 | #else: 223 | #print str(count) + ": " + head['sha'] +" -"+ str(head['stats']['total']) 224 | #else: 225 | #print str(count) + ": " + head['sha'] +" x"+ str(head['stats']['total']) 226 | for parent in head['parents']: 227 | link_commit = json.dumps(parent['url'])[1:-1] + auth 228 | _commit = json.load(urllib2.urlopen(link_commit)) 229 | head = loadPoints(_commit) 230 | return head 231 | 232 | 233 | 234 | if args.script == 'issue-status': 235 | issueStatus(args.issueid) 236 | elif args.script == 'issue-update': 237 | updateIssue(args.issueid) 238 | elif args.script == 'issue-commits': 239 | issueCommits(args.issueid) 240 | elif args.script == 'related-issues': 241 | relatedIssues(args.issueid) 242 | elif args.script == 'commit-points': 243 | pullCommitPoints(args.pullid) 244 | elif args.script == 'commit-data': 245 | commitData(args.commitid) 246 | elif args.script== 'update-commits': 247 | updateCommits(args.branch, args.head, args.tail) 248 | 249 | -------------------------------------------------------------------------------- /scripts/test.sh: -------------------------------------------------------------------------------- 1 | ARGN=3 2 | ARG2="f94095ba1d48038d4a81,36ae0e8b1bc5ad261c936e8f7f730f6c827c221f" 3 | ARG0="user-add" 4 | ARG1="3esmit,31a58f2ddf2258697cce1b969e7c298b" 5 | 6 | export ARGN 7 | export ARG0 8 | export ARG1 9 | export ARG2 10 | 11 | 12 | 13 | 14 | python github-oracle/github_oracle.py 15 | 16 | ARG0="update-new" 17 | ARG1="ethereans/TheEtherian,master,f6a4474822a1193f81b45a571e521218a48ca8e3" 18 | 19 | #python github-oracle/github_oracle.py 20 | 21 | ARG0="update-old" 22 | ARG1="ethereans/TheEtherian,master,b2ca0a249c6614d2be14d7d77694f52cd83acfd9,7d69d0e065d983cacb39f88ea1500c9224fe622f,e2c8c7a091ce3893635ce47169c972c6d5434ffa" 23 | 24 | python github-oracle/github_oracle.py -------------------------------------------------------------------------------- /tools/encrypted_queries_tools.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | import os 3 | import argparse 4 | import sys 5 | from cryptography.hazmat.primitives import hashes 6 | from cryptography.hazmat.primitives.kdf import x963kdf 7 | from cryptography.hazmat.primitives.asymmetric import ec 8 | from cryptography.hazmat.primitives.ciphers import Cipher,algorithms,modes 9 | from cryptography.hazmat.backends import default_backend 10 | import base64 11 | import base58 12 | 13 | backend = default_backend() 14 | 15 | def hex_to_key(pub_key_hex): 16 | pub_key_hex = pub_key_hex.strip() 17 | pub_key_point = pub_key_hex.decode('hex') 18 | public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256K1(), pub_key_point) 19 | public_key = public_numbers.public_key(backend) 20 | return public_key 21 | 22 | def hex_to_priv_key(priv_key_hex, public_key_hex): 23 | priv_key_value = long(priv_key_hex, 16) 24 | public_key = hex_to_key(public_key_hex) 25 | public_numbers = public_key.public_numbers() 26 | private_numbers = ec.EllipticCurvePrivateNumbers(priv_key_value, public_numbers) 27 | priv_key = private_numbers.private_key(backend) 28 | return priv_key 29 | 30 | # Hybrid Encryption Scheme: 31 | # - We perform a Elliptic Curves Diffie-Hellman Key Exchange using: 32 | # - SECP256K1 as curve for key generation 33 | # - ANSI X9.63 KDF as Key Derivation Function to derive the shared secret 34 | # - The symmetric cipher is an AES256.MODE_GCM with authentication tag 16-byte 35 | # of length. Since the key is used only once, we can pick the known nonce/iv 36 | # '000000000000' (96 bits of length). We return concatenation of the encoded 37 | # point, the tag and the ciphertext 38 | 39 | def encrypt(message, receiver_public_key): 40 | sender_private_key = ec.generate_private_key(ec.SECP256K1(), backend) 41 | shared_key = sender_private_key.exchange(ec.ECDH(), receiver_public_key) 42 | sender_public_key = sender_private_key.public_key() 43 | point = sender_public_key.public_numbers().encode_point() 44 | iv = '000000000000' 45 | xkdf = x963kdf.X963KDF( 46 | algorithm = hashes.SHA256(), 47 | length = 32, 48 | sharedinfo = '', 49 | backend = backend 50 | ) 51 | key = xkdf.derive(shared_key) 52 | encryptor = Cipher( 53 | algorithms.AES(key), 54 | modes.GCM(iv), 55 | backend = backend 56 | ).encryptor() 57 | ciphertext = encryptor.update(message) + encryptor.finalize() 58 | return point + encryptor.tag + ciphertext 59 | 60 | 61 | def decrypt(message, receiver_private_key): 62 | point = message[0:65] 63 | tag = message[65:81] 64 | ciphertext = message[81:] 65 | sender_public_numbers = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256K1(), point) 66 | sender_public_key = sender_public_numbers.public_key(backend) 67 | shared_key = receiver_private_key.exchange(ec.ECDH(), sender_public_key) 68 | iv = '000000000000' 69 | xkdf = x963kdf.X963KDF( 70 | algorithm = hashes.SHA256(), 71 | length = 32, 72 | sharedinfo = '', 73 | backend = backend 74 | ) 75 | key = xkdf.derive(shared_key) 76 | decryptor = Cipher( 77 | algorithms.AES(key), 78 | modes.GCM(iv,tag), 79 | backend = backend 80 | ).decryptor() 81 | message = decryptor.update(ciphertext) + decryptor.finalize() 82 | return message 83 | 84 | 85 | def main(): 86 | parser = argparse.ArgumentParser(description='Encrypt messages to Oraclize using Elliptic Curve Integrated Encryption Scheme.') 87 | parser.add_argument('-e', '--encrypt', dest='mode', action='store_const', const='encrypt', help='Encrypt a string. Requires -p') 88 | parser.add_argument('-p', '--with-public-key', dest='public_key', action='store', help='Use the provided hex-encoded public key to encrypt') 89 | parser.add_argument('-d', '--decrypt', dest='mode', action='store_const', const='decrypt', help='Decrypt a string. Provide private key in Wallet Import Format in standard input, or first line of standard input if encrypted text is also provided on standard input. DO NOT PUT YOUR PRIVATE KEY ON THE COMMAND LINE.') 90 | parser.add_argument('-g', '--generate', dest='mode', action='store_const', const='generate', help='Generates a public and a private key') 91 | parser.add_argument('text', nargs='?', action='store', help='String to encrypt, decrypt. If not specified, standard input will be used.') 92 | 93 | args = parser.parse_args() 94 | 95 | if args.mode != 'encrypt' and args.mode != 'decrypt' and args.mode != 'generate': 96 | parser.print_help() 97 | return 98 | 99 | if args.mode == 'encrypt' and not args.public_key: 100 | print "Please, provide a valid public key" 101 | return 102 | 103 | if args.mode == 'encrypt': 104 | if args.public_key: 105 | pub_key = hex_to_key(args.public_key) 106 | 107 | if args.text: 108 | print base64.b64encode(encrypt(args.text, pub_key)) 109 | return 110 | else: 111 | print base64.b64encode(encrypt(sys.stdin.read(), pub_key)) 112 | return 113 | elif args.mode == 'decrypt': 114 | if args.text: 115 | print "Insert your public key" 116 | public_key = sys.stdin.read() 117 | print "Insert your private key:" 118 | private_key = sys.stdin.read() 119 | private_key = hex_to_priv_key(private_key, public_key) 120 | text = base64.b64decode(args.text) 121 | else: 122 | print "Insert your public key" 123 | public_key = sys.stdin.read() 124 | print "\nInsert your private key:" 125 | private_key = sys.stdin.read() 126 | private_key = hex_to_priv_key(private_key, public_key) 127 | print "\nInsert encrypted text" 128 | text = base64.b64decode(sys.stdin.read()) 129 | 130 | print decrypt(text, private_key) 131 | 132 | if args.mode == 'generate': 133 | receiver_private_key = ec.generate_private_key(ec.SECP256K1(), backend) 134 | receiver_public_key = receiver_private_key.public_key() 135 | number = receiver_private_key.private_numbers() 136 | print "Public Key:", receiver_public_key.public_numbers().encode_point().encode('hex') 137 | print "Private Key:", hex(number.private_value) 138 | 139 | 140 | 141 | 142 | if __name__ == "__main__": 143 | main() 144 | --------------------------------------------------------------------------------