├── LICENSE
├── OrderStatisticTree.abi
├── OrderStatisticTree.binary
├── OrderStatisticTree.sol
├── README.md
├── bignumber.min.js
├── ethereum.js
├── ethereum.js.map
├── jquery.js
├── ost_test.html
└── ost_test.js
/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 |
635 | Copyright (C)
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 | Copyright (C)
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 | .
--------------------------------------------------------------------------------
/OrderStatisticTree.abi:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "constant" : true,
4 | "inputs" : [],
5 | "name" : "count",
6 | "outputs" : [
7 | {
8 | "name" : "count",
9 | "type" : "uint256"
10 | }
11 | ],
12 | "type" : "function"
13 | },
14 | {
15 | "constant" : true,
16 | "inputs" : [
17 | {
18 | "name" : "value",
19 | "type" : "uint256"
20 | }
21 | ],
22 | "name" : "node_right_child",
23 | "outputs" : [
24 | {
25 | "name" : "child",
26 | "type" : "uint256"
27 | }
28 | ],
29 | "type" : "function"
30 | },
31 | {
32 | "constant" : true,
33 | "inputs" : [
34 | {
35 | "name" : "value",
36 | "type" : "uint256"
37 | },
38 | {
39 | "name" : "n",
40 | "type" : "uint256"
41 | }
42 | ],
43 | "name" : "in_top_n",
44 | "outputs" : [
45 | {
46 | "name" : "truth",
47 | "type" : "bool"
48 | }
49 | ],
50 | "type" : "function"
51 | },
52 | {
53 | "constant" : true,
54 | "inputs" : [
55 | {
56 | "name" : "value",
57 | "type" : "uint256"
58 | }
59 | ],
60 | "name" : "percentile",
61 | "outputs" : [
62 | {
63 | "name" : "k",
64 | "type" : "uint256"
65 | }
66 | ],
67 | "type" : "function"
68 | },
69 | {
70 | "constant" : true,
71 | "inputs" : [
72 | {
73 | "name" : "value",
74 | "type" : "uint256"
75 | }
76 | ],
77 | "name" : "node_side",
78 | "outputs" : [
79 | {
80 | "name" : "side",
81 | "type" : "bool"
82 | }
83 | ],
84 | "type" : "function"
85 | },
86 | {
87 | "constant" : false,
88 | "inputs" : [
89 | {
90 | "name" : "value",
91 | "type" : "uint256"
92 | }
93 | ],
94 | "name" : "remove",
95 | "outputs" : [],
96 | "type" : "function"
97 | },
98 | {
99 | "constant" : true,
100 | "inputs" : [
101 | {
102 | "name" : "value",
103 | "type" : "uint256"
104 | }
105 | ],
106 | "name" : "node_parent",
107 | "outputs" : [
108 | {
109 | "name" : "parent",
110 | "type" : "uint256"
111 | }
112 | ],
113 | "type" : "function"
114 | },
115 | {
116 | "constant" : true,
117 | "inputs" : [
118 | {
119 | "name" : "value",
120 | "type" : "uint256"
121 | }
122 | ],
123 | "name" : "node_dupes",
124 | "outputs" : [
125 | {
126 | "name" : "dupes",
127 | "type" : "uint256"
128 | }
129 | ],
130 | "type" : "function"
131 | },
132 | {
133 | "constant" : true,
134 | "inputs" : [
135 | {
136 | "name" : "value",
137 | "type" : "uint256"
138 | }
139 | ],
140 | "name" : "permille",
141 | "outputs" : [
142 | {
143 | "name" : "k",
144 | "type" : "uint256"
145 | }
146 | ],
147 | "type" : "function"
148 | },
149 | {
150 | "constant" : true,
151 | "inputs" : [
152 | {
153 | "name" : "value",
154 | "type" : "uint256"
155 | }
156 | ],
157 | "name" : "node_left_child",
158 | "outputs" : [
159 | {
160 | "name" : "child",
161 | "type" : "uint256"
162 | }
163 | ],
164 | "type" : "function"
165 | },
166 | {
167 | "constant" : true,
168 | "inputs" : [],
169 | "name" : "median",
170 | "outputs" : [
171 | {
172 | "name" : "value",
173 | "type" : "uint256"
174 | }
175 | ],
176 | "type" : "function"
177 | },
178 | {
179 | "constant" : false,
180 | "inputs" : [
181 | {
182 | "name" : "value",
183 | "type" : "uint256"
184 | }
185 | ],
186 | "name" : "insert",
187 | "outputs" : [],
188 | "type" : "function"
189 | },
190 | {
191 | "constant" : true,
192 | "inputs" : [
193 | {
194 | "name" : "value",
195 | "type" : "uint256"
196 | }
197 | ],
198 | "name" : "duplicates",
199 | "outputs" : [
200 | {
201 | "name" : "n",
202 | "type" : "uint256"
203 | }
204 | ],
205 | "type" : "function"
206 | },
207 | {
208 | "constant" : true,
209 | "inputs" : [
210 | {
211 | "name" : "value",
212 | "type" : "uint256"
213 | }
214 | ],
215 | "name" : "rank",
216 | "outputs" : [
217 | {
218 | "name" : "smaller",
219 | "type" : "uint256"
220 | }
221 | ],
222 | "type" : "function"
223 | },
224 | {
225 | "constant" : true,
226 | "inputs" : [
227 | {
228 | "name" : "value",
229 | "type" : "uint256"
230 | }
231 | ],
232 | "name" : "node_count",
233 | "outputs" : [
234 | {
235 | "name" : "count",
236 | "type" : "uint256"
237 | }
238 | ],
239 | "type" : "function"
240 | },
241 | {
242 | "constant" : true,
243 | "inputs" : [
244 | {
245 | "name" : "permille",
246 | "type" : "uint256"
247 | }
248 | ],
249 | "name" : "at_permille",
250 | "outputs" : [
251 | {
252 | "name" : "value",
253 | "type" : "uint256"
254 | }
255 | ],
256 | "type" : "function"
257 | },
258 | {
259 | "constant" : true,
260 | "inputs" : [
261 | {
262 | "name" : "pos",
263 | "type" : "uint256"
264 | }
265 | ],
266 | "name" : "select_at",
267 | "outputs" : [
268 | {
269 | "name" : "value",
270 | "type" : "uint256"
271 | }
272 | ],
273 | "type" : "function"
274 | },
275 | {
276 | "constant" : true,
277 | "inputs" : [
278 | {
279 | "name" : "value",
280 | "type" : "uint256"
281 | }
282 | ],
283 | "name" : "node_height",
284 | "outputs" : [
285 | {
286 | "name" : "height",
287 | "type" : "uint256"
288 | }
289 | ],
290 | "type" : "function"
291 | },
292 | {
293 | "constant" : true,
294 | "inputs" : [
295 | {
296 | "name" : "percentile",
297 | "type" : "uint256"
298 | }
299 | ],
300 | "name" : "at_percentile",
301 | "outputs" : [
302 | {
303 | "name" : "value",
304 | "type" : "uint256"
305 | }
306 | ],
307 | "type" : "function"
308 | }
309 | ]
310 |
--------------------------------------------------------------------------------
/OrderStatisticTree.binary:
--------------------------------------------------------------------------------
1 | 5b5b6113cf806100106000396000f3006000357c01000000000000000000000000000000000000000000000000000000009004806306661abd146100f557806321f0a7271461010757806337da80581461011c5780633b5f24eb1461013457806348da1532146101495780634cc822151461015e5780635014a18e1461016f5780635663263714610184578063598ac8f21461019957806366d5c8ed146101ae57806377049457146101c357806390b5561d146101d55780639f853717146101e6578063b37c191b146101fb578063bdc0f93c14610210578063d9269cb414610225578063e832fda31461023a578063e973b7ba1461024f578063fa2b579d1461026457005b6100fd610613565b8060005260206000f35b6101126004356107f0565b8060005260206000f35b61012a600435602435610671565b8060005260206000f35b61013f6004356106a3565b8060005260206000f35b610154600435610848565b8060005260206000f35b6101696004356102b8565b60006000f35b61017a600435610825565b8060005260206000f35b61018f6004356108b1565b8060005260206000f35b6101a4600435610722565b8060005260206000f35b6101b96004356107bb565b8060005260206000f35b6101cb6107a5565b8060005260206000f35b6101e0600435610279565b60006000f35b6101f16004356105eb565b8060005260206000f35b610206600435610368565b8060005260206000f35b61021b60043561088e565b8060005260206000f35b61023060043561077b565b8060005260206000f35b61024560043561048d565b8060005260206000f35b61025a60043561086b565b8060005260206000f35b61026f6004356106f9565b8060005260206000f35b600081146102935761028e6000600183610904565b6102b4565b60006000828152602001908152602001600020600501805490816001019055505b5b50565b6000600060008381526020019081526020016000209050600082146102f25760008160040154146102e8576102ed565b610364565b610309565b600081600501541461030357610308565b610364565b5b60008160050154116103235761031e82610a08565b610363565b806005018054908160019003905550600082141561034057610350565b8060040180549081600190039055505b610362816001015482600201546108d4565b5b5b5050565b6000600060006000600085141561037e57610484565b6000600060008152602001908152602001600020600501549350835060006000600081526020019081526020016000206000016000600181526020019081526020016000205492506000600084815260200190815260200160002091505b60011561048357848311156103f057610451565b8483106103fc5761040b565b81600501546001018401935083505b81600001600060008152602001908152602001600020549050600081141561043257610450565b60006000828152602001908152602001600020600401548401935083505b5b84831461045d57610462565b610483565b816000016000868510815260200190815260200160002054925082506103dc565b5b5b505050919050565b6000600060006000600060006000600060006000600060008152602001908152602001600020600501549750878a106105d457878a03965060006000600081526020019081526020016000206000016000600181526020019081526020016000205495506000600087815260200190815260200160002094505b6001156105cf578460000160006000815260200190815260200160002054935060018560050154019250600084141561054557600090508050610562565b600060008581526020019081526020016000209150816004015490505b8087106105bf5782810187106105b25784600001600060018152602001908152602001600020549550855060006000878152602001908152602001600020945084508281018703965086506105ba565b8598506105de565b6105ca565b839550855081945084505b610507565b6105dd565b600098506105de565b5b5050505050505050919050565b60006001600060008481526020019081526020016000206005015401905061060e565b919050565b60006000600060006000600081526020019081526020016000209150600060008360000160006001815260200190815260200160002054815260200190815260200160002090508060040154826005015401925061066c565b505090565b60006000600061068085610368565b915061068a610613565b90508360018383030310925061069b565b505092915050565b60006000600060006106b485610368565b9250600060008681526020019081526020016000206005015491506106d7610613565b9050806002606460648502010460648502010493506106f1565b505050919050565b60006000610705610613565b905061071560648285020461048d565b915061071c565b50919050565b600060006000600061073385610368565b925060006000868152602001908152602001600020600501549150610756610613565b90508060026103e86103e8850201046103e8850201049350610773565b505050919050565b60006000610787610613565b90506107986103e88285020461048d565b915061079f565b50919050565b60006107b160326106f9565b90506107b8565b90565b60006000600083815260200190815260200160002060000160006000815260200190815260200160002054905080505b919050565b60006000600083815260200190815260200160002060000160006001815260200190815260200160002054905080505b919050565b60006000600083815260200190815260200160002060010154905080505b919050565b60006000600083815260200190815260200160002060020154905080505b919050565b60006000600083815260200190815260200160002060030154905080505b919050565b60006000600083815260200190815260200160002060040154905080505b919050565b60006000600083815260200190815260200160002060050154905080505b919050565b60008214156108e2576108ff565b6108eb82610b56565b6108f482610bde565b6108fe8282610d35565b5b5b5050565b6000600060006000600060008881526020019081526020016000209350836000016000878152602001908152602001600020549250600083146109965784831461095e57828510159050610959838287610904565b610991565b600060008481526020019081526020016000206005018054908160010190555061098785610b56565b61099085610bde565b5b6109fe565b848460000160008881526020019081526020016000208190555060006000868152602001908152602001600020915086826001018190555085826002018190555060018260030181905550600182600401819055506109f485610bde565b6109fd85610c32565b5b5b50505050505050565b60006000600060006000600060006000600060008a8152602001908152602001600020975087600101549650876002015495506000600088815260200190815260200160002094508760000160006000815260200190815260200160002054935087600001600060018152602001908152602001600020549250600084148015610a925750600083145b610b1b5760008414158015610aa8575060008314155b610b0a5782840191506000600083815260200190815260200160002090508185600001600088815260200190815260200160002081905550868160010181905550858160020181905550610afb89610eb2565b610b0587876108d4565b610b16565b610b15898585610f38565b5b610b4a565b600085600001600088815260200190815260200160002081905550610b3f89610eb2565b610b4987876108d4565b5b5b505050505050505050565b60006000600083815260200190815260200160002090508060050154600060008360000160006001815260200190815260200160002054815260200190815260200160002060040154600060008460000160006000815260200190815260200160002054815260200190815260200160002060040154600101010181600401819055505b5050565b6000600060008381526020019081526020016000206001015490505b600081141515610c2d57610c0d81610b56565b600060008281526020019081526020016000206001015490508050610bfa565b5b5050565b60006000600060006000610c45866110f0565b600060008781526020019081526020016000209450846001015493506000841415610c6f57610d2c565b610c7884611195565b92508460020154915081610c9157600190508050610cb7565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff905080505b600281028314610cde576000831415610ccf57610cd9565b610cd884610c32565b5b610d2b565b807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff02610d0a87611195565b14610d1457610d1f565b610d1e8683611216565b5b610d2a848315611216565b5b5b5b505050505050565b60006000600060006000600060006000891415610d5157610ea6565b610d5a896110f0565b610d6389611195565b965087955087610d97577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff94508450610d9e565b6001945084505b610da789611195565b9350846002028414610def5784871415610dc057610dea565b600060008a815260200190815260200160002092508250610de983600101548460020154610d35565b5b610ea5565b600060008a8152602001908152602001600020925082600001600089158152602001908152602001600020549150610e2682611195565b9050847fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff028114610e5657610e62565b610e61828915611216565b5b610e6c8989611216565b6000811415610e7a57610ea4565b600060008a815260200190815260200160002092508250610ea383600101548460020154610d35565b5b5b5b5b505050505050505050565b6000600060008381526020019081526020016000209050600081600101819055506000816002018190555060008160000160006000815260200190815260200160002081905550600081600001600060018152602001908152602001600020819055506000816004018190555060008160030181905550600081600501819055505b5050565b600060006000600060006000600060006000610f538b611374565b9850600060008a8152602001908152602001600020975087600501549650610f7a89610a08565b600060008d815260200190815260200160002095508560010154945060006000868152602001908152602001600020935085600301549250856002015491508560040154905085600001600060018152602001908152602001600020549950895085600001600060008152602001908152602001600020549a508a508884600001600084815260200190815260200160002081905550848860010181905550818860020181905550856005015487820103886004018190555082886003018190555086886005018190555060008b14156110535761108a565b8a886000016000600081526020019081526020016000208190555088600060008d8152602001908152602001600020600101819055505b60008a1415611098576110cf565b89886000016000600181526020019081526020016000208190555088600060008c8152602001908152602001600020600101819055505b6110d88c610eb2565b6110e189610bde565b5b505050505050505050505050565b600060006000600060008581526020019081526020016000209250600060008460000160006000815260200190815260200160002054815260200190815260200160002060030154915060006000846000016000600181526020019081526020016000205481526020019081526020016000206003015490508082116111815760018101836003018190555061118e565b6001820183600301819055505b5b50505050565b60006000600060008481526020019081526020016000209050600060008260000160006001815260200190815260200160002054815260200190815260200160002060030154600060008360000160006000815260200190815260200160002054815260200190815260200160002060030154039150611210565b50919050565b60006000600060006000600060006000600089159850600060008c8152602001908152602001600020975087600201549650876001015495508760000160008a81526020019081526020016000205494506000600086815260200190815260200160002093508360000160008b815260200190815260200160002054925060006000878152602001908152602001600020915060006000848152602001908152602001600020905084826000016000898152602001908152602001600020819055508684600201819055508584600101819055508a8460000160008c815260200190815260200160002081905550848860010181905550898860020181905550828860000160008b8152602001908152602001600020819055508a816001018190555088816002018190555061134b8b6110f0565b611354856110f0565b61135d8b610b56565b61136685610b56565b5b5050505050505050505050565b600060006000600084815260200190815260200160002060000160006001815260200190815260200160002054905060008114156113b8578291506113c9566113c8565b6113c181611374565b91506113c9565b5b5091905056
--------------------------------------------------------------------------------
/OrderStatisticTree.sol:
--------------------------------------------------------------------------------
1 | /*
2 | This program is free software: you can redistribute it and/or modify
3 | it under the terms of the GNU General Public License as published by
4 | the Free Software Foundation, either version 3 of the License, or
5 | (at your option) any later version.
6 |
7 | This program is distributed in the hope that it will be useful,
8 | but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | GNU General Public License for more details.
11 |
12 | You should have received a copy of the GNU General Public License
13 | along with this program. If not, see .
14 |
15 | Copyright 2015 Conrad Barski
16 |
17 | */
18 |
19 | contract OrderStatisticTree {
20 | function OrderStatisticTree() {
21 | }
22 | function update_count(uint value) private {
23 | Node n=nodes[value];
24 | n.count=1+nodes[n.children[false]].count+nodes[n.children[true]].count+n.dupes;
25 | }
26 | function update_counts(uint value) private {
27 | uint parent=nodes[value].parent;
28 | while (parent!=0) {
29 | update_count(parent);
30 | parent=nodes[parent].parent;
31 | }
32 | }
33 | function update_height(uint value) private {
34 | Node n=nodes[value];
35 | uint height_left=nodes[n.children[false]].height;
36 | uint height_right=nodes[n.children[true]].height;
37 | if (height_left>height_right)
38 | n.height=height_left+1;
39 | else
40 | n.height=height_right+1;
41 | }
42 | function balance_factor(uint value) constant private returns (int bf) {
43 | Node n=nodes[value];
44 | return int(nodes[n.children[false]].height)-int(nodes[n.children[true]].height);
45 | }
46 | function rotate(uint value,bool dir) private {
47 | bool other_dir=!dir;
48 | Node n=nodes[value];
49 | bool side=n.side;
50 | uint parent=n.parent;
51 | uint value_new=n.children[other_dir];
52 | Node n_new=nodes[value_new];
53 | uint orphan=n_new.children[dir];
54 | Node p=nodes[parent];
55 | Node o=nodes[orphan];
56 | p.children[side]=value_new;
57 | n_new.side=side;
58 | n_new.parent=parent;
59 | n_new.children[dir]=value;
60 | n.parent=value_new;
61 | n.side=dir;
62 | n.children[other_dir]=orphan;
63 | o.parent=value;
64 | o.side=other_dir;
65 | update_height(value);
66 | update_height(value_new);
67 | update_count(value);
68 | update_count(value_new);
69 | }
70 | function rebalance_insert(uint n_value) private {
71 | update_height(n_value);
72 | Node n=nodes[n_value];
73 | uint p_value=n.parent;
74 | if (p_value!=0) {
75 | int p_bf=balance_factor(p_value);
76 | bool side=n.side;
77 | int sign;
78 | if (side)
79 | sign=-1;
80 | else
81 | sign=1;
82 | if (p_bf == sign*2) {
83 | if (balance_factor(n_value) == (-1 * sign))
84 | rotate(n_value,side);
85 | rotate(p_value,!side);
86 | }
87 | else if (p_bf != 0)
88 | rebalance_insert(p_value);
89 | }
90 | }
91 | function rebalance_delete(uint p_value,bool side) private{
92 | if (p_value!=0) {
93 | update_height(p_value);
94 | int p_bf=balance_factor(p_value);
95 | bool dir=side;
96 | int sign;
97 | if (side)
98 | sign=1;
99 | else
100 | sign=-1;
101 | int bf=balance_factor(p_value);
102 | if (bf==(2*sign)) {
103 | Node p=nodes[p_value];
104 | uint s_value=p.children[!side];
105 | int s_bf=balance_factor(s_value);
106 | if (s_bf == (-1 * sign))
107 | rotate(s_value,!side);
108 | rotate(p_value,side);
109 | if (s_bf!=0){
110 | p=nodes[p_value];
111 | rebalance_delete(p.parent,p.side);
112 | }
113 | }
114 | else if (p_bf != sign){
115 | p=nodes[p_value];
116 | rebalance_delete(p.parent,p.side);
117 | }
118 | }
119 | }
120 | function fix_parents(uint parent,bool side) private {
121 | if(parent!=0) {
122 | update_count(parent);
123 | update_counts(parent);
124 | rebalance_delete(parent,side);
125 | }
126 | }
127 | function insert_helper(uint p_value,bool side,uint value) private {
128 | Node root=nodes[p_value];
129 | uint c_value=root.children[side];
130 | if (c_value==0){
131 | root.children[side]=value;
132 | Node child=nodes[value];
133 | child.parent=p_value;
134 | child.side=side;
135 | child.height=1;
136 | child.count=1;
137 | update_counts(value);
138 | rebalance_insert(value);
139 | }
140 | else if (c_value==value){
141 | nodes[c_value].dupes++;
142 | update_count(value);
143 | update_counts(value);
144 | }
145 | else{
146 | bool side_new=(value >= c_value);
147 | insert_helper(c_value,side_new,value);
148 | }
149 | }
150 | function insert(uint value) {
151 | if (value==0)
152 | nodes[value].dupes++;
153 | else{
154 | insert_helper(0,true,value);
155 | }
156 | }
157 | function rightmost_leaf(uint value) constant private returns (uint leaf) {
158 | uint child=nodes[value].children[true];
159 | if (child!=0)
160 | return rightmost_leaf(child);
161 | else
162 | return value;
163 | }
164 | function zero_out(uint value) private {
165 | Node n=nodes[value];
166 | n.parent=0;
167 | n.side=false;
168 | n.children[false]=0;
169 | n.children[true]=0;
170 | n.count=0;
171 | n.height=0;
172 | n.dupes=0;
173 | }
174 | function remove_branch(uint value,uint left,uint right) private {
175 | uint ipn=rightmost_leaf(left);
176 | Node i=nodes[ipn];
177 | uint dupes=i.dupes;
178 | remove_helper(ipn);
179 | Node n=nodes[value];
180 | uint parent=n.parent;
181 | Node p=nodes[parent];
182 | uint height=n.height;
183 | bool side=n.side;
184 | uint count=n.count;
185 | right=n.children[true];
186 | left=n.children[false];
187 | p.children[side]=ipn;
188 | i.parent=parent;
189 | i.side=side;
190 | i.count=count+dupes-n.dupes;
191 | i.height=height;
192 | i.dupes=dupes;
193 | if (left!=0) {
194 | i.children[false]=left;
195 | nodes[left].parent=ipn;
196 | }
197 | if (right!=0) {
198 | i.children[true]=right;
199 | nodes[right].parent=ipn;
200 | }
201 | zero_out(value);
202 | update_counts(ipn);
203 | }
204 | function remove_helper(uint value) private {
205 | Node n=nodes[value];
206 | uint parent=n.parent;
207 | bool side=n.side;
208 | Node p=nodes[parent];
209 | uint left=n.children[false];
210 | uint right=n.children[true];
211 | if ((left == 0) && (right == 0)) {
212 | p.children[side]=0;
213 | zero_out(value);
214 | fix_parents(parent,side);
215 | }
216 | else if ((left !=0) && (right != 0)) {
217 | remove_branch(value,left,right);
218 | }
219 | else {
220 | uint child=left+right;
221 | Node c=nodes[child];
222 | p.children[side]=child;
223 | c.parent=parent;
224 | c.side=side;
225 | zero_out(value);
226 | fix_parents(parent,side);
227 | }
228 | }
229 | function remove(uint value){
230 | Node n=nodes[value];
231 | if (value==0){
232 | if (n.dupes==0)
233 | return;
234 | }
235 | else{
236 | if (n.count==0)
237 | return;
238 | }
239 | if (n.dupes>0) {
240 | n.dupes--;
241 | if(value!=0)
242 | n.count--;
243 | fix_parents(n.parent,n.side);
244 | }
245 | else
246 | remove_helper(value);
247 | }
248 | function rank(uint value) constant returns (uint smaller){
249 | if(value!=0){
250 | smaller=nodes[0].dupes;
251 | uint cur=nodes[0].children[true];
252 | Node cur_node=nodes[cur];
253 | while(true){
254 | if (cur<=value){
255 | if(cur uint) children;
359 | uint parent;
360 | bool side;
361 | uint height;
362 | uint count;
363 | uint dupes;
364 | }
365 | mapping(uint => Node) nodes;
366 | }
367 |
368 |
369 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Order Statistic Tree implementation in the Ethereum Solidity Language
2 |
3 | ## Rationale
4 | Most smart contracts in the ethereum smart contract system will probably involve products and/or users. In many instances, it may be necessary for the contract to rank these products or users to make a decision. This is particularly important for contracts involving a reputation or auction algorithm [1].
5 |
6 | Common ranking statistics include:
7 |
8 | - Determining percentile of a value
9 | - Determining membership in the "top n" for a value
10 | - Determining the rank order of a value
11 | - Determining the median
12 | - Determining a value in a certain position in the ordered dataset.
13 |
14 | The naïve algorithm for ranking data involves sorting the entire list of values and determining position in this list. However, in the ethereum system this is not viable for several reasons:
15 |
16 | 1. Sorting a list repeatedly as values are inserted/removed is inefficient, and would be extremely costly in terms of an ethereum gas price for execution.
17 | 2. Blocks in ethereum have a fixed gas limit. Therefore, if a "global" operation needs to be performed in a single transaction, such as occassionally sorting all products/users on some metric, it may simply be impossible to perform this transaction after a certain number of products/users is reached by a contract... your dapp would break if it became too popular.
18 |
19 | Therefore, it is necessary to implement a data structure in an ethereum contract that maintains a sorted set of values at all times, even as new values are inserted/removed. For this contract, we achieve this by implementing an [Order Statistic Tree](http://en.wikipedia.org/wiki/Order_statistic_tree) with a balanced tree structure via the [AVL method](http://en.wikipedia.org/wiki/AVL_tree). Using this data structure, the OrderStatisticTree contract can offer O(logn) inserts, removals, percentiles, topn, and rank order determination [2] [3].
20 |
21 | ## Running this contract on go-ethereum
22 |
23 | To try this contract via go-ethereum, simply:
24 |
25 | 1. Host the files in this repo on a web server on your local machine
26 | 2. Run the go ethereum CLI client on localhost:8080 with the "-rpc" flag enabled (or modify ost_test.js to use a different JSON-RPC endpoint.) Make sure you have some ether currency before continuing with the following steps. [3]
27 | 3. Launch "ost_test.html" in Google Chrome.
28 | 4. Press "publish contract" to publish the OST contract _(Note: This will publish a binary version of the contract, already compiled- At this time, go-ethereum does not yet contain support for compiling the solidity language. See steps below for separate compilation.)_
29 | 5. Wait 12 seconds or more for a block to be mined _(In the future, I'll modify the contract to wait automatically.)_
30 | 6. Press either "Run tests" to run programmer-created tests, or "Run generative tests" to run algorithmically generated tests designed to deeply exercise the tree balancing algorithms.
31 |
32 | Here is what the output should look like after clicking "Run Tests" button (see lower right panel): http://jsfiddle.net/zwxsqcr0/1/
33 |
34 | At this point, you should see output in the browser UI exercising functions in the contract, showing outputs and test results, as well as showing store information extracted from the contract for debugging [4].
35 |
36 | ## Disclaimer
37 |
38 | This contract has been heavily tested with random scripts, however ethereum is an extremely alpha project right now and the OST is extremely alpha as well, and almost certainly contains bugs. I can take no responsibility if anything bad happens to you if you use this contract. Also, be aware that **in actual use you MUST implement "gatekeeper" code of some sort in the mutating public functions of the contract, or any random ethereum user can modify data in the contract at will.** [5]
39 |
40 | ## Documentation of Public Contract Functions
41 |
42 | - **insert(uint value)**: Places a new value into the tree. _Duplicates are permitted_.
43 | - **remove(uint value)**: Removes a value, if it exists. _Only removes a single value if there are duplicates_.
44 | - **rank(uint value)**: Returns the position of the item in the list, if items were sorted from smallest to largest.
45 | - **select_at(uint pos)**: Returns the value at the given location in the dataset, ranked from lowest to highest.
46 | - **duplicates(uint value)**: Returns how many instances of this value are currently stored.
47 | - **count()**: Returns the total count of values in the tree.
48 | - **in_top_n(uint value,uint n)**: Indicates whether the given item is in the top n values in the tree (only true for duplicates if all members are in the "top n".)
49 | - **percentile(uint value)**: Returns the percentile of the value in the tree.
50 | - **at_percentile(uint percentile)**: Returns the value at the given percentile.
51 | - **permille(uint value)**: Returns the permille of the value in the tree. (This is like percentile, just with thousands instead of hundreds.)
52 | - **at_permille(uint permille)**: Returns the value at the given permille.
53 | - **median()**: Returns the median of all values. (Returns the higher value if there are an even number of values.)
54 | - **node_?(uint value)**: These are various low-level debugging functions that will likely be removed in future versions of this contract.
55 |
56 | ## Compiling the Contract
57 |
58 | This contract was compiled using cpp-ethereum/solc, using the flags "solc OrderStatisticTree.sol --json-abi file --binary file".
59 |
60 | ## Footnotes
61 |
62 | [1]: There is already a [heap implementation](https://github.com/ethereum/serpent/blob/master/examples/cyberdyne/heap.se) available in the ethereum serpent dialect that can be used for many auction types. However, other auction algorithms require an order statistic tree or similar structure for efficient implementation.
63 |
64 | [2]: Note that the underlying data structure algos in ethereum already carry an O(logn^2) limitation, so technically speaking this OST contract has O(logn^3) performance characteristics. (Read articles from [the official ethereum blog](http://blog.ethereum.org) for details on ethereum performance on this subject and others.
65 |
66 | [3]: Go ethereum is currently under heavy development. If you are reading this in early 2015 you may want to review some [important information here](http://forum.ethereum.org/discussion/1784/my-working-steps-go-ethereum-cli-json-rpc-chrome-browser-etherum-js-solidity) regarding the go-ethereum JSON-RPC interface to get things working.
67 |
68 | [4]: My implementation for showing debugging output is inefficient and the main reason for the slowness in running the tests- This would not be an issue in actual use.
69 |
70 | [5]: Currently the only mutating public functions in this contract are *insert()* and *remove()*.
71 |
72 | ## Copyright & License
73 |
74 | Licensed under GNU GENERAL PUBLIC LICENSE Version 3
75 |
76 | Copyright © 2015 Conrad Barski
--------------------------------------------------------------------------------
/bignumber.min.js:
--------------------------------------------------------------------------------
1 | /*! bignumber.js v2.0.0 https://github.com/MikeMcl/bignumber.js/LICENCE */
2 | (function(n){"use strict";function t(n,i){var b,a,l,p,o,w,s=this;if(!(s instanceof t))return new t(n,i);if(n instanceof t){if(i==null){u=0;s.s=n.s;s.e=n.e;s.c=(n=n.c)?n.slice():n;return}n+=""}else if(p=(o=typeof n)=="number"){if(i==null&&n===~~n){for(s.s=1/n<0?(n=-n,-1):1,a=u=0,l=n;l>=10;l/=10,a++);s.e=a;s.c=[n];return}n=n===0&&1/n<0?"-0":n+""}else o!="string"&&(n+="");if(o=n,i==null&&ft.test(o))s.s=o.charCodeAt(0)===45?(o=o.slice(1),-1):1;else{if(i==10)return s=new t(o),y(s,c+s.e+1,h);if(o=lt.call(o).replace(/^\+(?!-)/,""),s.s=o.charCodeAt(0)===45?(o=o.replace(/^-(?!-)/,""),-1):1,i!=null?i!=~~i&&d||(e=!(i>=2&&i<65))?(f(i,2),w=ft.test(o)):(b="["+ut.slice(0,i=i|0)+"]+",o=o.replace(/\.$/,"").replace(/^\./,"0."),(w=new RegExp("^"+b+"(?:\\."+b+")?$",i<37?"i":"").test(o))?(p&&(o.replace(/^0\.0*|\./,"").length>15&&f(n,0),p=!p),o=ct(o,10,i,s.s)):o!="Infinity"&&o!="NaN"&&(f(n,1,i),n="NaN")):w=ft.test(o),!w){s.c=s.e=null;o!="Infinity"&&(o!="NaN"&&f(n,3),s.s=null);u=0;return}}for((a=o.indexOf("."))>-1&&(o=o.replace(".","")),(l=o.search(/e/i))>0?(a<0&&(a=l),a+=+o.slice(l+1),o=o.substring(0,l)):a<0&&(a=o.length),l=0;o.charCodeAt(l)===48;l++);for(i=o.length;o.charCodeAt(--i)===48;);if(o=o.slice(l,i+1),o)if(i=o.length,p&&i>15&&f(n,0),a=a-l-1,a>v)s.c=s.e=null;else if(a=10;u/=10,f++);return(i=f+i*r-1)>v?n.c=n.e=null:ii-1&&(r[u+1]==null&&(r[u+1]=0),r[u+1]+=r[u]/i|0,r[u]%=i)}return r.reverse()}function ct(n,i,r,u){var l,e,v,y,s,f,w,o=n.indexOf("."),p=h;for(r<37&&(n=n.toLowerCase()),o>=0&&(n=n.replace(".",""),w=new t(r),s=w.pow(n.length-o),w.c=ht(s.toFixed(),10,i),w.e=w.c.length),f=ht(n,r,i),e=v=f.length;f[--v]==0;f.pop());if(!f[0])return"0";if(o<0?--e:(s.c=f,s.e=e,s.s=u,s=a(s,w,c,p,i),f=s.c,y=s.r,e=s.e),l=e+c+1,o=f[l],v=i/2,y=y||l<0||f[l+1]!=null,y=p<4?(o!=null||y)&&(p==0||p==(s.s<0?3:2)):o>v||o==v&&(p==4||y||p==6&&f[l-1]&1||p==(s.s<0?8:7)),l<1||!f[0])f.length=1,v=0,y?(f[0]=1,e=-c):e=f[0]=0;else{if(f.length=l,y)for(--i;++f[--l]>i;)f[l]=0,l||(++e,f.unshift(1));for(v=f.length;!f[--v];);}for(o=0,n="";o<=v;n+=ut.charAt(f[o++]));if(e<0){for(;++e;n="0"+n);n="0."+n}else if(o=n.length,++e>o)for(e-=o;e--;n+="0");else e1&&(u=u.charAt(0)+"."+u.slice(1));u+=(f<0?"e":"e+")+f}else{if(r=u.length,f<0){for(e=o-r;++f;u="0"+u);u="0."+u}else if(++f>r){for(e=o-f,f-=r;f--;u+="0");e>0&&(u+=".")}else e=o-r,f0&&(u+=".");if(e>0)for(;e--;u+="0");}return n.s<0&&n.c[0]?"-"+u:u}function f(n,t,i,r,f,o){if(d){var c,s=["new BigNumber","cmp","div","eq","gt","gte","lt","lte","minus","mod","plus","times","toFraction","divToInt"][u?u<0?-u:u:1/u<0?1:0]+"()",h=e?" out of range":" not a"+(f?" non-zero":"n")+" integer";h=([s+" number type has more than 15 significant digits",s+" not a base "+i+" number",s+" base"+h,s+" not a number"][t]||i+"() "+t+(o?" not a boolean or binary digit":h+(r?" or not ["+(e?" negative, positive":" integer, integer")+" ]":"")))+": "+n;e=u=0;c=new Error(h);c.name="BigNumber Error";throw c;}}function y(n,t,i,u){var c,o,e,s,a,h,p,f,y=st;if(f=n.c){n:{for(c=1,s=f[0];s>=10;s/=10,c++);if(o=t-c,o<0)o+=r,e=t,a=f[h=0],p=a/y[c-e-1]%10|0;else if(h=Math.ceil((o+1)/r),h>=f.length)if(u){for(;f.length<=h;f.push(0));a=p=0;c=1;o%=r;e=o-r+1}else break n;else{for(a=s=f[h],c=1;s>=10;s/=10,c++);o%=r;e=o-r+c;p=e<0?0:a/y[c-e-1]%10|0}if(u=u||t<0||f[h+1]!=null||(e<0?a:a%y[c-e-1]),u=i<4?(p||u)&&(i==0||i==(n.s<0?3:2)):p>5||p==5&&(i==4||u||i==6&&(o>0?e>0?a/y[c-e]:0:f[h-1])%10&1||i==(n.s<0?8:7)),t<1||!f[0])return f.length=0,u?(t-=n.e+1,f[0]=y[t%r],n.e=-t||0):f[0]=n.e=0,n;if(o==0?(f.length=h,s=1,h--):(f.length=h+1,s=y[r-o],f[h]=e>0?g(a/y[c-e]%y[e])*s:0),u)for(;;)if(h==0){for(o=1,e=f[0];e>=10;e/=10,o++);for(e=f[0]+=s,s=1;e>=10;e/=10,s++);o!=s&&(n.e++,f[0]==l&&(f[0]=1));break}else{if(f[h]+=s,f[h]!=l)break;f[h--]=0;s=1}for(o=f.length;f[--o]===0;f.pop());}n.e>v?n.c=n.e=null:n.ei)||w(n)!=n&&n!==0)},l=a&&typeof a=="object"?function(){if(a.hasOwnProperty(t))return(n=a[t])!=null}:function(){if(y.length>g)return(n=y[g++])!=null};if(l(t="DECIMAL_PLACES")&&(r(n,0,o)?c=n|0:f(n,t,s)),i[t]=c,l(t="ROUNDING_MODE")&&(r(n,0,8)?h=n|0:f(n,t,s)),i[t]=h,l(t="EXPONENTIAL_AT")&&(r(n,-o,o)?p=-(k=~~(n<0?-n:+n)):!e&&n&&r(n[0],-o,0)&&r(n[1],0,o)?(p=~~n[0],k=~~n[1]):f(n,t,s,1)),i[t]=[p,k],l(t="RANGE")&&(r(n,-o,o)&&~~n?nt=-(v=~~(n<0?-n:+n)):!e&&n&&r(n[0],-o,-1)&&r(n[1],1,o)?(nt=~~n[0],v=~~n[1]):f(n,t,s,1,1)),i[t]=[nt,v],l(t="ERRORS")&&(n===!!n||n===1||n===0?(e=u=0,w=(d=!!n)?parseInt:parseFloat):f(n,t,s,0,0,1)),i[t]=d,l(t="FORMAT"))if(typeof n=="object")b=n;else if(d){i=new Error(s+"() "+t+" not an object: "+n);i.name="BigNumber Error";throw i;}return i[t]=b,i};a=function(){function n(n,t,i){var f,e,o,h,r=0,u=n.length,c=t%s,l=t/s|0;for(n=n.slice();u--;)o=n[u]%s,h=n[u]/s|0,f=l*o+h*c,e=c*o+f%s*s+r,r=(e/i|0)+(f/s|0)+l*h,n[u]=e%i;return r&&n.unshift(r),n}function i(n,t,i,r){var u,f;if(i!=r)f=i>r?1:-1;else for(u=f=0;ut[u]?1:-1;break}return f}function u(n,t,i,r){for(var u=0;i--;)n[i]-=u,u=n[i]1;n.shift());}return function(f,e,o,s,h){var nt,ut,a,ot,p,tt,ft,it,et,v,w,st,ht,rt,lt,k,ct,d=f.s==e.s?1:-1,b=f.c,c=e.c;if(!b||!b[0]||!c||!c[0])return new t(!f.s||!e.s||(b?c&&b[0]==c[0]:!c)?NaN:b&&b[0]==0||!c?d*0:d/0);for(it=new t(d),et=it.c=[],ut=f.e-e.e,d=o+ut+1,h||(h=l,ut=(rt=f.e/r,a=rt|0,rt>0||rt===a?a:a-1)-(k=e.e/r,a=k|0,k>0||k===a?a:a-1),d=d/r|0),a=0;c[a]==(b[a]||0);a++);if(c[a]>(b[a]||0)&&ut--,d<0)et.push(1),ot=!0;else{for(rt=b.length,k=c.length,a=0,d+=2,p=g(h/(c[0]+1)),p>1&&(c=n(c,p,h),b=n(b,p,h),k=c.length,rt=b.length),ht=k,v=b.slice(0,k),w=v.length;w=h/2&<++;do p=0,nt=i(c,v,k,w),nt<0?(st=v[0],k!=w&&(st=st*h+(v[1]||0)),p=g(st/lt),p>1?(p>=h&&(p=h-1),tt=n(c,p,h),ft=tt.length,w=v.length,nt=i(tt,v,ft,w),nt==1&&(p--,u(tt,k=10;d/=10,a++);y(it,o+(it.e=a+ut*r-1)+1,s,ot)}else it.e=ut,it.r=+ot;return it}}();i.absoluteValue=i.abs=function(){var n=new t(this);return n.s<0&&(n.s=1),n};i.ceil=function(){return y(new t(this),this.e+1,2)};i.comparedTo=i.cmp=function(n,i){var f,l=this,e=l.c,o=(u=-u,n=new t(n,i)).c,r=l.s,c=n.s,s=l.e,h=n.e;if(!r||!c)return null;if(f=e&&!e[0],i=o&&!o[0],f||i)return f?i?0:-c:r;if(r!=c)return r;if(f=r<0,i=s==h,!e||!o)return i?0:!e^f?1:-1;if(!i)return s>h^f?1:-1;for(r=-1,c=(s=e.length)<(h=o.length)?s:h;++ro[r]^f?1:-1;return s==h?0:s>h^f?1:-1};i.decimalPlaces=i.dp=function(){var n,t,i=this.c;if(!i)return null;if(n=((t=i.length-1)-g(this.e/r))*r,t=i[t])for(;t%10==0;t/=10,n--);return n<0&&(n=0),n};i.dividedBy=i.div=function(n,i){return u=2,a(this,new t(n,i),c,h)};i.dividedToIntegerBy=i.divToInt=function(n,i){return u=13,a(this,new t(n,i),0,1)};i.equals=i.eq=function(n,t){return u=3,this.cmp(n,t)===0};i.floor=function(){return y(new t(this),this.e+1,3)};i.greaterThan=i.gt=function(n,t){return u=4,this.cmp(n,t)>0};i.greaterThanOrEqualTo=i.gte=function(n,t){return u=5,(t=this.cmp(n,t))==1||t===0};i.isFinite=function(){return!!this.c};i.isInteger=i.isInt=function(){return!!this.c&&g(this.e/r)>this.c.length-2};i.isNaN=function(){return!this.s};i.isNegative=i.isNeg=function(){return this.s<0};i.isZero=function(){return!!this.c&&this.c[0]==0};i.lessThan=i.lt=function(n,t){return u=6,this.cmp(n,t)<0};i.lessThanOrEqualTo=i.lte=function(n,t){return u=7,(t=this.cmp(n,t))==-1||t===0};i.minus=function(n,i){var e,c,v,w,p=this,s=p.s;if(u=8,n=new t(n,i),i=n.s,!s||!i)return new t(NaN);if(s!=i)return n.s=-i,p.plus(n);var y=p.e/r,a=n.e/r,f=p.c,o=n.c;if(!y||!a){if(!f||!o)return f?(n.s=-i,n):new t(o?p:NaN);if(!f[0]||!o[0])return o[0]?(n.s=-i,n):new t(f[0]?p:h==3?-0:0)}if(e=y|0,y=y>0||y===e?e:e-1,e=a|0,a=a>0||a===e?e:e-1,f=f.slice(),s=y-a){for((w=s<0)?(s=-s,v=f):(a=y,v=o),v.reverse(),i=s;i--;v.push(0));v.reverse()}else for(c=(w=(s=f.length)<(i=o.length))?s:i,s=i=0;i0)for(;i--;f[e++]=0);for(i=l-1;c>s;){if(f[--c]0||c===f?f:f-1,f=o|0,o=o>0||o===f?f:f-1,e=e.slice(),f=c-o){for(f>0?(o=c,h=s):(f=-f,h=e),h.reverse();f--;h.push(0));h.reverse()}for(f=e.length,i=s.length,f-i<0&&(h=s,s=e,e=h,i=f),f=0;i;)f=(e[--i]=e[i]+s[i]+f)/l|0,e[i]%=l;return f&&(e.unshift(f),++o),et(n,e,o)};i.round=function(n,i){return n=n==null||((e=n<0||n>o)||w(n)!=n)&&!f(n,"decimal places","round")?0:n|0,i=i==null||((e=i<0||i>8)||w(i)!=i&&i!==0)&&!f(i,"mode","round")?h:i|0,y(new t(this),n+this.e+1,i)};i.squareRoot=i.sqrt=function(){var v,i,r,s,f,e=this,o=e.c,n=e.s,u=e.e,l=c+4,p=new t("0.5");if(n!==1||!o||!o[0])return new t(!n||n<0&&(!o||o[0])?NaN:o?e:1/0);if(n=Math.sqrt(+e),n==0||n==1/0?(i=tt(o),(i.length+u)%2==0&&(i+="0"),n=Math.sqrt(i),u=g((u+1)/2)-(u<0||u%2),n==1/0?i="1e"+u:(i=n.toExponential(),i=i.slice(0,i.indexOf("e")+1)+u),r=new t(i)):r=new t(n.toString()),r.c[0])for(u=r.e,n=u+l,n<3&&(n=0);;)if(f=r,r=p.times(f.plus(a(e,f,l,1))),tt(f.c).slice(0,n)===(i=tt(r.c)).slice(0,n))if(r.e0||c===e?e:e-1)+(e=f|0,f>0||f===e?e:e-1),v=o.length,i=h.length,v=0;){for(p=0,f=v+c,w=v,d=h[c]%s,g=h[c]/s|0;f>c;)y=o[--w]%s,k=o[w]/s|0,b=g*y+k*d,y=d*y+b%s*s+a[f]+p,p=(y/l|0)+(b/s|0)+g*k,a[f--]=y%l;a[f]=p}return p?++e:a.shift(),et(n,a,e)};i.toExponential=function(n){var t=this;return t.c?rt(t,n==null||((e=n<0||n>o)||w(n)!=n&&n!==0)&&!f(n,"decimal places","toExponential")?null:n|0,1):t.toString()};i.toFixed=function(n){var t,i=this,r=p,u=k;return n=n==null||((e=n<0||n>o)||w(n)!=n&&n!==0)&&!f(n,"decimal places","toFixed")?null:i.e+(n|0),p=-(k=1/0),n!=null&&i.c?(t=rt(i,n),i.s<0&&i.c&&(i.c[0]?t.indexOf("-")<0&&(t="-"+t):t=t.replace("-",""))):t=i.toString(),p=r,k=u,t};i.toFormat=function(n){var f=this;if(!f.c)return f.toString();var t,h=f.s<0,c=b.groupSeparator,r=+b.groupSize,u=+b.secondaryGroupSize,l=f.toFixed(n).split("."),i=l[0],s=l[1],e=h?i.slice(1):i,o=e.length;if(u&&(t=r,r=u,u=t,o-=t),r>0&&o>0){for(t=o%r||r,i=e.substr(0,t);t0&&(i+=c+e.slice(t));h&&(i="-"+i)}return s?i+b.decimalSeparator+((u=+b.fractionGroupSize)?s.replace(new RegExp("\\d{"+u+"}\\B","g"),"$&"+b.fractionGroupSeparator):s):i};i.toFraction=function(n){var ut,c,i,w,k,o,s,nt,rt,l=c=new t(it),y=s=new t(it),b=this,ft=b.c,p=new t(it);if(!ft)return b.toString();for(rt=tt(ft),w=p.e=rt.length-b.e-1,p.c[0]=st[(k=w%r)<0?r+k:k],(n==null||(!(u=12,o=new t(n)).s||(e=o.cmp(l)<0||!o.c)||d&&g(o.e/r)0)&&(n=w>0?p:l),k=v,v=1/0,o=new t(rt),s.c[0]=0;;){if(nt=a(o,p,0,1),i=c.plus(nt.times(y)),i.cmp(n)==1)break;c=y;y=i;l=s.plus(nt.times(i=l));s=i;p=o.minus(nt.times(i=p));o=i}return i=a(n.minus(c),y,0,1),s=s.plus(i.times(l)),c=c.plus(i.times(y)),s.s=l.s=b.s,w*=2,ut=a(l,y,w,h).minus(b).abs().cmp(a(s,c,w,h).minus(b).abs())<1?[l.toString(),y.toString()]:[s.toString(),c.toString()],v=k,ut};i.toNumber=function(){var n=this;return+n||(n.s?0*n.s:NaN)};i.toPower=i.pow=function(n){var i=n*0==0?~~n:n,r=new t(this),u=new t(it);if(((e=n<-ot||n>ot)&&(i=n/0)||w(n)!=n&&n!==0&&!(i=NaN))&&!f(n,"exponent","pow")||!i)return new t(Math.pow(+r,i));for(i=i<0?-i:i;;){if(i&1&&(u=u.times(r)),i>>=1,!i)break;r=r.times(r)}return n<0?it.div(u):u};i.toPrecision=function(n){var t=this;return n==null||((e=n<1||n>o)||w(n)!=n)&&!f(n,"precision","toPrecision")||!t.c?t.toString():rt(t,--n|0,2)};i.toString=function(n){var r,t,o,u=this,i=u.e;if(i===null)t=u.s?"Infinity":"NaN";else{if(n==r&&(i<=p||i>=k))return rt(u,r,1);if(t=tt(u.c),i<0){for(;++i;t="0"+t);t="0."+t}else if(o=t.length,i>0)if(++i>o)for(i-=o;i--;t+="0");else i1)t=r+"."+t.slice(1);else if(r=="0")return r;if(n!=null)if((e=!(n>=2&&n<65))||n!=~~n&&d)f(n,"base","toS");else if(t=ct(t,n|0,10,u.s),t=="0")return t}return u.s<0?"-"+t:t};i.valueOf=i.toJSON=function(){return this.toString()};typeof module!="undefined"&&module.exports?module.exports=t:typeof define=="function"&&define.amd?define(function(){return t}):n.BigNumber=t})(this)
--------------------------------------------------------------------------------
/ethereum.js:
--------------------------------------------------------------------------------
1 | require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o.
17 | */
18 | /** @file abi.js
19 | * @authors:
20 | * Marek Kotewicz
21 | * Gav Wood
22 | * @date 2014
23 | */
24 |
25 | // TODO: is these line is supposed to be here?
26 | if ("build" !== 'build') {/*
27 | var BigNumber = require('bignumber.js'); // jshint ignore:line
28 | */}
29 |
30 | var web3 = require('./web3'); // jshint ignore:line
31 |
32 | BigNumber.config({ ROUNDING_MODE: BigNumber.ROUND_DOWN });
33 |
34 | var ETH_PADDING = 32;
35 |
36 | /// method signature length in bytes
37 | var ETH_METHOD_SIGNATURE_LENGTH = 4;
38 |
39 | /// Finds first index of array element matching pattern
40 | /// @param array
41 | /// @param callback pattern
42 | /// @returns index of element
43 | var findIndex = function (array, callback) {
44 | var end = false;
45 | var i = 0;
46 | for (; i < array.length && !end; i++) {
47 | end = callback(array[i]);
48 | }
49 | return end ? i - 1 : -1;
50 | };
51 |
52 | /// @returns a function that is used as a pattern for 'findIndex'
53 | var findMethodIndex = function (json, methodName) {
54 | return findIndex(json, function (method) {
55 | return method.name === methodName;
56 | });
57 | };
58 |
59 | /// @returns method with given method name
60 | var getMethodWithName = function (json, methodName) {
61 | var index = findMethodIndex(json, methodName);
62 | if (index === -1) {
63 | console.error('method ' + methodName + ' not found in the abi');
64 | return undefined;
65 | }
66 | return json[index];
67 | };
68 |
69 | /// Filters all function from input abi
70 | /// @returns abi array with filtered objects of type 'function'
71 | var filterFunctions = function (json) {
72 | return json.filter(function (current) {
73 | return current.type === 'function';
74 | });
75 | };
76 |
77 | /// Filters all events form input abi
78 | /// @returns abi array with filtered objects of type 'event'
79 | var filterEvents = function (json) {
80 | return json.filter(function (current) {
81 | return current.type === 'event';
82 | });
83 | };
84 |
85 | /// @param string string to be padded
86 | /// @param number of characters that result string should have
87 | /// @param sign, by default 0
88 | /// @returns right aligned string
89 | var padLeft = function (string, chars, sign) {
90 | return new Array(chars - string.length + 1).join(sign ? sign : "0") + string;
91 | };
92 |
93 | /// @param expected type prefix (string)
94 | /// @returns function which checks if type has matching prefix. if yes, returns true, otherwise false
95 | var prefixedType = function (prefix) {
96 | return function (type) {
97 | return type.indexOf(prefix) === 0;
98 | };
99 | };
100 |
101 | /// @param expected type name (string)
102 | /// @returns function which checks if type is matching expected one. if yes, returns true, otherwise false
103 | var namedType = function (name) {
104 | return function (type) {
105 | return name === type;
106 | };
107 | };
108 |
109 | var arrayType = function (type) {
110 | return type.slice(-2) === '[]';
111 | };
112 |
113 | /// Formats input value to byte representation of int
114 | /// If value is negative, return it's two's complement
115 | /// If the value is floating point, round it down
116 | /// @returns right-aligned byte representation of int
117 | var formatInputInt = function (value) {
118 | var padding = ETH_PADDING * 2;
119 | if (value instanceof BigNumber || typeof value === 'number') {
120 | if (typeof value === 'number')
121 | value = new BigNumber(value);
122 | value = value.round();
123 |
124 | if (value.lessThan(0))
125 | value = new BigNumber("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16).plus(value).plus(1);
126 | value = value.toString(16);
127 | }
128 | else if (value.indexOf('0x') === 0)
129 | value = value.substr(2);
130 | else if (typeof value === 'string')
131 | value = formatInputInt(new BigNumber(value));
132 | else
133 | value = (+value).toString(16);
134 | return padLeft(value, padding);
135 | };
136 |
137 | /// Formats input value to byte representation of string
138 | /// @returns left-algined byte representation of string
139 | var formatInputString = function (value) {
140 | return web3.fromAscii(value, ETH_PADDING).substr(2);
141 | };
142 |
143 | /// Formats input value to byte representation of bool
144 | /// @returns right-aligned byte representation bool
145 | var formatInputBool = function (value) {
146 | return '000000000000000000000000000000000000000000000000000000000000000' + (value ? '1' : '0');
147 | };
148 |
149 | /// Formats input value to byte representation of real
150 | /// Values are multiplied by 2^m and encoded as integers
151 | /// @returns byte representation of real
152 | var formatInputReal = function (value) {
153 | return formatInputInt(new BigNumber(value).times(new BigNumber(2).pow(128)));
154 | };
155 |
156 | var dynamicTypeBytes = function (type, value) {
157 | // TODO: decide what to do with array of strings
158 | if (arrayType(type) || type === 'string') // only string itself that is dynamic; stringX is static length.
159 | return formatInputInt(value.length);
160 | return "";
161 | };
162 |
163 | /// Setups input formatters for solidity types
164 | /// @returns an array of input formatters
165 | var setupInputTypes = function () {
166 |
167 | return [
168 | { type: prefixedType('uint'), format: formatInputInt },
169 | { type: prefixedType('int'), format: formatInputInt },
170 | { type: prefixedType('hash'), format: formatInputInt },
171 | { type: prefixedType('string'), format: formatInputString },
172 | { type: prefixedType('real'), format: formatInputReal },
173 | { type: prefixedType('ureal'), format: formatInputReal },
174 | { type: namedType('address'), format: formatInputInt },
175 | { type: namedType('bool'), format: formatInputBool }
176 | ];
177 | };
178 |
179 | var inputTypes = setupInputTypes();
180 |
181 | /// Formats input params to bytes
182 | /// @param contract json abi
183 | /// @param name of the method that we want to use
184 | /// @param array of params that will be formatted to bytes
185 | /// @returns bytes representation of input params
186 | var toAbiInput = function (json, methodName, params) {
187 | var bytes = "";
188 |
189 | var method = getMethodWithName(json, methodName);
190 | var padding = ETH_PADDING * 2;
191 |
192 | /// first we iterate in search for dynamic
193 | method.inputs.forEach(function (input, index) {
194 | bytes += dynamicTypeBytes(input.type, params[index]);
195 | });
196 |
197 | method.inputs.forEach(function (input, i) {
198 | var typeMatch = false;
199 | for (var j = 0; j < inputTypes.length && !typeMatch; j++) {
200 | typeMatch = inputTypes[j].type(method.inputs[i].type, params[i]);
201 | }
202 | if (!typeMatch) {
203 | console.error('input parser does not support type: ' + method.inputs[i].type);
204 | }
205 |
206 | var formatter = inputTypes[j - 1].format;
207 | var toAppend = "";
208 |
209 | if (arrayType(method.inputs[i].type))
210 | toAppend = params[i].reduce(function (acc, curr) {
211 | return acc + formatter(curr);
212 | }, "");
213 | else
214 | toAppend = formatter(params[i]);
215 |
216 | bytes += toAppend;
217 | });
218 | return bytes;
219 | };
220 |
221 | /// Check if input value is negative
222 | /// @param value is hex format
223 | /// @returns true if it is negative, otherwise false
224 | var signedIsNegative = function (value) {
225 | return (new BigNumber(value.substr(0, 1), 16).toString(2).substr(0, 1)) === '1';
226 | };
227 |
228 | /// Formats input right-aligned input bytes to int
229 | /// @returns right-aligned input bytes formatted to int
230 | var formatOutputInt = function (value) {
231 | value = value || "0";
232 | // check if it's negative number
233 | // it it is, return two's complement
234 | if (signedIsNegative(value)) {
235 | return new BigNumber(value, 16).minus(new BigNumber('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16)).minus(1);
236 | }
237 | return new BigNumber(value, 16);
238 | };
239 |
240 | /// Formats big right-aligned input bytes to uint
241 | /// @returns right-aligned input bytes formatted to uint
242 | var formatOutputUInt = function (value) {
243 | value = value || "0";
244 | return new BigNumber(value, 16);
245 | };
246 |
247 | /// @returns input bytes formatted to real
248 | var formatOutputReal = function (value) {
249 | return formatOutputInt(value).dividedBy(new BigNumber(2).pow(128));
250 | };
251 |
252 | /// @returns input bytes formatted to ureal
253 | var formatOutputUReal = function (value) {
254 | return formatOutputUInt(value).dividedBy(new BigNumber(2).pow(128));
255 | };
256 |
257 | /// @returns right-aligned input bytes formatted to hex
258 | var formatOutputHash = function (value) {
259 | return "0x" + value;
260 | };
261 |
262 | /// @returns right-aligned input bytes formatted to bool
263 | var formatOutputBool = function (value) {
264 | return value === '0000000000000000000000000000000000000000000000000000000000000001' ? true : false;
265 | };
266 |
267 | /// @returns left-aligned input bytes formatted to ascii string
268 | var formatOutputString = function (value) {
269 | return web3.toAscii(value);
270 | };
271 |
272 | /// @returns right-aligned input bytes formatted to address
273 | var formatOutputAddress = function (value) {
274 | return "0x" + value.slice(value.length - 40, value.length);
275 | };
276 |
277 | var dynamicBytesLength = function (type) {
278 | if (arrayType(type) || type === 'string') // only string itself that is dynamic; stringX is static length.
279 | return ETH_PADDING * 2;
280 | return 0;
281 | };
282 |
283 | /// Setups output formaters for solidity types
284 | /// @returns an array of output formatters
285 | var setupOutputTypes = function () {
286 |
287 | return [
288 | { type: prefixedType('uint'), format: formatOutputUInt },
289 | { type: prefixedType('int'), format: formatOutputInt },
290 | { type: prefixedType('hash'), format: formatOutputHash },
291 | { type: prefixedType('string'), format: formatOutputString },
292 | { type: prefixedType('real'), format: formatOutputReal },
293 | { type: prefixedType('ureal'), format: formatOutputUReal },
294 | { type: namedType('address'), format: formatOutputAddress },
295 | { type: namedType('bool'), format: formatOutputBool }
296 | ];
297 | };
298 |
299 | var outputTypes = setupOutputTypes();
300 |
301 | /// Formats output bytes back to param list
302 | /// @param contract json abi
303 | /// @param name of the method that we want to use
304 | /// @param bytes representtion of output
305 | /// @returns array of output params
306 | var fromAbiOutput = function (json, methodName, output) {
307 |
308 | output = output.slice(2);
309 | var result = [];
310 | var method = getMethodWithName(json, methodName);
311 | var padding = ETH_PADDING * 2;
312 |
313 | var dynamicPartLength = method.outputs.reduce(function (acc, curr) {
314 | return acc + dynamicBytesLength(curr.type);
315 | }, 0);
316 |
317 | var dynamicPart = output.slice(0, dynamicPartLength);
318 | output = output.slice(dynamicPartLength);
319 |
320 | method.outputs.forEach(function (out, i) {
321 | var typeMatch = false;
322 | for (var j = 0; j < outputTypes.length && !typeMatch; j++) {
323 | typeMatch = outputTypes[j].type(method.outputs[i].type);
324 | }
325 |
326 | if (!typeMatch) {
327 | console.error('output parser does not support type: ' + method.outputs[i].type);
328 | }
329 |
330 | var formatter = outputTypes[j - 1].format;
331 | if (arrayType(method.outputs[i].type)) {
332 | var size = formatOutputUInt(dynamicPart.slice(0, padding));
333 | dynamicPart = dynamicPart.slice(padding);
334 | var array = [];
335 | for (var k = 0; k < size; k++) {
336 | array.push(formatter(output.slice(0, padding)));
337 | output = output.slice(padding);
338 | }
339 | result.push(array);
340 | }
341 | else if (prefixedType('string')(method.outputs[i].type)) {
342 | dynamicPart = dynamicPart.slice(padding);
343 | result.push(formatter(output.slice(0, padding)));
344 | output = output.slice(padding);
345 | } else {
346 | result.push(formatter(output.slice(0, padding)));
347 | output = output.slice(padding);
348 | }
349 | });
350 |
351 | return result;
352 | };
353 |
354 | /// @returns display name for method eg. multiply(uint256) -> multiply
355 | var methodDisplayName = function (method) {
356 | var length = method.indexOf('(');
357 | return length !== -1 ? method.substr(0, length) : method;
358 | };
359 |
360 | /// @returns overloaded part of method's name
361 | var methodTypeName = function (method) {
362 | /// TODO: make it not vulnerable
363 | var length = method.indexOf('(');
364 | return length !== -1 ? method.substr(length + 1, method.length - 1 - (length + 1)) : "";
365 | };
366 |
367 | /// @param json abi for contract
368 | /// @returns input parser object for given json abi
369 | var inputParser = function (json) {
370 | var parser = {};
371 | filterFunctions(json).forEach(function (method) {
372 | var displayName = methodDisplayName(method.name);
373 | var typeName = methodTypeName(method.name);
374 |
375 | var impl = function () {
376 | var params = Array.prototype.slice.call(arguments);
377 | return toAbiInput(json, method.name, params);
378 | };
379 |
380 | if (parser[displayName] === undefined) {
381 | parser[displayName] = impl;
382 | }
383 |
384 | parser[displayName][typeName] = impl;
385 | });
386 |
387 | return parser;
388 | };
389 |
390 | /// @param json abi for contract
391 | /// @returns output parser for given json abi
392 | var outputParser = function (json) {
393 | var parser = {};
394 | filterFunctions(json).forEach(function (method) {
395 |
396 | var displayName = methodDisplayName(method.name);
397 | var typeName = methodTypeName(method.name);
398 |
399 | var impl = function (output) {
400 | return fromAbiOutput(json, method.name, output);
401 | };
402 |
403 | if (parser[displayName] === undefined) {
404 | parser[displayName] = impl;
405 | }
406 |
407 | parser[displayName][typeName] = impl;
408 | });
409 |
410 | return parser;
411 | };
412 |
413 | /// @param method name for which we want to get method signature
414 | /// @returns (promise) contract method signature for method with given name
415 | var methodSignature = function (name) {
416 | return web3.sha3(web3.fromAscii(name)).slice(0, 2 + ETH_METHOD_SIGNATURE_LENGTH * 2);
417 | };
418 |
419 | module.exports = {
420 | inputParser: inputParser,
421 | outputParser: outputParser,
422 | methodSignature: methodSignature,
423 | methodDisplayName: methodDisplayName,
424 | methodTypeName: methodTypeName,
425 | getMethodWithName: getMethodWithName,
426 | filterFunctions: filterFunctions,
427 | filterEvents: filterEvents
428 | };
429 |
430 |
431 | },{"./web3":8}],2:[function(require,module,exports){
432 | /*
433 | This file is part of ethereum.js.
434 |
435 | ethereum.js is free software: you can redistribute it and/or modify
436 | it under the terms of the GNU Lesser General Public License as published by
437 | the Free Software Foundation, either version 3 of the License, or
438 | (at your option) any later version.
439 |
440 | ethereum.js is distributed in the hope that it will be useful,
441 | but WITHOUT ANY WARRANTY; without even the implied warranty of
442 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
443 | GNU Lesser General Public License for more details.
444 |
445 | You should have received a copy of the GNU Lesser General Public License
446 | along with ethereum.js. If not, see .
447 | */
448 | /** @file contract.js
449 | * @authors:
450 | * Marek Kotewicz
451 | * @date 2014
452 | */
453 |
454 | var web3 = require('./web3');
455 | var abi = require('./abi');
456 | var eventImpl = require('./event');
457 |
458 | var addFunctionRelatedPropertiesToContract = function (contract) {
459 |
460 | contract.call = function (options) {
461 | contract._isTransact = false;
462 | contract._options = options;
463 | return contract;
464 | };
465 |
466 | contract.transact = function (options) {
467 | contract._isTransact = true;
468 | contract._options = options;
469 | return contract;
470 | };
471 |
472 | contract._options = {};
473 | ['gas', 'gasPrice', 'value', 'from'].forEach(function(p) {
474 | contract[p] = function (v) {
475 | contract._options[p] = v;
476 | return contract;
477 | };
478 | });
479 |
480 | };
481 |
482 | var addFunctionsToContract = function (contract, desc, address) {
483 | var inputParser = abi.inputParser(desc);
484 | var outputParser = abi.outputParser(desc);
485 |
486 | // create contract functions
487 | abi.filterFunctions(desc).forEach(function (method) {
488 |
489 | var displayName = abi.methodDisplayName(method.name);
490 | var typeName = abi.methodTypeName(method.name);
491 |
492 | var impl = function () {
493 | var params = Array.prototype.slice.call(arguments);
494 | var signature = abi.methodSignature(method.name);
495 | var parsed = inputParser[displayName][typeName].apply(null, params);
496 |
497 | var options = contract._options || {};
498 | options.to = address;
499 | options.data = signature + parsed;
500 |
501 | var isTransact = contract._isTransact === true || (contract._isTransact !== false && !method.constant);
502 | var collapse = options.collapse !== false;
503 |
504 | // reset
505 | contract._options = {};
506 | contract._isTransact = null;
507 |
508 | if (isTransact) {
509 | // it's used byt natspec.js
510 | // TODO: figure out better way to solve this
511 | web3._currentContractAbi = desc;
512 | web3._currentContractAddress = address;
513 | web3._currentContractMethodName = method.name;
514 | web3._currentContractMethodParams = params;
515 |
516 | // transactions do not have any output, cause we do not know, when they will be processed
517 | web3.eth.transact(options);
518 | return;
519 | }
520 |
521 | var output = web3.eth.call(options);
522 | var ret = outputParser[displayName][typeName](output);
523 | if (collapse)
524 | {
525 | if (ret.length === 1)
526 | ret = ret[0];
527 | else if (ret.length === 0)
528 | ret = null;
529 | }
530 | return ret;
531 | };
532 |
533 | if (contract[displayName] === undefined) {
534 | contract[displayName] = impl;
535 | }
536 |
537 | contract[displayName][typeName] = impl;
538 | });
539 | };
540 |
541 | var addEventRelatedPropertiesToContract = function (contract, desc, address) {
542 | contract.address = address;
543 |
544 | Object.defineProperty(contract, 'topics', {
545 | get: function() {
546 | return abi.filterEvents(desc).map(function (e) {
547 | return abi.methodSignature(e.name);
548 | });
549 | }
550 | });
551 |
552 | };
553 |
554 | var addEventsToContract = function (contract, desc, address) {
555 | // create contract events
556 | abi.filterEvents(desc).forEach(function (e) {
557 |
558 | var impl = function () {
559 | var params = Array.prototype.slice.call(arguments);
560 | var signature = abi.methodSignature(e.name);
561 | var event = eventImpl(address, signature);
562 | var o = event.apply(null, params);
563 | return web3.eth.watch(o);
564 | };
565 |
566 | impl.address = address;
567 |
568 | Object.defineProperty(impl, 'topics', {
569 | get: function() {
570 | return [abi.methodSignature(e.name)];
571 | }
572 | });
573 |
574 | // TODO: rename these methods, cause they are used not only for methods
575 | var displayName = abi.methodDisplayName(e.name);
576 | var typeName = abi.methodTypeName(e.name);
577 |
578 | if (contract[displayName] === undefined) {
579 | contract[displayName] = impl;
580 | }
581 |
582 | contract[displayName][typeName] = impl;
583 |
584 | });
585 | };
586 |
587 |
588 | /**
589 | * This method should be called when we want to call / transact some solidity method from javascript
590 | * it returns an object which has same methods available as solidity contract description
591 | * usage example:
592 | *
593 | * var abi = [{
594 | * name: 'myMethod',
595 | * inputs: [{ name: 'a', type: 'string' }],
596 | * outputs: [{name: 'd', type: 'string' }]
597 | * }]; // contract abi
598 | *
599 | * var myContract = web3.eth.contract('0x0123123121', abi); // creation of contract object
600 | *
601 | * myContract.myMethod('this is test string param for call'); // myMethod call (implicit, default)
602 | * myContract.call().myMethod('this is test string param for call'); // myMethod call (explicit)
603 | * myContract.transact().myMethod('this is test string param for transact'); // myMethod transact
604 | *
605 | * @param address - address of the contract, which should be called
606 | * @param desc - abi json description of the contract, which is being created
607 | * @returns contract object
608 | */
609 |
610 | var contract = function (address, desc) {
611 |
612 | // workaround for invalid assumption that method.name is the full anonymous prototype of the method.
613 | // it's not. it's just the name. the rest of the code assumes it's actually the anonymous
614 | // prototype, so we make it so as a workaround.
615 | // TODO: we may not want to modify input params, maybe use copy instead?
616 | desc.forEach(function (method) {
617 | if (method.name.indexOf('(') === -1) {
618 | var displayName = method.name;
619 | var typeName = method.inputs.map(function(i){return i.type; }).join();
620 | method.name = displayName + '(' + typeName + ')';
621 | }
622 | });
623 |
624 | var result = {};
625 | addFunctionRelatedPropertiesToContract(result);
626 | addFunctionsToContract(result, desc, address);
627 | addEventRelatedPropertiesToContract(result, desc, address);
628 | addEventsToContract(result, desc, address);
629 |
630 | return result;
631 | };
632 |
633 | module.exports = contract;
634 |
635 |
636 | },{"./abi":1,"./event":3,"./web3":8}],3:[function(require,module,exports){
637 | /*
638 | This file is part of ethereum.js.
639 |
640 | ethereum.js is free software: you can redistribute it and/or modify
641 | it under the terms of the GNU Lesser General Public License as published by
642 | the Free Software Foundation, either version 3 of the License, or
643 | (at your option) any later version.
644 |
645 | ethereum.js is distributed in the hope that it will be useful,
646 | but WITHOUT ANY WARRANTY; without even the implied warranty of
647 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
648 | GNU Lesser General Public License for more details.
649 |
650 | You should have received a copy of the GNU Lesser General Public License
651 | along with ethereum.js. If not, see .
652 | */
653 | /** @file event.js
654 | * @authors:
655 | * Marek Kotewicz
656 | * @date 2014
657 | */
658 |
659 | var implementationOfEvent = function (address, signature) {
660 |
661 | return function (options) {
662 | var o = options || {};
663 | o.address = o.address || address;
664 | o.topics = o.topics || [];
665 | o.topics.push(signature);
666 | return o;
667 | };
668 | };
669 |
670 | module.exports = implementationOfEvent;
671 |
672 |
673 | },{}],4:[function(require,module,exports){
674 | /*
675 | This file is part of ethereum.js.
676 |
677 | ethereum.js is free software: you can redistribute it and/or modify
678 | it under the terms of the GNU Lesser General Public License as published by
679 | the Free Software Foundation, either version 3 of the License, or
680 | (at your option) any later version.
681 |
682 | ethereum.js is distributed in the hope that it will be useful,
683 | but WITHOUT ANY WARRANTY; without even the implied warranty of
684 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
685 | GNU Lesser General Public License for more details.
686 |
687 | You should have received a copy of the GNU Lesser General Public License
688 | along with ethereum.js. If not, see .
689 | */
690 | /** @file filter.js
691 | * @authors:
692 | * Jeffrey Wilcke
693 | * Marek Kotewicz
694 | * Marian Oancea
695 | * Gav Wood
696 | * @date 2014
697 | */
698 |
699 | var web3 = require('./web3'); // jshint ignore:line
700 |
701 | /// should be used when we want to watch something
702 | /// it's using inner polling mechanism and is notified about changes
703 | var Filter = function(options, impl) {
704 | this.impl = impl;
705 | this.callbacks = [];
706 |
707 | if (typeof options !== "string") {
708 | // evaluate lazy properties
709 | options = {
710 | to: options.to,
711 | topic: options.topic,
712 | topics: options.topics,
713 | earliest: options.earliest,
714 | latest: options.latest,
715 | max: options.max,
716 | skip: options.skip,
717 | address: options.address
718 | };
719 | }
720 |
721 | this.id = impl.newFilter(options);
722 | web3.provider.startPolling({call: impl.changed, args: [this.id]}, this.id, this.trigger.bind(this));
723 | };
724 |
725 | /// alias for changed*
726 | Filter.prototype.arrived = function(callback) {
727 | this.changed(callback);
728 | };
729 |
730 | /// gets called when there is new eth/shh message
731 | Filter.prototype.changed = function(callback) {
732 | this.callbacks.push(callback);
733 | };
734 |
735 | /// trigger calling new message from people
736 | Filter.prototype.trigger = function(messages) {
737 | for (var i = 0; i < this.callbacks.length; i++) {
738 | for (var j = 0; j < messages.length; j++) {
739 | this.callbacks[i].call(this, messages[j]);
740 | }
741 | }
742 | };
743 |
744 | /// should be called to uninstall current filter
745 | Filter.prototype.uninstall = function() {
746 | this.impl.uninstallFilter(this.id);
747 | web3.provider.stopPolling(this.id);
748 | };
749 |
750 | /// should be called to manually trigger getting latest messages from the client
751 | Filter.prototype.messages = function() {
752 | return this.impl.getMessages(this.id);
753 | };
754 |
755 | /// alias for messages
756 | Filter.prototype.logs = function () {
757 | return this.messages();
758 | };
759 |
760 | module.exports = Filter;
761 |
762 | },{"./web3":8}],5:[function(require,module,exports){
763 | /*
764 | This file is part of ethereum.js.
765 |
766 | ethereum.js is free software: you can redistribute it and/or modify
767 | it under the terms of the GNU Lesser General Public License as published by
768 | the Free Software Foundation, either version 3 of the License, or
769 | (at your option) any later version.
770 |
771 | ethereum.js is distributed in the hope that it will be useful,
772 | but WITHOUT ANY WARRANTY; without even the implied warranty of
773 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
774 | GNU Lesser General Public License for more details.
775 |
776 | You should have received a copy of the GNU Lesser General Public License
777 | along with ethereum.js. If not, see .
778 | */
779 | /** @file httpsync.js
780 | * @authors:
781 | * Marek Kotewicz
782 | * Marian Oancea
783 | * @date 2014
784 | */
785 |
786 | if ("build" !== 'build') {/*
787 | var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; // jshint ignore:line
788 | */}
789 |
790 | var HttpSyncProvider = function (host) {
791 | this.handlers = [];
792 | this.host = host || 'http://localhost:8080';
793 | };
794 |
795 | /// Transforms inner message to proper jsonrpc object
796 | /// @param inner message object
797 | /// @returns jsonrpc object
798 | function formatJsonRpcObject(object) {
799 | return {
800 | jsonrpc: '2.0',
801 | method: object.call,
802 | params: object.args,
803 | id: object._id
804 | };
805 | }
806 |
807 | /// Transforms jsonrpc object to inner message
808 | /// @param incoming jsonrpc message
809 | /// @returns inner message object
810 | function formatJsonRpcMessage(message) {
811 | var object = JSON.parse(message);
812 |
813 | return {
814 | _id: object.id,
815 | data: object.result,
816 | error: object.error
817 | };
818 | }
819 |
820 | HttpSyncProvider.prototype.send = function (payload) {
821 | var data = formatJsonRpcObject(payload);
822 |
823 | var request = new XMLHttpRequest();
824 | request.open('POST', this.host, false);
825 | request.send(JSON.stringify(data));
826 |
827 | // check request.status
828 | return request.responseText;
829 | };
830 |
831 | module.exports = HttpSyncProvider;
832 |
833 |
834 | },{}],6:[function(require,module,exports){
835 | /*
836 | This file is part of ethereum.js.
837 |
838 | ethereum.js is free software: you can redistribute it and/or modify
839 | it under the terms of the GNU Lesser General Public License as published by
840 | the Free Software Foundation, either version 3 of the License, or
841 | (at your option) any later version.
842 |
843 | ethereum.js is distributed in the hope that it will be useful,
844 | but WITHOUT ANY WARRANTY; without even the implied warranty of
845 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
846 | GNU Lesser General Public License for more details.
847 |
848 | You should have received a copy of the GNU Lesser General Public License
849 | along with ethereum.js. If not, see .
850 | */
851 | /** @file providermanager.js
852 | * @authors:
853 | * Jeffrey Wilcke
854 | * Marek Kotewicz
855 | * Marian Oancea
856 | * Gav Wood
857 | * @date 2014
858 | */
859 |
860 | var web3 = require('./web3'); // jshint ignore:line
861 |
862 | /**
863 | * Provider manager object prototype
864 | * It's responsible for passing messages to providers
865 | * If no provider is set it's responsible for queuing requests
866 | * It's also responsible for polling the ethereum node for incoming messages
867 | * Default poll timeout is 12 seconds
868 | * If we are running ethereum.js inside ethereum browser, there are backend based tools responsible for polling,
869 | * and provider manager polling mechanism is not used
870 | */
871 | var ProviderManager = function() {
872 | this.polls = [];
873 | this.provider = undefined;
874 | this.id = 1;
875 |
876 | var self = this;
877 | var poll = function () {
878 | if (self.provider) {
879 | self.polls.forEach(function (data) {
880 | data.data._id = self.id;
881 | self.id++;
882 | var result = self.provider.send(data.data);
883 |
884 | result = JSON.parse(result);
885 |
886 | // dont call the callback if result is not an array, or empty one
887 | if (result.error || !(result.result instanceof Array) || result.result.length === 0) {
888 | return;
889 | }
890 |
891 | data.callback(result.result);
892 | });
893 | }
894 | setTimeout(poll, 1000);
895 | };
896 | poll();
897 | };
898 |
899 | /// sends outgoing requests
900 | ProviderManager.prototype.send = function(data) {
901 |
902 | data.args = data.args || [];
903 | data._id = this.id++;
904 |
905 | if (this.provider === undefined) {
906 | console.error('provider is not set');
907 | return null;
908 | }
909 |
910 | //TODO: handle error here?
911 | var result = this.provider.send(data);
912 | result = JSON.parse(result);
913 |
914 | if (result.error) {
915 | console.log(result.error);
916 | return null;
917 | }
918 |
919 | return result.result;
920 | };
921 |
922 | /// setups provider, which will be used for sending messages
923 | ProviderManager.prototype.set = function(provider) {
924 | this.provider = provider;
925 | };
926 |
927 | /// this method is only used, when we do not have native qt bindings and have to do polling on our own
928 | /// should be callled, on start watching for eth/shh changes
929 | ProviderManager.prototype.startPolling = function (data, pollId, callback) {
930 | this.polls.push({data: data, id: pollId, callback: callback});
931 | };
932 |
933 | /// should be called to stop polling for certain watch changes
934 | ProviderManager.prototype.stopPolling = function (pollId) {
935 | for (var i = this.polls.length; i--;) {
936 | var poll = this.polls[i];
937 | if (poll.id === pollId) {
938 | this.polls.splice(i, 1);
939 | }
940 | }
941 | };
942 |
943 | module.exports = ProviderManager;
944 |
945 |
946 | },{"./web3":8}],7:[function(require,module,exports){
947 | /*
948 | This file is part of ethereum.js.
949 |
950 | ethereum.js is free software: you can redistribute it and/or modify
951 | it under the terms of the GNU Lesser General Public License as published by
952 | the Free Software Foundation, either version 3 of the License, or
953 | (at your option) any later version.
954 |
955 | ethereum.js is distributed in the hope that it will be useful,
956 | but WITHOUT ANY WARRANTY; without even the implied warranty of
957 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
958 | GNU Lesser General Public License for more details.
959 |
960 | You should have received a copy of the GNU Lesser General Public License
961 | along with ethereum.js. If not, see .
962 | */
963 | /** @file qtsync.js
964 | * @authors:
965 | * Marek Kotewicz
966 | * Marian Oancea
967 | * @date 2014
968 | */
969 |
970 | var QtSyncProvider = function () {
971 | };
972 |
973 | QtSyncProvider.prototype.send = function (payload) {
974 | return navigator.qt.callMethod(JSON.stringify(payload));
975 | };
976 |
977 | module.exports = QtSyncProvider;
978 |
979 |
980 | },{}],8:[function(require,module,exports){
981 | /*
982 | This file is part of ethereum.js.
983 |
984 | ethereum.js is free software: you can redistribute it and/or modify
985 | it under the terms of the GNU Lesser General Public License as published by
986 | the Free Software Foundation, either version 3 of the License, or
987 | (at your option) any later version.
988 |
989 | ethereum.js is distributed in the hope that it will be useful,
990 | but WITHOUT ANY WARRANTY; without even the implied warranty of
991 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
992 | GNU Lesser General Public License for more details.
993 |
994 | You should have received a copy of the GNU Lesser General Public License
995 | along with ethereum.js. If not, see .
996 | */
997 | /** @file web3.js
998 | * @authors:
999 | * Jeffrey Wilcke
1000 | * Marek Kotewicz
1001 | * Marian Oancea
1002 | * Gav Wood
1003 | * @date 2014
1004 | */
1005 |
1006 | if ("build" !== 'build') {/*
1007 | var BigNumber = require('bignumber.js');
1008 | */}
1009 |
1010 | var ETH_UNITS = [
1011 | 'wei',
1012 | 'Kwei',
1013 | 'Mwei',
1014 | 'Gwei',
1015 | 'szabo',
1016 | 'finney',
1017 | 'ether',
1018 | 'grand',
1019 | 'Mether',
1020 | 'Gether',
1021 | 'Tether',
1022 | 'Pether',
1023 | 'Eether',
1024 | 'Zether',
1025 | 'Yether',
1026 | 'Nether',
1027 | 'Dether',
1028 | 'Vether',
1029 | 'Uether'
1030 | ];
1031 |
1032 | /// @returns an array of objects describing web3 api methods
1033 | var web3Methods = function () {
1034 | return [
1035 | { name: 'sha3', call: 'web3_sha3' }
1036 | ];
1037 | };
1038 |
1039 | /// @returns an array of objects describing web3.eth api methods
1040 | var ethMethods = function () {
1041 | var blockCall = function (args) {
1042 | return typeof args[0] === "string" ? "eth_blockByHash" : "eth_blockByNumber";
1043 | };
1044 |
1045 | var transactionCall = function (args) {
1046 | return typeof args[0] === "string" ? 'eth_transactionByHash' : 'eth_transactionByNumber';
1047 | };
1048 |
1049 | var uncleCall = function (args) {
1050 | return typeof args[0] === "string" ? 'eth_uncleByHash' : 'eth_uncleByNumber';
1051 | };
1052 |
1053 | var methods = [
1054 | { name: 'balanceAt', call: 'eth_balanceAt' },
1055 | { name: 'stateAt', call: 'eth_stateAt' },
1056 | { name: 'storageAt', call: 'eth_storageAt' },
1057 | { name: 'countAt', call: 'eth_countAt'},
1058 | { name: 'codeAt', call: 'eth_codeAt' },
1059 | { name: 'transact', call: 'eth_transact' },
1060 | { name: 'call', call: 'eth_call' },
1061 | { name: 'block', call: blockCall },
1062 | { name: 'transaction', call: transactionCall },
1063 | { name: 'uncle', call: uncleCall },
1064 | { name: 'compilers', call: 'eth_compilers' },
1065 | { name: 'flush', call: 'eth_flush' },
1066 | { name: 'lll', call: 'eth_lll' },
1067 | { name: 'solidity', call: 'eth_solidity' },
1068 | { name: 'serpent', call: 'eth_serpent' },
1069 | { name: 'logs', call: 'eth_logs' }
1070 | ];
1071 | return methods;
1072 | };
1073 |
1074 | /// @returns an array of objects describing web3.eth api properties
1075 | var ethProperties = function () {
1076 | return [
1077 | { name: 'coinbase', getter: 'eth_coinbase', setter: 'eth_setCoinbase' },
1078 | { name: 'listening', getter: 'eth_listening', setter: 'eth_setListening' },
1079 | { name: 'mining', getter: 'eth_mining', setter: 'eth_setMining' },
1080 | { name: 'gasPrice', getter: 'eth_gasPrice' },
1081 | { name: 'accounts', getter: 'eth_accounts' },
1082 | { name: 'peerCount', getter: 'eth_peerCount' },
1083 | { name: 'defaultBlock', getter: 'eth_defaultBlock', setter: 'eth_setDefaultBlock' },
1084 | { name: 'number', getter: 'eth_number'}
1085 | ];
1086 | };
1087 |
1088 | /// @returns an array of objects describing web3.db api methods
1089 | var dbMethods = function () {
1090 | return [
1091 | { name: 'put', call: 'db_put' },
1092 | { name: 'get', call: 'db_get' },
1093 | { name: 'putString', call: 'db_putString' },
1094 | { name: 'getString', call: 'db_getString' }
1095 | ];
1096 | };
1097 |
1098 | /// @returns an array of objects describing web3.shh api methods
1099 | var shhMethods = function () {
1100 | return [
1101 | { name: 'post', call: 'shh_post' },
1102 | { name: 'newIdentity', call: 'shh_newIdentity' },
1103 | { name: 'haveIdentity', call: 'shh_haveIdentity' },
1104 | { name: 'newGroup', call: 'shh_newGroup' },
1105 | { name: 'addToGroup', call: 'shh_addToGroup' }
1106 | ];
1107 | };
1108 |
1109 | /// @returns an array of objects describing web3.eth.watch api methods
1110 | var ethWatchMethods = function () {
1111 | var newFilter = function (args) {
1112 | return typeof args[0] === 'string' ? 'eth_newFilterString' : 'eth_newFilter';
1113 | };
1114 |
1115 | return [
1116 | { name: 'newFilter', call: newFilter },
1117 | { name: 'uninstallFilter', call: 'eth_uninstallFilter' },
1118 | { name: 'getMessages', call: 'eth_filterLogs' }
1119 | ];
1120 | };
1121 |
1122 | /// @returns an array of objects describing web3.shh.watch api methods
1123 | var shhWatchMethods = function () {
1124 | return [
1125 | { name: 'newFilter', call: 'shh_newFilter' },
1126 | { name: 'uninstallFilter', call: 'shh_uninstallFilter' },
1127 | { name: 'getMessages', call: 'shh_getMessages' }
1128 | ];
1129 | };
1130 |
1131 | /// creates methods in a given object based on method description on input
1132 | /// setups api calls for these methods
1133 | var setupMethods = function (obj, methods) {
1134 | methods.forEach(function (method) {
1135 | obj[method.name] = function () {
1136 | var args = Array.prototype.slice.call(arguments);
1137 | var call = typeof method.call === 'function' ? method.call(args) : method.call;
1138 | return web3.provider.send({
1139 | call: call,
1140 | args: args
1141 | });
1142 | };
1143 | });
1144 | };
1145 |
1146 | /// creates properties in a given object based on properties description on input
1147 | /// setups api calls for these properties
1148 | var setupProperties = function (obj, properties) {
1149 | properties.forEach(function (property) {
1150 | var proto = {};
1151 | proto.get = function () {
1152 | return web3.provider.send({
1153 | call: property.getter
1154 | });
1155 | };
1156 |
1157 | if (property.setter) {
1158 | proto.set = function (val) {
1159 | return web3.provider.send({
1160 | call: property.setter,
1161 | args: [val]
1162 | });
1163 | };
1164 | }
1165 | Object.defineProperty(obj, property.name, proto);
1166 | });
1167 | };
1168 |
1169 | /// setups web3 object, and it's in-browser executed methods
1170 | var web3 = {
1171 | _callbacks: {},
1172 | _events: {},
1173 | providers: {},
1174 |
1175 | toHex: function(str) {
1176 | var hex = "";
1177 | for(var i = 0; i < str.length; i++) {
1178 | var n = str.charCodeAt(i).toString(16);
1179 | hex += n.length < 2 ? '0' + n : n;
1180 | }
1181 |
1182 | return hex;
1183 | },
1184 |
1185 | /// @returns ascii string representation of hex value prefixed with 0x
1186 | toAscii: function(hex) {
1187 | // Find termination
1188 | var str = "";
1189 | var i = 0, l = hex.length;
1190 | if (hex.substring(0, 2) === '0x')
1191 | i = 2;
1192 | for(; i < l; i+=2) {
1193 | var code = parseInt(hex.substr(i, 2), 16);
1194 | if(code === 0) {
1195 | break;
1196 | }
1197 |
1198 | str += String.fromCharCode(code);
1199 | }
1200 |
1201 | return str;
1202 | },
1203 |
1204 | /// @returns hex representation (prefixed by 0x) of ascii string
1205 | fromAscii: function(str, pad) {
1206 | pad = pad === undefined ? 0 : pad;
1207 | var hex = this.toHex(str);
1208 | while(hex.length < pad*2)
1209 | hex += "00";
1210 | return "0x" + hex;
1211 | },
1212 |
1213 | /// @returns decimal representaton of hex value prefixed by 0x
1214 | toDecimal: function (val) {
1215 | // remove 0x and place 0, if it's required
1216 | val = val.length > 2 ? val.substring(2) : "0";
1217 | return (new BigNumber(val, 16).toString(10));
1218 | },
1219 |
1220 | /// @returns hex representation (prefixed by 0x) of decimal value
1221 | fromDecimal: function (val) {
1222 | return "0x" + (new BigNumber(val).toString(16));
1223 | },
1224 |
1225 | /// used to transform value/string to eth string
1226 | /// TODO: use BigNumber.js to parse int
1227 | toEth: function(str) {
1228 | var val = typeof str === "string" ? str.indexOf('0x') === 0 ? parseInt(str.substr(2), 16) : parseInt(str) : str;
1229 | var unit = 0;
1230 | var units = ETH_UNITS;
1231 | while (val > 3000 && unit < units.length - 1)
1232 | {
1233 | val /= 1000;
1234 | unit++;
1235 | }
1236 | var s = val.toString().length < val.toFixed(2).length ? val.toString() : val.toFixed(2);
1237 | var replaceFunction = function($0, $1, $2) {
1238 | return $1 + ',' + $2;
1239 | };
1240 |
1241 | while (true) {
1242 | var o = s;
1243 | s = s.replace(/(\d)(\d\d\d[\.\,])/, replaceFunction);
1244 | if (o === s)
1245 | break;
1246 | }
1247 | return s + ' ' + units[unit];
1248 | },
1249 |
1250 | /// eth object prototype
1251 | eth: {
1252 | contractFromAbi: function (abi) {
1253 | return function(addr) {
1254 | // Default to address of Config. TODO: rremove prior to genesis.
1255 | addr = addr || '0xc6d9d2cd449a754c494264e1809c50e34d64562b';
1256 | var ret = web3.eth.contract(addr, abi);
1257 | ret.address = addr;
1258 | return ret;
1259 | };
1260 | },
1261 | watch: function (params) {
1262 | return new web3.filter(params, ethWatch);
1263 | }
1264 | },
1265 |
1266 | /// db object prototype
1267 | db: {},
1268 |
1269 | /// shh object prototype
1270 | shh: {
1271 | watch: function (params) {
1272 | return new web3.filter(params, shhWatch);
1273 | }
1274 | },
1275 |
1276 | /// @returns true if provider is installed
1277 | haveProvider: function() {
1278 | return !!web3.provider.provider;
1279 | }
1280 | };
1281 |
1282 | /// setups all api methods
1283 | setupMethods(web3, web3Methods());
1284 | setupMethods(web3.eth, ethMethods());
1285 | setupProperties(web3.eth, ethProperties());
1286 | setupMethods(web3.db, dbMethods());
1287 | setupMethods(web3.shh, shhMethods());
1288 |
1289 | var ethWatch = {
1290 | changed: 'eth_changed'
1291 | };
1292 |
1293 | setupMethods(ethWatch, ethWatchMethods());
1294 |
1295 | var shhWatch = {
1296 | changed: 'shh_changed'
1297 | };
1298 |
1299 | setupMethods(shhWatch, shhWatchMethods());
1300 |
1301 | web3.setProvider = function(provider) {
1302 | //provider.onmessage = messageHandler; // there will be no async calls, to remove
1303 | web3.provider.set(provider);
1304 | };
1305 |
1306 | module.exports = web3;
1307 |
1308 |
1309 | },{}],"web3":[function(require,module,exports){
1310 | var web3 = require('./lib/web3');
1311 | var ProviderManager = require('./lib/providermanager');
1312 | web3.provider = new ProviderManager();
1313 | web3.filter = require('./lib/filter');
1314 | web3.providers.HttpSyncProvider = require('./lib/httpsync');
1315 | web3.providers.QtSyncProvider = require('./lib/qtsync');
1316 | web3.eth.contract = require('./lib/contract');
1317 | web3.abi = require('./lib/abi');
1318 |
1319 |
1320 | module.exports = web3;
1321 |
1322 | },{"./lib/abi":1,"./lib/contract":2,"./lib/filter":4,"./lib/httpsync":5,"./lib/providermanager":6,"./lib/qtsync":7,"./lib/web3":8}]},{},["web3"])
1323 |
1324 |
1325 | //# sourceMappingURL=ethereum.js.map
--------------------------------------------------------------------------------
/ethereum.js.map:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/drcode/ethereum-order-statistic-tree/0d2107ee3891052344e70dba7ef44ca2c61f9f4b/ethereum.js.map
--------------------------------------------------------------------------------
/ost_test.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/ost_test.js:
--------------------------------------------------------------------------------
1 | /*
2 | This program is free software: you can redistribute it and/or modify
3 | it under the terms of the GNU General Public License as published by
4 | the Free Software Foundation, either version 3 of the License, or
5 | (at your option) any later version.
6 |
7 | This program is distributed in the hope that it will be useful,
8 | but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | GNU General Public License for more details.
11 |
12 | You should have received a copy of the GNU General Public License
13 | along with this program. If not, see .
14 |
15 | Copyright 2015 Conrad Barski
16 |
17 | */
18 |
19 | var contract;
20 | var contract_address;
21 | var contract_abi;
22 | var contract_hex;
23 | var cycle=false;
24 |
25 | var web3 = require('web3');
26 | web3.setProvider(new web3.providers.HttpSyncProvider('http://localhost:8080'));
27 |
28 | function cleanup_hex(s){
29 | return '0x'+s.replace(/\n/g, "");
30 | }
31 |
32 | function load_contract_hex(){
33 | $.getJSON(
34 | 'OrderStatisticTree.abi',
35 | //'http://localhost:8081/OrderStatisticTree.abi',
36 | function(abi){
37 | contract_abi=abi;
38 | })
39 | }
40 |
41 | function load_contract_abi(){
42 | $.get(
43 | 'OrderStatisticTree.binary',
44 | //'http://localhost:8081/OrderStatisticTree.binary',
45 | function(hex){
46 | contract_hex=cleanup_hex(hex);
47 | })
48 | }
49 |
50 | function publish_contract(){
51 | contract_address=web3.eth.transact({data:contract_hex,gas:"50000",gasprice:"50"});
52 | $('#address').text('Contract address : '+contract_address);
53 | contract=web3.eth.contract(contract_address,contract_abi);
54 | $('#test').show();
55 | $('#generative_test').show();
56 | $('#test_table').show();
57 | $('#publish').prop('disabled',true);
58 | }
59 |
60 | function store(value,visited){
61 | if (visited[value]){
62 | alert('Cycle in tree :(');
63 | cycle=true;
64 | }
65 | visited[value]=true;
66 | var side="left";
67 | if (contract.call().node_side(value).toString()=="true")
68 | side="right"
69 | var result={
70 | value:value,
71 | dupes:parseInt(contract.call().node_dupes(value))
72 | }
73 | if (value!=0){
74 | result.side=side;
75 | result.parent=parseInt(contract.call().node_parent(value));
76 | result.height=parseInt(contract.call().node_height(value));
77 | result.count=parseInt(contract.call().node_count(value));
78 | }
79 | var left=parseInt(contract.call().node_left_child(value));
80 | var right=parseInt(contract.call().node_right_child(value));
81 | if (left!=0 && !cycle)
82 | result.left=store(left,visited);
83 | if (right!=0 && !cycle)
84 | result.right=store(right,visited);
85 | return result;
86 | }
87 |
88 | var tests=
89 | [
90 | [
91 | 'insert',
92 | [5],
93 | null
94 | ],
95 | [
96 | 'percentile',
97 | [5],
98 | 50
99 | ],
100 | [
101 | 'remove',
102 | [5],
103 | null
104 | ],
105 | [
106 | 'insert',
107 | [5],
108 | null
109 | ],
110 | [
111 | 'rank',
112 | [5],
113 | 0
114 | ],
115 | [
116 | 'insert',
117 | [0],
118 | null
119 | ],
120 | [
121 | 'rank',
122 | [5],
123 | 1
124 | ],
125 | [
126 | 'insert',
127 | [6],
128 | null
129 | ],
130 | [
131 | 'insert',
132 | [7],
133 | null
134 | ],
135 | [
136 | 'count',
137 | [],
138 | 4
139 | ],
140 | [
141 | 'percentile',
142 | [6],
143 | 62
144 | ],
145 | [
146 | 'insert',
147 | [5],
148 | null
149 | ],
150 | [
151 | 'percentile',
152 | [6],
153 | 70
154 | ],
155 | [
156 | 'insert',
157 | [8],
158 | null
159 | ],
160 | [
161 | 'select_at',
162 | [1],
163 | 5
164 | ],
165 | [
166 | 'select_at',
167 | [4],
168 | 7
169 | ],
170 | [
171 | 'median',
172 | [],
173 | 6
174 | ],
175 | [
176 | 'remove',
177 | [5],
178 | null
179 | ],
180 | [
181 | 'remove',
182 | [5],
183 | null
184 | ]
185 | ]
186 | var xtra_test=null;
187 |
188 | function rand_int(n){
189 | return Math.floor(Math.random()*n);
190 | }
191 |
192 | var test_depth=20;
193 |
194 | function generate_tests(){
195 | if (xtra_test!=null)
196 | return xtra_test;
197 | var items=[];
198 | var arr=[];
199 |
200 | var remove=function(){
201 | var pos=rand_int(items.length);
202 | arr.push(['remove',[items[pos]],null]);
203 | items.splice(pos,1);
204 | }
205 | for(var i=0;i0)
207 | remove();
208 | else{
209 | var nu=rand_int(test_depth);
210 | items.push(nu);
211 | arr.push(['insert',[nu],null]);
212 | }
213 | }
214 | while(items.length>0)
215 | remove();
216 | $('#script').text(JSON.stringify(arr));
217 | console.log(JSON.stringify(arr,undefined,2));
218 | return arr;
219 | }
220 |
221 | function bad_store(store){
222 | if(store==null)
223 | return false;
224 | var count=1+store.dupes;
225 | var height_left=0;
226 | var height_right=0;
227 | var right=store.right;
228 | var left=store.left;
229 | if (right!=null){
230 | count+=right.count;
231 | height_right=right.height;
232 | if(bad_store(right))
233 | return true;
234 | }
235 | if (left!=null){
236 | count+=left.count;
237 | height_left=left.height;
238 | if(bad_store(left))
239 | return true;
240 | }
241 | var height=Math.max(height_left,height_right)+1;
242 | if (Math.abs(height_left-height_right)>=2 || height!=store.height || count!=store.count)
243 | return true;
244 | }
245 |
246 | function test_contract(generative){
247 | var corrupt=false;
248 | var st;
249 | $('#test_table tr').remove();
250 | var cur_tests=tests;
251 | if(generative)
252 | cur_tests=generate_tests();
253 | for(var i=0;i'+test[0]+'('+test[1]+') | = | '+result+' | '+status+' | '+JSON.stringify(st,undefined,4)+' | ');
267 | if (cycle){
268 | corrupt=true;
269 | break;
270 | }
271 | if (bad_store(st.right)){
272 | corrupt=true;
273 | alert('bad store');
274 | break;
275 | }
276 |
277 | }
278 | if(!corrupt && generative){
279 | if (st.right!=null)
280 | alert('junk left over');
281 | }
282 | }
283 |
284 | $(function(){
285 | load_contract_hex();
286 | load_contract_abi();
287 | })
288 |
--------------------------------------------------------------------------------