├── .gitignore
├── LICENSE
├── README.md
├── build.gradle
├── contracts
├── RaidenMicroTransferChannels.sol
├── Token.sol
├── lib
│ └── ECVerify.sol
└── test
│ ├── CustomToken.sol
│ ├── ERC223ReceivingContract.sol
│ └── StandardToken.sol
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── rm-ethereum.conf
├── settings.gradle
└── src
├── main
└── java
│ ├── Http.java
│ ├── MicroRaiden.java
│ ├── Utility.java
│ └── Wallet.java
└── test
└── java
└── MicroRaidenTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | # Created by https://www.gitignore.io/api/gradle,eclipse
3 |
4 | ### Eclipse ###
5 |
6 | .metadata
7 | bin/
8 | tmp/
9 | *.tmp
10 | *.bak
11 | *.swp
12 | *~.nib
13 | *.pkey
14 | local.properties
15 | .settings/
16 | .loadpath
17 | .recommenders
18 |
19 | # External tool builders
20 | .externalToolBuilders/
21 |
22 | # Locally stored "Eclipse launch configurations"
23 | *.launch
24 |
25 | # PyDev specific (Python IDE for Eclipse)
26 | *.pydevproject
27 |
28 | # CDT-specific (C/C++ Development Tooling)
29 | .cproject
30 |
31 | # Java annotation processor (APT)
32 | .factorypath
33 |
34 | # PDT-specific (PHP Development Tools)
35 | .buildpath
36 |
37 | # sbteclipse plugin
38 | .target
39 |
40 | # Tern plugin
41 | .tern-project
42 |
43 | # TeXlipse plugin
44 | .texlipse
45 |
46 | # STS (Spring Tool Suite)
47 | .springBeans
48 |
49 | # Code Recommenders
50 | .recommenders/
51 |
52 | # Scala IDE specific (Scala & Java development for Eclipse)
53 | .cache-main
54 | .scala_dependencies
55 | .worksheet
56 |
57 | ### Eclipse Patch ###
58 | # Eclipse Core
59 | .project
60 |
61 | # JDT-specific (Eclipse Java Development Tools)
62 | .classpath
63 |
64 | ### Gradle ###
65 | .gradle
66 | **/build/
67 |
68 | # Ignore Gradle GUI config
69 | gradle-app.setting
70 |
71 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
72 | !gradle-wrapper.jar
73 |
74 | # Cache of project
75 | .gradletasknamecache
76 |
77 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898
78 | # gradle/wrapper/gradle-wrapper.properties
79 |
80 | # End of https://www.gitignore.io/api/gradle,eclipse
81 |
82 |
--------------------------------------------------------------------------------
/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 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## About MicroRaiden Java
2 | Eventually the goal is a full port of the [µRaiden](https://github.com/raiden-network/microraiden) project from
3 | Python to Java. However, initially - we're aiming for the bare min
4 | functionality to support micropayment channels between two peers such
5 | that we can automatically deploy channels from one entity with some
6 | initial deposit supplied by the initiator of the channel.
7 | The current version of code has been tested with [Kovan](https://gitter.im/kovan-testnet/) testnet only for now. However, other testnet should also work after proper configurations.
8 | ## Prerequisites and Notes
9 | - Parity installation. More information about parity intallation can be found https://www.parity.io/. The version of parity being used is 1.8.4-beta.
10 | - Run your parity service with the following command:
11 | ```
12 | parity --geth --chain kovan --force-ui --reseal-min-period 0 --jsonrpc-cors "*" --jsonrpc-apis web3,eth,net,parity,traces,rpc,personal
13 | ```
14 | It may take a while to get syncronized.
15 | ## Working with the existing contracts deployed on Kovan.
16 | We have deployed the [CustomToken](https://kovan.etherscan.io/address/0x0fc373426c87f555715e6fe673b07fe9e7f0e6e7) and [RaidenMicroTransferChannels](https://kovan.etherscan.io/address/0x5832edf9Da129Aa13fdA0fBff93379d3ED8a4a93) contracts. The ABI and addresses have been added in the configuration file `rm-ethereum.conf` in this project.
17 | ### Building
18 | ```
19 | ./gradlew installDist
20 | ```
21 | ### Running
22 | ```
23 | ./gradlew run
24 | ```
25 | or
26 | ```
27 | ./build/install/microraiden-java/bin/microraiden-java
28 | ```
29 | ### Use createAccount command to create an account
30 | ```
31 | ./build/install/microraiden-java/bin/microraiden-java createAccount Alice
32 | ```
33 | This version of the project now is very basic. We do not take any credentials from you when creating the account. A file Alice.pkey should be created with private key shown in plaintext.
34 | ### Use getAccountInfo command to get the information of the new account
35 | ```
36 | ./build/install/microraiden-java/bin/microraiden-java getAccountInfo Alice
37 | ```
38 | If your parity service running correctly, you should see your AccountName, AccountID, AccountNonce, and AccountBalance.
39 | ### Get some free Kovan test Ethers
40 | Copy the AccountID and paste it [here](https://gitter.im/kovan-testnet/faucet). Wait a period of time until the test ethers have been given to your account.
41 | ### Get some Custom token by using buyToken command
42 | ```
43 | ./build/install/microraiden-java/bin/microraiden-java buyToken Alice 0.1
44 | ```
45 | ### Use getTokenBalance command to see the number of tokens in the account
46 | ```
47 | ./build/install/microraiden-java/bin/microraiden-java getTokenBalance Alice
48 | ```
49 | ### Create another new account as the payment recipient.
50 | ```
51 | ./build/install/microraiden-java/bin/microraiden-java createAccount Bob
52 | ```
53 | The token balance of Bob should be zero.
54 | ### Create a payment channel from Alice to Bob by using createChannel command
55 | ```
56 | ./build/install/microraiden-java/bin/microraiden-java createChannel Alice Bob 30
57 | ```
58 | Wait until the transaction has been mined.
59 | A channel key, a block number, and a URL should be shown in the terminal. The key can be used to see the created channel by pasting it into the `channels` field in the URL page.
60 | The token balance of Alice should be updated now since she puts 30 Tokens into the payment channel as deposit. However, Bob cannot receive it since the channel has not been closed.
61 | ### Close the payment channel and check the balances of Alice and Bob
62 | ```
63 | ./build/install/microraiden-java/bin/microraiden-java closeChannelCooperatively Alice Alice Bob 5351492 12.5
64 | ```
65 | The first `Alice` is the delegator who send the transcation to Kovan testnet. The second `Alice` and `Bob` are the token sender and receiver, respectively. `5351492` is the block number where the payment channel was created. `12.5` is the real amount of token that Alice eventually pays Bob.
66 | The token balances of Alice and Bob should be updated.
67 | ### Working with RightMesh library.
68 | All of these functions should work by signing transactions and relaying
69 | them into a superpeer. For now we'll just set the superpeer ip address
70 | but when integrated into RM, this part will be replaced by relaying it
71 | through the mesh to the superpeer.
72 |
73 | ## Working with your own token and develop a new channel contract
74 | - It is very important to noted that the ethererumj currently DOES NOT support the newest version of Solidity (0.4.19). Some of the new features in Solidity with version >= 0.4.16, such as key words `view` and `pure`, are not compatible when using ethereumj to parse the application binary interface (ABI) of the smart contract. In order to install a paticular version solidity compiler (e.g. 0.4.15), please use `brew` command as shown [here](http://solidity.readthedocs.io/en/develop/installing-solidity.html#binary-packages).
75 | - The smart contracts used in this project are not exactly the same as the smart contracts in µRaiden project. The smart contracts compatible with this project have been included in this repo already.
76 | - Users can use `populus` to compile and deploy them onto the testnet. Referring the steps and configurations [here](https://github.com/raiden-network/microraiden/blob/master/contracts/README.md#usage) is helpful.
77 | - After the smart contract deployment onto Kovan testnet, open file rm-ethereum.conf and update the address values.
78 | - The updated configuration now is ready to work with this project.
79 | - In order to see payment channels opened at your deployed smart contracts on Etherscan, you need to manusally assemble all pieces of solidity files and perform the solidity contract source code verification [here](https://etherscan.io/verifyContract).
80 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * This build file was generated by the Gradle 'init' task.
3 | *
4 | * This generated file contains a sample Java project to get you started.
5 | * For more details take a look at the Java Quickstart chapter in the Gradle
6 | * user guide available at https://docs.gradle.org/4.3/userguide/tutorial_java_projects.html
7 | */
8 |
9 | // Apply the java plugin to add support for Java
10 | apply plugin: 'java'
11 |
12 | // Apply the application plugin to add support for building an application
13 | apply plugin: 'application'
14 |
15 | // In this section you declare where to find the dependencies of your project
16 | repositories {
17 | // Use jcenter for resolving your dependencies.
18 | // You can declare any Maven/Ivy/file repository here.
19 | jcenter()
20 | mavenCentral()
21 | maven {
22 | url "https://dl.bintray.com/ethereum/maven/"
23 | }
24 | }
25 |
26 | dependencies {
27 | // https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient
28 | compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.3.4'
29 |
30 |
31 | // This dependency is found on compile classpath of this component and consumers.
32 | compile 'com.google.guava:guava:23.0'
33 |
34 | // Use JUnit test framework
35 | testCompile 'junit:junit:4.12'
36 |
37 | // https://mvnrepository.com/artifact/org.ethereum/ethereumj-core
38 | implementation (group: 'org.ethereum', name: 'ethereumj-core', version: '1.4.5-RELEASE')
39 |
40 | // https://mvnrepository.com/artifact/commons-io/commons-io
41 | compile group: 'commons-io', name: 'commons-io', version: '2.5'
42 |
43 | // https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple
44 | compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1'
45 |
46 | // https://mvnrepository.com/artifact/org.kocakosm/pitaya
47 | compile group: 'org.kocakosm', name: 'pitaya', version: '0.4'
48 |
49 | // https://mvnrepository.com/artifact/org.whispersystems/signal-protocol-java
50 | compile group: 'org.whispersystems', name: 'signal-protocol-java', version: '2.4.0'
51 |
52 | // https://mvnrepository.com/artifact/com.lambdaworks/scrypt
53 | compile group: 'com.lambdaworks', name: 'scrypt', version: '1.4.0'
54 |
55 |
56 | }
57 |
58 | // Define the main class for the application
59 | mainClassName = 'MicroRaiden'
60 |
61 |
--------------------------------------------------------------------------------
/contracts/RaidenMicroTransferChannels.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.15;
2 |
3 | import './Token.sol';
4 | import './lib/ECVerify.sol';
5 |
6 | /// @title Raiden MicroTransfer Channels Contract.
7 | contract RaidenMicroTransferChannels {
8 |
9 | /*
10 | * Data structures
11 | */
12 |
13 | // Number of blocks to wait from an uncooperativeClose initiated by the sender
14 | // in order to give the receiver a chance to respond with a balance proof
15 | // in case the sender cheats. After the challenge period, the sender can settle
16 | // and delete the channel.
17 | uint32 public challenge_period;
18 |
19 | // Contract semantic version
20 | string public constant version = '0.1.0';
21 |
22 | // We temporarily limit total token deposits in a channel to 100 tokens with 18 decimals.
23 | // This was calculated just for RDN with its current (as of 30/11/2017) price and should
24 | // not be considered to be the same for other tokens.
25 | // This is just for the bug bounty release, as a safety measure.
26 | uint256 public constant channel_deposit_bugbounty_limit = 10 ** 18 * 100;
27 |
28 | Token public token;
29 |
30 | mapping (bytes32 => Channel) public channels;
31 | mapping (bytes32 => ClosingRequest) public closing_requests;
32 |
33 | // 24 bytes (deposit) + 4 bytes (block number)
34 | struct Channel {
35 | // uint192 is the maximum uint size needed for deposit based on a
36 | // 10^8 * 10^18 token totalSupply.
37 | uint192 deposit;
38 |
39 | // Block number at which the channel was opened. Used in creating
40 | // a unique identifier for the channel between a sender and receiver.
41 | // Supports creation of multiple channels between the 2 parties and prevents
42 | // replay of messages in later channels.
43 | uint32 open_block_number;
44 | }
45 |
46 | // 24 bytes (deposit) + 4 bytes (block number)
47 | struct ClosingRequest {
48 | // Number of tokens owed by the sender when closing the channel.
49 | uint192 closing_balance;
50 |
51 | // Block number at which the challenge period ends, in case it has been initiated.
52 | uint32 settle_block_number;
53 | }
54 |
55 | /*
56 | * Events
57 | */
58 |
59 | event ChannelCreated(
60 | address indexed _sender,
61 | address indexed _receiver,
62 | uint192 _deposit);
63 | event ChannelToppedUp (
64 | address indexed _sender,
65 | address indexed _receiver,
66 | uint32 indexed _open_block_number,
67 | uint192 _added_deposit);
68 | event ChannelCloseRequested(
69 | address indexed _sender,
70 | address indexed _receiver,
71 | uint32 indexed _open_block_number,
72 | uint192 _balance);
73 | event ChannelSettled(
74 | address indexed _sender,
75 | address indexed _receiver,
76 | uint32 indexed _open_block_number,
77 | uint192 _balance);
78 |
79 |
80 | /*
81 | * Constructor
82 | */
83 |
84 | /// @notice Constructor for creating the uRaiden microtransfer channels contract.
85 | /// @param _token_address The address of the Token used by the uRaiden contract.
86 | /// @param _challenge_period A fixed number of blocks representing the challenge period.
87 | /// We enforce a minimum of 500 blocks waiting period.
88 | /// after a sender requests the closing of the channel without the receiver's signature.
89 | function RaidenMicroTransferChannels(address _token_address, uint32 _challenge_period) public {
90 | require(_token_address != 0x0);
91 | require(addressHasCode(_token_address));
92 | require(_challenge_period >= 500);
93 |
94 | token = Token(_token_address);
95 |
96 | // Check if the contract is indeed a token contract
97 | require(token.totalSupply() > 0);
98 |
99 | challenge_period = _challenge_period;
100 | }
101 |
102 | /*
103 | * External functions
104 | */
105 |
106 | /// @notice Opens a new channel or tops up an existing one, compatibility with ERC 223.
107 | /// @dev Can only be called from the trusted Token contract.
108 | /// @param _sender_address The address that sends the tokens.
109 | /// @param _deposit The amount of tokens that the sender escrows.
110 | /// @param _data Receiver address in bytes.
111 | function tokenFallback(address _sender_address, uint256 _deposit, bytes _data) external {
112 | // Make sure we trust the token
113 | require(msg.sender == address(token));
114 |
115 | uint192 deposit = uint192(_deposit);
116 | require(deposit == _deposit);
117 |
118 | uint length = _data.length;
119 |
120 | // createChannel - receiver address (20 bytes)
121 | // topUp - receiver address (20 bytes) + open_block_number (4 bytes) = 24 bytes
122 | require(length == 20 || length == 24);
123 |
124 | address receiver = addressFromData(_data);
125 |
126 | if(length == 20) {
127 | createChannelPrivate(_sender_address, receiver, deposit);
128 | } else {
129 | uint32 open_block_number = blockNumberFromData(_data);
130 | updateInternalBalanceStructs(
131 | _sender_address,
132 | receiver,
133 | open_block_number,
134 | deposit
135 | );
136 | }
137 | }
138 |
139 | /// @notice Creates a new channel between `msg.sender` and `_receiver_address` and transfers
140 | /// the `_deposit` token deposit to this contract, compatibility with ERC20 tokens.
141 | /// @param _receiver_address The address that receives tokens.
142 | /// @param _deposit The amount of tokens that the sender escrows.
143 | function createChannelERC20(address _receiver_address, uint192 _deposit) external {
144 | createChannelPrivate(msg.sender, _receiver_address, _deposit);
145 |
146 | // transferFrom deposit from sender to contract
147 | // ! needs prior approval from user
148 | require(token.transferFrom(msg.sender, address(this), _deposit));
149 | }
150 |
151 | /// @notice Increase the channel deposit with `_added_deposit`.
152 | /// @param _receiver_address The address that receives tokens.
153 | /// @param _open_block_number The block number at which a channel between the
154 | /// sender and receiver was created.
155 | /// @param _added_deposit The added token deposit with which the current deposit is increased.
156 | function topUpERC20(
157 | address _receiver_address,
158 | uint32 _open_block_number,
159 | uint192 _added_deposit)
160 | external
161 | {
162 | updateInternalBalanceStructs(
163 | msg.sender,
164 | _receiver_address,
165 | _open_block_number,
166 | _added_deposit
167 | );
168 |
169 | // transferFrom deposit from msg.sender to contract
170 | // ! needs prior approval from user
171 | // Do transfer after any state change
172 | require(token.transferFrom(msg.sender, address(this), _added_deposit));
173 | }
174 |
175 | /// @notice Function called by the sender, receiver or a delegate, with all the needed
176 | /// signatures to close the channel and settle immediately.
177 | /// @param _receiver_address The address that receives tokens.
178 | /// @param _open_block_number The block number at which a channel between the
179 | /// sender and receiver was created.
180 | /// @param _balance The amount of tokens owed by the sender to the receiver.
181 | /// @param _balance_msg_sig_r The balance message signed by the sender.
182 | /// @param _balance_msg_sig_s The balance message signed by the sender.
183 | /// @param _balance_msg_sig_v The balance message signed by the sender.
184 | /// @param _closing_sig_r The receiver's signed balance message, containing the sender's address.
185 | /// @param _closing_sig_s The receiver's signed balance message, containing the sender's address.
186 | /// @param _closing_sig_v The receiver's signed balance message, containing the sender's address.
187 | function cooperativeClose(
188 | address _receiver_address,
189 | uint32 _open_block_number,
190 | uint192 _balance,
191 | bytes32 _balance_msg_sig_r,
192 | bytes32 _balance_msg_sig_s,
193 | uint8 _balance_msg_sig_v,
194 | bytes32 _closing_sig_r,
195 | bytes32 _closing_sig_s,
196 | uint8 _closing_sig_v)
197 | external
198 | {
199 | // Derive sender address from signed balance proof
200 | address sender = extractBalanceProofSignature(_receiver_address, _open_block_number, _balance, _balance_msg_sig_r,_balance_msg_sig_s,_balance_msg_sig_v);
201 |
202 | // Derive receiver address from closing signature
203 | address receiver = extractClosingSignature(sender, _open_block_number, _balance, _closing_sig_r,_closing_sig_s,_closing_sig_v);
204 | require(receiver == _receiver_address);
205 |
206 | // Both signatures have been verified and the channel can be settled.
207 | settleChannel(sender, receiver, _open_block_number, _balance);
208 | }
209 |
210 | /// @notice Sender requests the closing of the channel and starts the challenge period.
211 | /// This can only happen once.
212 | /// @param _receiver_address The address that receives tokens.
213 | /// @param _open_block_number The block number at which a channel between
214 | /// the sender and receiver was created.
215 | /// @param _balance The amount of tokens owed by the sender to the receiver.
216 | function uncooperativeClose(
217 | address _receiver_address,
218 | uint32 _open_block_number,
219 | uint192 _balance)
220 | external
221 | {
222 | bytes32 key = getKey(msg.sender, _receiver_address, _open_block_number);
223 |
224 | require(channels[key].open_block_number > 0);
225 | require(closing_requests[key].settle_block_number == 0);
226 | require(_balance <= channels[key].deposit);
227 |
228 | // Mark channel as closed
229 | closing_requests[key].settle_block_number = uint32(block.number) + challenge_period;
230 | require(closing_requests[key].settle_block_number > block.number);
231 | closing_requests[key].closing_balance = _balance;
232 | ChannelCloseRequested(msg.sender, _receiver_address, _open_block_number, _balance);
233 | }
234 |
235 |
236 | /// @notice Function called by the sender after the challenge period has ended, in order to
237 | /// settle and delete the channel, in case the receiver has not closed the channel himself.
238 | /// @param _receiver_address The address that receives tokens.
239 | /// @param _open_block_number The block number at which a channel between
240 | /// the sender and receiver was created.
241 | function settle(address _receiver_address, uint32 _open_block_number) external {
242 | bytes32 key = getKey(msg.sender, _receiver_address, _open_block_number);
243 |
244 | // Make sure an uncooperativeClose has been initiated
245 | require(closing_requests[key].settle_block_number > 0);
246 |
247 | // Make sure the challenge_period has ended
248 | require(block.number > closing_requests[key].settle_block_number);
249 |
250 | settleChannel(msg.sender, _receiver_address, _open_block_number,
251 | closing_requests[key].closing_balance
252 | );
253 | }
254 |
255 | /// @notice Function for retrieving information about a channel.
256 | /// @param _sender_address The address that sends tokens.
257 | /// @param _receiver_address The address that receives tokens.
258 | /// @param _open_block_number The block number at which a channel between the
259 | /// sender and receiver was created.
260 | /// @return Channel information (unique_identifier, deposit, settle_block_number, closing_balance).
261 | function getChannelInfo(
262 | address _sender_address,
263 | address _receiver_address,
264 | uint32 _open_block_number)
265 | external
266 | constant
267 | returns (bytes32, uint192, uint32, uint192)
268 | {
269 | bytes32 key = getKey(_sender_address, _receiver_address, _open_block_number);
270 | require(channels[key].open_block_number > 0);
271 |
272 | return (
273 | key,
274 | channels[key].deposit,
275 | closing_requests[key].settle_block_number,
276 | closing_requests[key].closing_balance
277 | );
278 | }
279 |
280 | /*
281 | * Public functions
282 | */
283 |
284 | /// @notice Returns the sender address extracted from the balance proof.
285 | /// dev Works with eth_signTypedData https://github.com/ethereum/EIPs/pull/712.
286 | /// @param _receiver_address The address that receives tokens.
287 | /// @param _open_block_number The block number at which a channel between the
288 | /// sender and receiver was created.
289 | /// @param _balance The amount of tokens owed by the sender to the receiver.
290 | /// @param _balance_msg_sig_r The balance message signed by the sender.
291 | /// @param _balance_msg_sig_s The balance message signed by the sender.
292 | /// @param _balance_msg_sig_v The balance message signed by the sender.
293 | /// @return Address of the balance proof signer.
294 | function extractBalanceProofSignature(
295 | address _receiver_address,
296 | uint32 _open_block_number,
297 | uint192 _balance,
298 | bytes32 _balance_msg_sig_r,
299 | bytes32 _balance_msg_sig_s,
300 | uint8 _balance_msg_sig_v)
301 | public
302 | constant
303 | returns (address)
304 | {
305 | // The variable names from below will be shown to the sender when signing
306 | // the balance proof, so they have to be kept in sync with the Dapp client.
307 | // The hashed strings should be kept in sync with this function's parameters
308 | // (variable names and types).
309 | // ! Note that EIP712 might change how hashing is done, triggering a
310 | // new contract deployment with updated code.
311 | bytes32 message_hash = getBalanceHash(
312 | _receiver_address,
313 | _open_block_number,
314 | _balance);
315 |
316 |
317 | // Derive address from signature
318 | address signer = ECVerify.ecverify(message_hash, _balance_msg_sig_r, _balance_msg_sig_s, _balance_msg_sig_v);
319 | return signer;
320 | }
321 |
322 |
323 | function getClosingHash(
324 | address _sender_address,
325 | uint32 _open_block_number,
326 | uint192 _balance)
327 | constant returns (bytes32 message_hash)
328 | {
329 | message_hash = keccak256(
330 | keccak256(
331 | 'string message_id',
332 | 'address sender',
333 | 'uint32 block_created',
334 | 'uint192 balance',
335 | 'address contract'
336 | ),
337 | keccak256(
338 | 'Receiver closing signature',
339 | _sender_address,
340 | _open_block_number,
341 | _balance,
342 | address(this)
343 | )
344 | );
345 | return message_hash;
346 | }
347 |
348 | function getBalanceHash(
349 | address _receiver_address,
350 | uint32 _open_block_number,
351 | uint192 _balance)
352 | constant returns (bytes32 message_hash)
353 | {
354 | message_hash = keccak256(
355 | keccak256(
356 | 'string message_id',
357 | 'address receiver',
358 | 'uint32 block_created',
359 | 'uint192 balance',
360 | 'address contract'
361 | ),
362 | keccak256(
363 | 'Sender balance proof signature',
364 | _receiver_address,
365 | _open_block_number,
366 | _balance,
367 | address(this)
368 | )
369 | );
370 | return message_hash;
371 | }
372 |
373 | /// @dev Returns the receiver address extracted from the closing signature.
374 | /// Works with eth_signTypedData https://github.com/ethereum/EIPs/pull/712.
375 | /// @param _sender_address The address that sends tokens.
376 | /// @param _open_block_number The block number at which a channel between the
377 | /// sender and receiver was created.
378 | /// @param _balance The amount of tokens owed by the sender to the receiver.
379 | /// @param _closing_sig_r The receiver's signed balance message, containing the sender's address.
380 | /// @param _closing_sig_s The receiver's signed balance message, containing the sender's address.
381 | /// @param _closing_sig_v The receiver's signed balance message, containing the sender's address.
382 | /// @return Address of the closing signature signer.
383 | function extractClosingSignature(
384 | address _sender_address,
385 | uint32 _open_block_number,
386 | uint192 _balance,
387 | bytes32 _closing_sig_r,
388 | bytes32 _closing_sig_s,
389 | uint8 _closing_sig_v)
390 | public
391 | constant
392 | returns (address)
393 | {
394 | // The variable names from below will be shown to the sender when signing
395 | // the balance proof, so they have to be kept in sync with the Dapp client.
396 | // The hashed strings should be kept in sync with this function's parameters
397 | // (variable names and types).
398 | // ! Note that EIP712 might change how hashing is done, triggering a
399 | // new contract deployment with updated code.
400 | bytes32 message_hash = getClosingHash(
401 | _sender_address,
402 | _open_block_number,
403 | _balance);
404 |
405 |
406 | // Derive address from signature
407 | address signer = ECVerify.ecverify(message_hash, _closing_sig_r, _closing_sig_s, _closing_sig_v);
408 | return signer;
409 | }
410 |
411 | /// @notice Returns the unique channel identifier used in the contract.
412 | /// @param _sender_address The address that sends tokens.
413 | /// @param _receiver_address The address that receives tokens.
414 | /// @param _open_block_number The block number at which a channel between the
415 | /// sender and receiver was created.
416 | /// @return Unique channel identifier.
417 | function getKey(
418 | address _sender_address,
419 | address _receiver_address,
420 | uint32 _open_block_number)
421 | public
422 | constant
423 | returns (bytes32 data)
424 | {
425 | return keccak256(_sender_address, _receiver_address, _open_block_number);
426 | }
427 |
428 | /*
429 | * Private functions
430 | */
431 |
432 | /// @dev Creates a new channel between a sender and a receiver.
433 | /// @param _sender_address The address that sends tokens.
434 | /// @param _receiver_address The address that receives tokens.
435 | /// @param _deposit The amount of tokens that the sender escrows.
436 | function createChannelPrivate(address _sender_address, address _receiver_address, uint192 _deposit) private {
437 | require(_deposit <= channel_deposit_bugbounty_limit);
438 |
439 | uint32 open_block_number = uint32(block.number);
440 |
441 | // Create unique identifier from sender, receiver and current block number
442 | bytes32 key = getKey(_sender_address, _receiver_address, open_block_number);
443 |
444 | require(channels[key].deposit == 0);
445 | require(channels[key].open_block_number == 0);
446 | require(closing_requests[key].settle_block_number == 0);
447 |
448 | // Store channel information
449 | channels[key] = Channel({deposit: _deposit, open_block_number: open_block_number});
450 | ChannelCreated(_sender_address, _receiver_address, _deposit);
451 | }
452 |
453 | /// @dev Updates internal balance Structures when the sender adds tokens to the channel.
454 | /// @param _sender_address The address that sends tokens.
455 | /// @param _receiver_address The address that receives tokens.
456 | /// @param _open_block_number The block number at which a channel between the
457 | /// sender and receiver was created.
458 | /// @param _added_deposit The added token deposit with which the current deposit is increased.
459 | function updateInternalBalanceStructs(
460 | address _sender_address,
461 | address _receiver_address,
462 | uint32 _open_block_number,
463 | uint192 _added_deposit)
464 | private
465 | {
466 | require(_added_deposit > 0);
467 | require(_open_block_number > 0);
468 |
469 | bytes32 key = getKey(_sender_address, _receiver_address, _open_block_number);
470 |
471 | require(channels[key].deposit > 0);
472 | require(closing_requests[key].settle_block_number == 0);
473 | require(channels[key].deposit + _added_deposit <= channel_deposit_bugbounty_limit);
474 |
475 | channels[key].deposit += _added_deposit;
476 | assert(channels[key].deposit > _added_deposit);
477 | ChannelToppedUp(_sender_address, _receiver_address, _open_block_number, _added_deposit);
478 | }
479 |
480 | /// @dev Deletes the channel and settles by transfering the balance to the receiver
481 | /// and the rest of the deposit back to the sender.
482 | /// @param _sender_address The address that sends tokens.
483 | /// @param _receiver_address The address that receives tokens.
484 | /// @param _open_block_number The block number at which a channel between the
485 | /// sender and receiver was created.
486 | /// @param _balance The amount of tokens owed by the sender to the receiver.
487 | function settleChannel(
488 | address _sender_address,
489 | address _receiver_address,
490 | uint32 _open_block_number,
491 | uint192 _balance)
492 | private
493 | {
494 | bytes32 key = getKey(_sender_address, _receiver_address, _open_block_number);
495 | Channel memory channel = channels[key];
496 |
497 | require(channel.open_block_number > 0);
498 | require(_balance <= channel.deposit);
499 |
500 | // Remove closed channel structures
501 | // channel.open_block_number will become 0
502 | // Change state before transfer call
503 | delete channels[key];
504 | delete closing_requests[key];
505 |
506 | // Send _balance to the receiver, as it is always <= deposit
507 | require(token.transfer(_receiver_address, _balance));
508 |
509 | // Send deposit - balance back to sender
510 | require(token.transfer(_sender_address, channel.deposit - _balance));
511 |
512 | ChannelSettled(_sender_address, _receiver_address, _open_block_number, _balance);
513 | }
514 |
515 | /*
516 | * Internal functions
517 | */
518 |
519 | /// @dev Internal function for getting an address from tokenFallback data bytes.
520 | /// @param b Bytes received.
521 | /// @return Address resulted.
522 | function addressFromData (bytes b) internal constant returns (address) {
523 | bytes20 addr;
524 | assembly {
525 | // Read address bytes
526 | // Offset of 32 bytes, representing b.length
527 | addr := mload(add(b, 0x20))
528 | }
529 | return address(addr);
530 | }
531 |
532 | /// @dev Internal function for getting the block number from tokenFallback data bytes.
533 | /// @param b Bytes received.
534 | /// @return Block number.
535 | function blockNumberFromData(bytes b) internal constant returns (uint32) {
536 | bytes4 block_number;
537 | assembly {
538 | // Read block number bytes
539 | // Offset of 32 bytes (b.length) + 20 bytes (address)
540 | block_number := mload(add(b, 0x34))
541 | }
542 | return uint32(block_number);
543 | }
544 |
545 | /// @dev Check if a contract exists.
546 | /// @param _contract The address of the contract to check for.
547 | /// @return True if a contract exists, false otherwise
548 | function addressHasCode(address _contract) internal constant returns (bool) {
549 | uint size;
550 | assembly {
551 | size := extcodesize(_contract)
552 | }
553 |
554 | return size > 0;
555 | }
556 | }
557 |
--------------------------------------------------------------------------------
/contracts/Token.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.15;
2 |
3 | /// @title Base Token contract - Functions to be implemented by token contracts.
4 | contract Token {
5 | /*
6 | * Implements ERC 20 standard.
7 | * https://github.com/ethereum/EIPs/blob/f90864a3d2b2b45c4decf95efd26b3f0c276051a/EIPS/eip-20-token-standard.md
8 | * https://github.com/ethereum/EIPs/issues/20
9 | *
10 | * Added support for the ERC 223 "tokenFallback" method in a "transfer" function with a payload.
11 | * https://github.com/ethereum/EIPs/issues/223
12 | */
13 |
14 | /*
15 | * This is a slight change to the ERC20 base standard.
16 | * function totalSupply() constant returns (uint256 supply);
17 | * is replaced with:
18 | * uint256 public totalSupply;
19 | * This automatically creates a getter function for the totalSupply.
20 | * This is moved to the base contract since public getter functions are not
21 | * currently recognised as an implementation of the matching abstract
22 | * function by the compiler.
23 | */
24 | uint256 public totalSupply;
25 |
26 | /*
27 | * NOTE:
28 | * The following variables were optional. Now, they are included in ERC 223 interface.
29 | * They allow one to customise the token contract & in no way influences the core functionality.
30 | */
31 | string public name; //fancy name: eg Simon Bucks
32 | uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
33 | string public symbol; //An identifier: eg SBX
34 |
35 |
36 | /// @param _owner The address from which the balance will be retrieved.
37 | /// @return The balance.
38 | function balanceOf(address _owner) public constant returns (uint256 balance);
39 |
40 | /// @notice send `_value` token to `_to` from `msg.sender`.
41 | /// @param _to The address of the recipient.
42 | /// @param _value The amount of token to be transferred.
43 | /// @param _data Data to be sent to `tokenFallback.
44 | /// @return Returns success of function call.
45 | function transfer(address _to, uint256 _value, bytes _data) public returns (bool success);
46 |
47 | /// @notice send `_value` token to `_to` from `msg.sender`.
48 | /// @param _to The address of the recipient.
49 | /// @param _value The amount of token to be transferred.
50 | /// @return Whether the transfer was successful or not.
51 | function transfer(address _to, uint256 _value) public returns (bool success);
52 |
53 | /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`.
54 | /// @param _from The address of the sender.
55 | /// @param _to The address of the recipient.
56 | /// @param _value The amount of token to be transferred.
57 | /// @return Whether the transfer was successful or not.
58 | function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
59 |
60 | /// @notice `msg.sender` approves `_spender` to spend `_value` tokens.
61 | /// @param _spender The address of the account able to transfer the tokens.
62 | /// @param _value The amount of tokens to be approved for transfer.
63 | /// @return Whether the approval was successful or not.
64 | function approve(address _spender, uint256 _value) public returns (bool success);
65 |
66 | /// @param _owner The address of the account owning tokens.
67 | /// @param _spender The address of the account able to transfer the tokens.
68 | /// @return Amount of remaining tokens allowed to spent.
69 | function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
70 |
71 | /*
72 | * Events
73 | */
74 | event Transfer(address indexed _from, address indexed _to, uint256 _value);
75 | event Approval(address indexed _owner, address indexed _spender, uint256 _value);
76 |
77 | // There is no ERC223 compatible Transfer event, with `_data` included.
78 | }
79 |
--------------------------------------------------------------------------------
/contracts/lib/ECVerify.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.15;
2 |
3 | library ECVerify {
4 |
5 | function ecverify(bytes32 hash, bytes32 r, bytes32 s, uint8 v) internal constant returns (address signature_address) {
6 |
7 | // Version of signature should be 27 or 28, but 0 and 1 are also possible
8 | if (v < 27) {
9 | v += 27;
10 | }
11 |
12 | require(v == 27 || v == 28);
13 | signature_address = ecrecover(hash, v, r, s);
14 |
15 | // ecrecover returns zero on error
16 | require(signature_address != 0x0);
17 |
18 | return signature_address;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/contracts/test/CustomToken.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.15;
2 |
3 | /*
4 | This Token Contract implements the standard token functionality (https://github.com/ethereum/EIPs/issues/20), the ERC223 functionality (https://github.com/ethereum/EIPs/issues/223) as well as the following OPTIONAL extras intended for use by humans.
5 |
6 | In other words. This is intended for deployment in something like a Token Factory or Mist wallet, and then used by humans.
7 | Imagine coins, currencies, shares, voting weight, etc.
8 | Machine-based, rapid creation of many tokens would not necessarily need these extra features or will be minted in other manners.
9 |
10 | 1) Initial Finite Supply (upon creation one specifies how much is minted).
11 | 2) In the absence of a token registry: Optional Decimal, Symbol & Name.
12 |
13 | .*/
14 |
15 | import "./StandardToken.sol";
16 |
17 | /// @title CustomToken
18 | contract CustomToken is StandardToken {
19 |
20 | /*
21 | * Token metadata
22 | */
23 | string public version = 'H0.1'; //human 0.1 standard. Just an arbitrary versioning scheme.
24 | string public name;
25 | string public symbol;
26 | uint8 public decimals;
27 | uint256 public multiplier;
28 |
29 | address public owner_address;
30 |
31 | /*
32 | * Events
33 | */
34 | event Minted(address indexed _to, uint256 indexed _num);
35 |
36 | /*
37 | * Public functions
38 | */
39 | /// @dev Contract constructor function.
40 | /// @param initial_supply Initial supply of tokens.
41 | /// @param token_name Token name for display.
42 | /// @param token_symbol Token symbol.
43 | /// @param decimal_units Number of token decimals.
44 | function CustomToken (
45 | uint256 initial_supply,
46 | string token_name,
47 | string token_symbol,
48 | uint8 decimal_units)
49 | public
50 | {
51 | // Set the name for display purposes
52 | name = token_name;
53 |
54 | // Amount of decimals for display purposes
55 | decimals = decimal_units;
56 | multiplier = 10**(uint256(decimal_units));
57 |
58 | // Set the symbol for display purposes
59 | symbol = token_symbol;
60 |
61 | // Initial supply is assigned to the owner
62 | owner_address = msg.sender;
63 | balances[owner_address] = initial_supply;
64 | totalSupply = initial_supply;
65 | }
66 |
67 | /// @notice Allows tokens to be minted and assigned to `msg.sender`
68 | /// For `msg.value >= 100 finney`, the sender receives 50 tokens
69 | function mint() public payable {
70 | require(msg.value >= 100 finney);
71 |
72 | // Assign 50 tokens to msg.sender
73 | uint256 num = 50 * multiplier;
74 | balances[msg.sender] += num;
75 | totalSupply += num;
76 |
77 | Minted(msg.sender, num);
78 |
79 | assert(balances[msg.sender] >= num);
80 | assert(totalSupply >= num);
81 | }
82 |
83 | /// @notice Transfers the collected ETH to the contract owner.
84 | function transferFunds() public {
85 | require(msg.sender == owner_address);
86 | require(this.balance > 0);
87 |
88 | owner_address.transfer(this.balance);
89 | assert(this.balance == 0);
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/contracts/test/ERC223ReceivingContract.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.15;
2 |
3 | /*
4 | * Contract that is working with ERC223 tokens
5 | * https://github.com/ethereum/EIPs/issues/223
6 | */
7 |
8 | /// @title ERC223ReceivingContract - contract implementation for compatibility with ERC223 tokens.
9 | contract ERC223ReceivingContract {
10 |
11 | /// @dev Function that is called when a user or another contract wants to transfer funds.
12 | /// @param _from Transaction initiator, analogue of msg.sender
13 | /// @param _value Number of tokens to transfer.
14 | /// @param _data Data containig a function signature and/or parameters
15 | function tokenFallback(address _from, uint256 _value, bytes _data) public;
16 | }
17 |
--------------------------------------------------------------------------------
/contracts/test/StandardToken.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.15;
2 |
3 | import "../Token.sol";
4 | import "./ERC223ReceivingContract.sol";
5 |
6 | /// @title Standard token contract - Standard token implementation.
7 | contract StandardToken is Token {
8 |
9 | /*
10 | * Data structures
11 | */
12 | mapping (address => uint256) balances;
13 | mapping (address => mapping (address => uint256)) allowed;
14 |
15 | /*
16 | * Public functions
17 | */
18 | /// @notice Send `_value` tokens to `_to` from `msg.sender`.
19 | /// @dev Transfers sender's tokens to a given address. Returns success.
20 | /// @param _to Address of token receiver.
21 | /// @param _value Number of tokens to transfer.
22 | /// @return Returns success of function call.
23 | function transfer(address _to, uint256 _value) public returns (bool) {
24 | require(_to != 0x0);
25 | require(_to != address(this));
26 | require(balances[msg.sender] >= _value);
27 | require(balances[_to] + _value >= balances[_to]);
28 |
29 | balances[msg.sender] -= _value;
30 | balances[_to] += _value;
31 |
32 | Transfer(msg.sender, _to, _value);
33 |
34 | return true;
35 | }
36 |
37 | /// @notice Send `_value` tokens to `_to` from `msg.sender` and trigger
38 | /// tokenFallback if sender is a contract.
39 | /// @dev Function that is called when a user or another contract wants to transfer funds.
40 | /// @param _to Address of token receiver.
41 | /// @param _value Number of tokens to transfer.
42 | /// @param _data Data to be sent to tokenFallback
43 | /// @return Returns success of function call.
44 | function transfer(
45 | address _to,
46 | uint256 _value,
47 | bytes _data)
48 | public
49 | returns (bool)
50 | {
51 | require(transfer(_to, _value));
52 |
53 | uint codeLength;
54 |
55 | assembly {
56 | // Retrieve the size of the code on target address, this needs assembly.
57 | codeLength := extcodesize(_to)
58 | }
59 |
60 | if (codeLength > 0) {
61 | ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
62 | receiver.tokenFallback(msg.sender, _value, _data);
63 | }
64 |
65 | return true;
66 | }
67 |
68 | /// @notice Transfer `_value` tokens from `_from` to `_to` if `msg.sender` is allowed.
69 | /// @dev Allows for an approved third party to transfer tokens from one
70 | /// address to another. Returns success.
71 | /// @param _from Address from where tokens are withdrawn.
72 | /// @param _to Address to where tokens are sent.
73 | /// @param _value Number of tokens to transfer.
74 | /// @return Returns success of function call.
75 | function transferFrom(address _from, address _to, uint256 _value)
76 | public
77 | returns (bool)
78 | {
79 | require(_from != 0x0);
80 | require(_to != 0x0);
81 | require(_to != address(this));
82 | require(balances[_from] >= _value);
83 | require(allowed[_from][msg.sender] >= _value);
84 | require(balances[_to] + _value >= balances[_to]);
85 |
86 | balances[_to] += _value;
87 | balances[_from] -= _value;
88 | allowed[_from][msg.sender] -= _value;
89 |
90 | Transfer(_from, _to, _value);
91 |
92 | return true;
93 | }
94 |
95 | /// @notice Allows `_spender` to transfer `_value` tokens from `msg.sender` to any address.
96 | /// @dev Sets approved amount of tokens for spender. Returns success.
97 | /// @param _spender Address of allowed account.
98 | /// @param _value Number of approved tokens.
99 | /// @return Returns success of function call.
100 | function approve(address _spender, uint256 _value) public returns (bool) {
101 | require(_spender != 0x0);
102 |
103 | // To change the approve amount you first have to reduce the addresses`
104 | // allowance to zero by calling `approve(_spender, 0)` if it is not
105 | // already 0 to mitigate the race condition described here:
106 | // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
107 | require(_value == 0 || allowed[msg.sender][_spender] == 0);
108 |
109 | allowed[msg.sender][_spender] = _value;
110 | Approval(msg.sender, _spender, _value);
111 | return true;
112 | }
113 |
114 | /*
115 | * Read functions
116 | */
117 | /// @dev Returns number of allowed tokens that a spender can transfer on
118 | /// behalf of a token owner.
119 | /// @param _owner Address of token owner.
120 | /// @param _spender Address of token spender.
121 | /// @return Returns remaining allowance for spender.
122 | function allowance(address _owner, address _spender)
123 | constant
124 | public
125 | returns (uint256)
126 | {
127 | return allowed[_owner][_spender];
128 | }
129 |
130 | /// @dev Returns number of tokens owned by the given address.
131 | /// @param _owner Address of token owner.
132 | /// @return Returns balance of owner.
133 | function balanceOf(address _owner) constant public returns (uint256) {
134 | return balances[_owner];
135 | }
136 | }
137 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/RightMesh/microraiden-java/0fba1bf91e0d0b5b61d02997591df1c15a0f1ffc/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | zipStoreBase=GRADLE_USER_HOME
4 | zipStorePath=wrapper/dists
5 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.3-bin.zip
6 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/rm-ethereum.conf:
--------------------------------------------------------------------------------
1 | {
2 | "gasPrice":"1000000000",
3 | "debugInfo":"false",
4 | "rpcAddress":"http://localhost:8545",
5 | "channelAddr":"0x5832edf9Da129Aa13fdA0fBff93379d3ED8a4a93",
6 | "tokenAddr":"0x0fC373426c87F555715E6fE673B07Fe9E7f0E6e7",
7 | "tokenABI":"[{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"mint\",\"outputs\":[],\"payable\":true,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"multiplier\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"transferFunds\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"version\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"owner_address\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"},{\"name\":\"_data\",\"type\":\"bytes\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"initial_supply\",\"type\":\"uint256\"},{\"name\":\"token_name\",\"type\":\"string\"},{\"name\":\"token_symbol\",\"type\":\"string\"},{\"name\":\"decimal_units\",\"type\":\"uint8\"}],\"payable\":false,\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_num\",\"type\":\"uint256\"}],\"name\":\"Minted\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_spender\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"}]",
8 | "channelABI":"[{\"constant\":true,\"inputs\":[],\"name\":\"challenge_period\",\"outputs\":[{\"name\":\"\",\"type\":\"uint32\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_sender_address\",\"type\":\"address\"},{\"name\":\"_receiver_address\",\"type\":\"address\"},{\"name\":\"_open_block_number\",\"type\":\"uint32\"}],\"name\":\"getChannelInfo\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes32\"},{\"name\":\"\",\"type\":\"uint192\"},{\"name\":\"\",\"type\":\"uint32\"},{\"name\":\"\",\"type\":\"uint192\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_receiver_address\",\"type\":\"address\"},{\"name\":\"_open_block_number\",\"type\":\"uint32\"},{\"name\":\"_balance\",\"type\":\"uint192\"}],\"name\":\"uncooperativeClose\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"version\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_receiver_address\",\"type\":\"address\"},{\"name\":\"_deposit\",\"type\":\"uint192\"}],\"name\":\"createChannelERC20\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_receiver_address\",\"type\":\"address\"},{\"name\":\"_open_block_number\",\"type\":\"uint32\"}],\"name\":\"settle\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_sender_address\",\"type\":\"address\"},{\"name\":\"_open_block_number\",\"type\":\"uint32\"},{\"name\":\"_balance\",\"type\":\"uint192\"}],\"name\":\"getClosingHash\",\"outputs\":[{\"name\":\"message_hash\",\"type\":\"bytes32\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"channel_deposit_bugbounty_limit\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_receiver_address\",\"type\":\"address\"},{\"name\":\"_open_block_number\",\"type\":\"uint32\"},{\"name\":\"_balance\",\"type\":\"uint192\"},{\"name\":\"_balance_msg_sig_r\",\"type\":\"bytes32\"},{\"name\":\"_balance_msg_sig_s\",\"type\":\"bytes32\"},{\"name\":\"_balance_msg_sig_v\",\"type\":\"uint8\"}],\"name\":\"extractBalanceProofSignature\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"closing_requests\",\"outputs\":[{\"name\":\"closing_balance\",\"type\":\"uint192\"},{\"name\":\"settle_block_number\",\"type\":\"uint32\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"channels\",\"outputs\":[{\"name\":\"deposit\",\"type\":\"uint192\"},{\"name\":\"open_block_number\",\"type\":\"uint32\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_sender_address\",\"type\":\"address\"},{\"name\":\"_receiver_address\",\"type\":\"address\"},{\"name\":\"_open_block_number\",\"type\":\"uint32\"}],\"name\":\"getKey\",\"outputs\":[{\"name\":\"data\",\"type\":\"bytes32\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_sender_address\",\"type\":\"address\"},{\"name\":\"_open_block_number\",\"type\":\"uint32\"},{\"name\":\"_balance\",\"type\":\"uint192\"},{\"name\":\"_closing_sig_r\",\"type\":\"bytes32\"},{\"name\":\"_closing_sig_s\",\"type\":\"bytes32\"},{\"name\":\"_closing_sig_v\",\"type\":\"uint8\"}],\"name\":\"extractClosingSignature\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_sender_address\",\"type\":\"address\"},{\"name\":\"_deposit\",\"type\":\"uint256\"},{\"name\":\"_data\",\"type\":\"bytes\"}],\"name\":\"tokenFallback\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_receiver_address\",\"type\":\"address\"},{\"name\":\"_open_block_number\",\"type\":\"uint32\"},{\"name\":\"_added_deposit\",\"type\":\"uint192\"}],\"name\":\"topUpERC20\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_receiver_address\",\"type\":\"address\"},{\"name\":\"_open_block_number\",\"type\":\"uint32\"},{\"name\":\"_balance\",\"type\":\"uint192\"}],\"name\":\"getBalanceHash\",\"outputs\":[{\"name\":\"message_hash\",\"type\":\"bytes32\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_receiver_address\",\"type\":\"address\"},{\"name\":\"_open_block_number\",\"type\":\"uint32\"},{\"name\":\"_balance\",\"type\":\"uint192\"},{\"name\":\"_balance_msg_sig_r\",\"type\":\"bytes32\"},{\"name\":\"_balance_msg_sig_s\",\"type\":\"bytes32\"},{\"name\":\"_balance_msg_sig_v\",\"type\":\"uint8\"},{\"name\":\"_closing_sig_r\",\"type\":\"bytes32\"},{\"name\":\"_closing_sig_s\",\"type\":\"bytes32\"},{\"name\":\"_closing_sig_v\",\"type\":\"uint8\"}],\"name\":\"cooperativeClose\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"token\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"_token_address\",\"type\":\"address\"},{\"name\":\"_challenge_period\",\"type\":\"uint32\"}],\"payable\":false,\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_sender\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_receiver\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_deposit\",\"type\":\"uint192\"}],\"name\":\"ChannelCreated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_sender\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_receiver\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_open_block_number\",\"type\":\"uint32\"},{\"indexed\":false,\"name\":\"_added_deposit\",\"type\":\"uint192\"}],\"name\":\"ChannelToppedUp\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_sender\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_receiver\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_open_block_number\",\"type\":\"uint32\"},{\"indexed\":false,\"name\":\"_balance\",\"type\":\"uint192\"}],\"name\":\"ChannelCloseRequested\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_sender\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_receiver\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_open_block_number\",\"type\":\"uint32\"},{\"indexed\":false,\"name\":\"_balance\",\"type\":\"uint192\"}],\"name\":\"ChannelSettled\",\"type\":\"event\"}]",
9 | "appendingZerosForETH":"1000000000000000000",
10 | "appendingZerosForTKN":"1000000000000000000",
11 | "maxDepositBits":"192"
12 | }
13 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * This settings file was generated by the Gradle 'init' task.
3 | *
4 | * The settings file is used to specify which projects to include in your build.
5 | * In a single project build this file can be empty or even removed.
6 | *
7 | * Detailed information about configuring a multi-project build in Gradle can be found
8 | * in the user guide at https://docs.gradle.org/4.3/userguide/multi_project_builds.html
9 | */
10 |
11 | /*
12 | // To declare projects as part of a multi-project build use the 'include' method
13 | include 'shared'
14 | include 'api'
15 | include 'services:webservice'
16 | */
17 |
18 | rootProject.name = 'microraiden-java'
19 |
--------------------------------------------------------------------------------
/src/main/java/Http.java:
--------------------------------------------------------------------------------
1 | import java.io.IOException;
2 | import java.io.UnsupportedEncodingException;
3 |
4 | import org.apache.http.client.ClientProtocolException;
5 | import org.apache.http.client.methods.CloseableHttpResponse;
6 | import org.apache.http.client.methods.HttpPost;
7 | import org.apache.http.entity.StringEntity;
8 | import org.apache.http.impl.client.BasicResponseHandler;
9 | import org.apache.http.impl.client.CloseableHttpClient;
10 | import org.apache.http.impl.client.HttpClientBuilder;
11 | import org.json.simple.JSONObject;
12 | import org.json.simple.parser.JSONParser;
13 | import org.json.simple.parser.ParseException;
14 |
15 | public class Http {
16 |
17 | private String rpcAddress;
18 | private boolean debugInfo;
19 | /**
20 | *
21 | * @param _rpcAddress the rpc URL
22 | * @param _debug debug info switch
23 | */
24 | public Http(String _rpcAddress, boolean _debug) {
25 | rpcAddress=_rpcAddress;
26 | debugInfo=_debug;
27 |
28 | }
29 |
30 | /**
31 | * This function is to send RPC request to the running peer.
32 | * @param requestString the HTTP request string
33 | * @return the result of the HTTP request
34 | * @throws IOException
35 | */
36 | public Object getHttpResponse(String requestString) throws IOException{
37 | JSONParser parser = new JSONParser();
38 | JSONObject jobj=new JSONObject();
39 | Object executionResult=null;
40 | String temp="";
41 | try {
42 | CloseableHttpClient httpClient = HttpClientBuilder.create().build();
43 |
44 | HttpPost request = new HttpPost(rpcAddress);
45 | request.addHeader("content-type", "application/json");
46 | request.setEntity(new StringEntity(requestString));
47 |
48 | CloseableHttpResponse response = httpClient.execute(request);
49 | response.close();
50 | httpClient.close();
51 |
52 | temp=new BasicResponseHandler().handleResponse(response);
53 | jobj=(JSONObject)parser.parse(temp);
54 | if(debugInfo) {
55 | System.out.println("result = "+jobj.toJSONString());
56 | }
57 | for (Object key : jobj.keySet()) {
58 | if (((String)key).equalsIgnoreCase("result")) {
59 | executionResult=jobj.get(key);
60 | }
61 | }
62 | }catch (UnsupportedEncodingException e) {
63 | System.out.println("UnsupportedEncodingException: " + e);
64 | }catch (ClientProtocolException e) {
65 | System.out.println("ClientProtocolException: "+ e);
66 | }catch (IOException e) {
67 | System.out.println("IOException: " + e);
68 | }catch(ParseException e) {
69 | System.out.println("ParseException: " + e);
70 | }catch (NumberFormatException e){
71 | System.out.println("NumberFormatException=" + e);
72 | }
73 | if("".equals(executionResult)) {
74 | throw new IOException(temp);
75 | }
76 | return executionResult;
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/src/main/java/MicroRaiden.java:
--------------------------------------------------------------------------------
1 | import java.lang.reflect.*;
2 | import java.math.BigInteger;
3 | import java.util.Arrays;
4 | import java.io.File;
5 | import java.io.FileOutputStream;
6 | import java.io.FileReader;
7 | import java.io.FileInputStream;
8 | import java.io.FileNotFoundException;
9 | import java.io.OutputStream;
10 | import java.io.UnsupportedEncodingException;
11 | import java.io.InputStream;
12 | import java.io.IOException;
13 |
14 | import org.apache.commons.codec.DecoderException;
15 | import org.apache.commons.codec.binary.Hex;
16 | import org.apache.commons.io.IOUtils;
17 | import org.apache.http.client.ClientProtocolException;
18 | import org.apache.http.client.methods.CloseableHttpResponse;
19 | import org.apache.http.client.methods.HttpPost;
20 | import org.apache.http.entity.StringEntity;
21 | import org.apache.http.impl.client.BasicResponseHandler;
22 | import org.apache.http.impl.client.CloseableHttpClient;
23 | import org.apache.http.impl.client.HttpClientBuilder;
24 | import org.ethereum.core.CallTransaction;
25 | import org.ethereum.core.Transaction;
26 | import org.ethereum.core.CallTransaction.Contract;
27 | import org.ethereum.crypto.ECKey;
28 | import org.ethereum.util.ByteUtil;
29 | import org.json.simple.JSONObject;
30 | import org.json.simple.parser.JSONParser;
31 | import org.json.simple.parser.ParseException;
32 | import org.kocakosm.pitaya.security.Digest;
33 | import org.kocakosm.pitaya.security.Digests;
34 |
35 | /*
36 | * CLI for the MicroRaiden client
37 | */
38 | public class MicroRaiden {
39 | private static final int LENGTH_OF_ID_IN_BYTES=20;
40 | private static final int INTERVAL_CHECK_TRANS_DONE=100;
41 |
42 | private static String rpcAddress=null;
43 | private static String channelAddr=null;
44 | private static String tokenAddr=null;
45 | private static String channelABI=null;
46 | private static String tokenABI=null;
47 |
48 | private static CallTransaction.Contract channelContract = null;
49 | private static CallTransaction.Contract tokenContract = null;
50 | private static String appendingZerosForETH=null;
51 | private static String appendingZerosForTKN=null;
52 | private static BigInteger MAX_DEPOSIT=null;
53 | private static BigInteger gasPrice=null;
54 | private static boolean debugInfo=false;
55 |
56 |
57 | private static Http httpAgent=null;
58 |
59 | public MicroRaiden() {
60 | //should probably create an eth account with priv / pub keys
61 | //for doing the signing in the constructor
62 |
63 | //another option is we load the account based on what is
64 | //already saved in the folder
65 |
66 | //we need to think about what we should do if the sender / recv
67 | //are located in the same folder, or different folders and how
68 | //to store the files
69 | }
70 |
71 | /**
72 | * Create a new Ethereum account to be used for testing microraiden
73 | * channels. Stores the account in the same folder where the
74 | * program is run. Note - there is no encryption on this private key
75 | * so it should be used for anything real!!
76 | * @param accountFile - the name of the output file for the account
77 | */
78 | public void createAccount(String accountFile) {
79 | ECKey keyPair = new ECKey();
80 | String address = new String(Hex.encodeHex(keyPair.getAddress()));
81 | System.out.println("Generated new account: 0x" + address);
82 | byte[] priv = keyPair.getPrivKeyBytes();
83 |
84 | try {
85 | OutputStream os = new FileOutputStream(accountFile + ".pkey");
86 | JSONObject obj=new JSONObject();
87 | obj.put("privkey", new String(Hex.encodeHex(priv)));
88 | obj.put("address", address);
89 | os.write(obj.toJSONString().getBytes());
90 | os.close();
91 | } catch (IOException e) {
92 | System.out.println("Couldn't write to file: " + accountFile + " " + e.toString());
93 | }
94 | }
95 |
96 | /**
97 | * This function is another way to create the account file for testing purpose.
98 | * After the user creates an account with, for example, MetaMask, the privateKey
99 | * can be found and used here to create the account file to perform tests on test nets.
100 | * @param accountFile the name of the account to be created.
101 | * @param privateKeyHex the privateKey given in 64 Hex digits. "0x" prefix is optional.
102 | */
103 | public void createAccountByPrivateKey(String accountFile, String privateKeyHex) {
104 | privateKeyHex=privateKeyHex.startsWith("0x")?privateKeyHex.substring(2):privateKeyHex;
105 | if(privateKeyHex.length()!=64) {
106 | System.out.println("The private key should be given in 64 HEX numbers.");
107 | return;
108 | }
109 | ECKey keyPair = new ECKey();
110 | try{
111 | keyPair=ECKey.fromPrivate(Hex.decodeHex(privateKeyHex.toCharArray()));
112 | }catch(DecoderException e) {
113 | System.out.println("Couldn't create ECKey with privateKeyHex = " + privateKeyHex);
114 | }
115 | String address = new String(Hex.encodeHex(keyPair.getAddress()));
116 | System.out.println("Generated new account: 0x" + address);
117 | byte[] priv = keyPair.getPrivKeyBytes();
118 | try {
119 | OutputStream os = new FileOutputStream(accountFile + ".pkey");
120 | JSONObject obj=new JSONObject();
121 | obj.put("privkey", new String(Hex.encodeHex(priv)));
122 | obj.put("address", address);
123 | os.write(obj.toJSONString().getBytes());
124 | os.close();
125 | } catch (IOException e) {
126 | System.out.println("Couldn't write to file: " + accountFile + " " + e.toString());
127 | }
128 | }
129 |
130 | /**
131 | * Reads all of the account files in the directory and lists which
132 | * are usable for testing channels with. Looks for files with the
133 | * .pkey extension.
134 | */
135 | public void listAccounts() {
136 | JSONParser parser = new JSONParser();
137 | JSONObject jobj=new JSONObject();
138 | File dir = new File(".");
139 | File[] filesList = dir.listFiles();
140 | for (File file : filesList) {
141 | if (file.isFile()) {
142 | if(file.getName().contains(".pkey")) {
143 | //System.out.println(file.getName());
144 | try {
145 | jobj = (JSONObject)parser.parse(new FileReader(file.getName()));
146 | System.out.println("0x" + ((String)jobj.get("address")));
147 | } catch(Exception ex) {
148 | System.out.println("Couldn't read from file: " + file.getName() + " " + ex.toString());
149 | }
150 | }
151 | }
152 | }
153 | }
154 |
155 | /**
156 | * This function should be used by sender to create the balance proof hash by using recevier's address,
157 | * the block index where the channel has been created,
158 | * the balance that the sender would like to pay to the receiver, and the channel address
159 | *
160 | * @param receiverAddress account ID of receiver in Hex String with 40 Hex digits, 0x is optional.
161 | * @param open_block_number the decimal literal of the open block index.
162 | * @param balance the double literal of real amount of token paying to receiver
163 | * @param channelAddress the channel address in Hex String with 40 Hex digits, 0x is optional.
164 | * @return the hash result.
165 | */
166 | private static byte[] getBalanceMsgHash(String receiverAddress,String open_block_number,String balance, String channelAddress) {
167 | byte[] receiverAddressBytes=new byte[0];
168 | byte[] channelAddressBytes=new byte[0];
169 | byte[] openBlockNumberBytes=new byte[0];
170 | byte[] balanceInChannelBytes=new byte[0];
171 |
172 | receiverAddress=receiverAddress.startsWith("0x")?receiverAddress.substring(2):receiverAddress;
173 | channelAddress=channelAddress.startsWith("0x")?channelAddress.substring(2):channelAddress;
174 | try {
175 | receiverAddressBytes=Hex.decodeHex(receiverAddress.toCharArray());
176 | }catch(DecoderException e) {
177 | System.out.println("The provided receiver's address is not valid.");
178 | return null;
179 | }
180 | if(receiverAddressBytes.length!=LENGTH_OF_ID_IN_BYTES) {
181 | System.out.println("The provided receiver's address is not valid.");
182 | return null;
183 | }
184 | try {
185 | channelAddressBytes=Hex.decodeHex(channelAddress.toCharArray());
186 | }catch(DecoderException e) {
187 | System.out.println("The provided channel's address is not valid.");
188 | return null;
189 | }
190 | if(channelAddressBytes.length!=LENGTH_OF_ID_IN_BYTES) {
191 | System.out.println("The provided channel's address is not valid.");
192 | return null;
193 | }
194 | try {
195 | Integer.parseInt(open_block_number);
196 | }catch(NumberFormatException e){
197 | System.out.println("The provided open block n is not valid.");
198 | return null;
199 | }
200 |
201 | BigInteger tempBalance=null;
202 | try {
203 | tempBalance=Utility.decimalToBigInteger(balance, appendingZerosForTKN);
204 | }catch(NumberFormatException e) {
205 | System.out.println("The provided balance is not valid.");
206 | return null;
207 | }
208 |
209 | try{
210 | openBlockNumberBytes=Hex.decodeHex(Utility.prependingZeros(Integer.toHexString(Integer.parseInt(open_block_number)),8).toCharArray());
211 | balanceInChannelBytes=Hex.decodeHex(Utility.prependingZeros(tempBalance.toString(16),48).toCharArray());
212 | }catch(DecoderException e) {
213 |
214 | }
215 | byte[] dataTypeName="string message_idaddress receiveruint32 block_createduint192 balanceaddress contract".getBytes();
216 | byte[] dataValue=Utility.concatenateByteArrays("Sender balance proof signature".getBytes(),receiverAddressBytes,openBlockNumberBytes,balanceInChannelBytes,channelAddressBytes);
217 | byte[] result = Utility.getSHA3HashHex(Utility.concatenateByteArrays(Utility.getSHA3HashHex(dataTypeName),Utility.getSHA3HashHex(dataValue)));
218 | if(debugInfo) {
219 | System.out.println("The value to be hashed in getBalanceMessageHash is "+new String(Hex.encodeHexString(Utility.concatenateByteArrays(Utility.getSHA3HashHex(dataTypeName),Utility.getSHA3HashHex(dataValue)))));
220 | System.out.println("The result of getBalanceMessageHash is "+new String(Hex.encodeHexString(result)));
221 | }
222 | return result;
223 | }
224 |
225 | /**
226 | * This function should be used by receiver to create the closing hash by using sender's address,
227 | * the block index where the channel has been created,
228 | * the balance that the sender would like to pay to the receiver, and the channel address
229 | *
230 | * @param senderAddress account ID of sender in Hex String with 40 Hex digits, 0x is optional.
231 | * @param open_block_number the decimal literal of the open block index.
232 | * @param balance the double literal of real amount of token paying to receiver
233 | * @param channelAddress the channel address in Hex String with 40 Hex digits, 0x is optional.
234 | * @return the hash result.
235 | */
236 | private static byte[] getClosingMsgHash(String senderAddress,String open_block_number,String balance, String channelAddress) {
237 | byte[] receiverAddressBytes=new byte[0];
238 | byte[] channelAddressBytes=new byte[0];
239 | byte[] openBlockNumberBytes=new byte[0];
240 | byte[] balanceInChannelBytes=new byte[0];
241 |
242 | senderAddress=senderAddress.startsWith("0x")?senderAddress.substring(2):senderAddress;
243 | channelAddress=channelAddress.startsWith("0x")?channelAddress.substring(2):channelAddress;
244 | try {
245 | receiverAddressBytes=Hex.decodeHex(senderAddress.toCharArray());
246 | }catch(DecoderException e) {
247 | System.out.println("The provided receiver's address is not valid.");
248 | return null;
249 | }
250 | if(receiverAddressBytes.length!=LENGTH_OF_ID_IN_BYTES) {
251 | System.out.println("The provided receiver's address is not valid.");
252 | return null;
253 | }
254 | try {
255 | channelAddressBytes=Hex.decodeHex(channelAddress.toCharArray());
256 | }catch(DecoderException e) {
257 | System.out.println("The provided channel's address is not valid.");
258 | return null;
259 | }
260 | if(channelAddressBytes.length!=LENGTH_OF_ID_IN_BYTES) {
261 | System.out.println("The provided channel's address is not valid.");
262 | return null;
263 | }
264 | try {
265 | Integer.parseInt(open_block_number);
266 | }catch(NumberFormatException e){
267 | System.out.println("The provided open block n is not valid.");
268 | return null;
269 | }
270 |
271 | BigInteger tempBalance=null;
272 | try {
273 | tempBalance=Utility.decimalToBigInteger(balance, appendingZerosForTKN);
274 | }catch(NumberFormatException e) {
275 | System.out.println("The provided balance is not valid.");
276 | return null;
277 | }
278 |
279 |
280 | try{
281 | openBlockNumberBytes=Hex.decodeHex(Utility.prependingZeros(Integer.toHexString(Integer.parseInt(open_block_number)),8).toCharArray());
282 | balanceInChannelBytes=Hex.decodeHex(Utility.prependingZeros(tempBalance.toString(16),48).toCharArray());
283 | }catch(DecoderException e) {
284 |
285 | }
286 | byte[] dataTypeName = "string message_idaddress senderuint32 block_createduint192 balanceaddress contract".getBytes();
287 | byte[] dataValue= Utility.concatenateByteArrays("Receiver closing signature".getBytes(),receiverAddressBytes,openBlockNumberBytes,balanceInChannelBytes,channelAddressBytes);
288 | byte[] result = Utility.getSHA3HashHex(Utility.concatenateByteArrays(Utility.getSHA3HashHex(dataTypeName),Utility.getSHA3HashHex(dataValue)));
289 | if(debugInfo) {
290 | System.out.println("The value to be hashed in getClosingMsgHash is "+new String(Hex.encodeHexString(Utility.concatenateByteArrays(Utility.getSHA3HashHex(dataTypeName),Utility.getSHA3HashHex(dataValue)))));
291 | System.out.println("The result of getClosingMsgHash is "+new String(Hex.encodeHexString(result)));
292 | }
293 | return result;
294 | }
295 |
296 | /**
297 | * This function should be used by receiver to create channel closing signature with
298 | * a. sender's address,
299 | * b. the block index where the channel has been created,
300 | * c. the balance that the receiver would like to receive from sender, and
301 | * d. the channel address
302 | *
303 | * @param senderAddr account ID of sender in Hex String with 40 Hex digits, 0x is optional.
304 | * @param channelAddr the channel address in Hex String with 40 Hex digits, 0x is optional.
305 | * @param open_block_number the decimal literal of the block index where the channel was open at.
306 | * @param balance the double literal of real amount of token paying to receiver
307 | * @param receiverName the receiver's name used to create a wallet to sign the signature.
308 | * @return the channel closing signature.
309 | */
310 | private static byte[] getClosingMsgHashSig(String senderAddr,String channelAddr, String openBlockNum, String balance, String receiverName) {
311 | Wallet receiverWallet=null;
312 | try {
313 | receiverWallet=new Wallet(receiverName);
314 | receiverWallet.update(httpAgent);
315 | }catch(Exception e) {
316 | return null;
317 | }
318 | byte [] closingMsgHash=getClosingMsgHash(senderAddr,openBlockNum,balance,channelAddr);
319 | if(closingMsgHash==null) {
320 | System.out.println("Argument Error.");
321 | return null;
322 | }
323 | byte [] closingMsgHashHex=null;
324 | try {
325 | closingMsgHashHex=Hex.decodeHex(new String(Hex.encodeHex(closingMsgHash)).toCharArray());
326 | }catch (DecoderException e) {
327 | System.out.println("Couldn't convert msgHashHex = 0x" + Hex.encodeHexString(closingMsgHash) + " to byte array.");
328 | return null;
329 | }
330 | return receiverWallet.signMessage(closingMsgHashHex);
331 |
332 | }
333 |
334 | /**
335 | * This function should be used by sender to create balance proof signature with receiver's address,
336 | * the block index where the channel has been created,
337 | * the balance that the sender would like to pay to the receiver, and the channel address
338 | *
339 | * @param receiverAddr account ID of receiver in Hex String with 40 Hex digits, 0x is optional.
340 | * @param channelAddr the channel address in Hex String with 40 Hex digits, 0x is optional.
341 | * @param open_block_number the decimal literal of the open block index.
342 | * @param balance the double literal of real amount of token paying to receiver
343 | * @param senderName the sender's name used to create a wallet to sign the signature.
344 | * @return the balance proof signature.
345 | */
346 | private static byte[] getBalanceMsgHashSig(String receiverAddr,String channelAddr, String openBlockNum, String balance, String senderName) {
347 | Wallet senderWallet=null;
348 | try {
349 | senderWallet=new Wallet(senderName);
350 | senderWallet.update(httpAgent);
351 | }catch(Exception e) {
352 | return null;
353 | }
354 |
355 | byte [] balanceMsgHash=getBalanceMsgHash(receiverAddr,openBlockNum,balance,channelAddr);
356 | if(balanceMsgHash==null) {
357 | System.out.println("Argument Error.");
358 | return null;
359 | }
360 | byte [] balanceMsgHashHex=null;
361 | try {
362 | balanceMsgHashHex=Hex.decodeHex(new String(Hex.encodeHex(balanceMsgHash)).toCharArray());
363 | }catch (DecoderException e) {
364 | System.out.println("Couldn't convert msgHashHex = 0x" + Hex.encodeHexString(balanceMsgHash) + " to byte array.");
365 | return null;
366 | }
367 | return senderWallet.signMessage(balanceMsgHashHex);
368 | }
369 |
370 | /**
371 | * This function is to close the channel in a cooperative manner.
372 | * @param delegatorName the delegator's name used to retrieve the wallet, as the signer of the channel closing transaction.
373 | * @param senderName the name of sender of this channel
374 | * @param receiverName the name of receiver of this channel
375 | * @param openBlockNum the block index where the channel was open in decimal literal
376 | * @param balance the double literal of the amount of taken paying to the receiver.
377 | */
378 | public void closeChannelCooperatively(String delegatorName, String senderName, String receiverName, String openBlockNum, String balance) {
379 | BigInteger tempBalance=null;
380 | try {
381 | tempBalance=Utility.decimalToBigInteger(balance, appendingZerosForTKN);
382 | }catch(NumberFormatException e) {
383 | System.out.println("The provided balance is not valid.");
384 | return;
385 | }
386 | Wallet delegatorWallet=null;
387 | Wallet senderWallet=null;
388 | Wallet receiverWallet=null;
389 | try {
390 | delegatorWallet=new Wallet(delegatorName);
391 | delegatorWallet.update(httpAgent);
392 | senderWallet=new Wallet(senderName);
393 | senderWallet.update(httpAgent);
394 | receiverWallet=new Wallet(receiverName);
395 | receiverWallet.update(httpAgent);
396 | }catch(Exception e) {
397 | System.out.println("The delagator/sender/receiver cannot be found.");
398 | return;
399 | }
400 |
401 | byte[] closing_Msg_Hash_Sig=getClosingMsgHashSig(senderWallet.getAccountID(),channelAddr,openBlockNum,balance,receiverName);
402 | byte[] balance_Msg_Hash_Sig=getBalanceMsgHashSig(receiverWallet.getAccountID(),channelAddr,openBlockNum,balance,senderName);
403 | if(closing_Msg_Hash_Sig==null||balance_Msg_Hash_Sig==null) {
404 | System.out.println("Argument Error!");
405 | return;
406 | }
407 | if(debugInfo) {
408 | System.out.println("The signed closingMsgHash is 0x"+Hex.encodeHexString(closing_Msg_Hash_Sig));
409 | System.out.println("The signed balanceMsgHash is 0x"+Hex.encodeHexString(balance_Msg_Hash_Sig));
410 | }
411 | byte[] balance_Msg_Hash_Sig_r=Arrays.copyOfRange(balance_Msg_Hash_Sig, 0, 32);
412 | byte[] balance_Msg_Hash_Sig_s=Arrays.copyOfRange(balance_Msg_Hash_Sig, 32, 64);
413 | byte[] balance_Msg_Hash_Sig_v=Arrays.copyOfRange(balance_Msg_Hash_Sig, 64, 65);
414 | byte[] closing_Msg_Hash_Sig_r=Arrays.copyOfRange(closing_Msg_Hash_Sig, 0, 32);
415 | byte[] closing_Msg_Hash_Sig_s=Arrays.copyOfRange(closing_Msg_Hash_Sig, 32, 64);
416 | byte[] closing_Msg_Hash_Sig_v=Arrays.copyOfRange(closing_Msg_Hash_Sig, 64, 65);
417 |
418 | //if(debugInfo) {
419 | System.out.println("User "+delegatorName+" is the delegator to close the channel "+senderName+" ==> "+receiverName+" at balance = "+balance+".");
420 | //}
421 |
422 |
423 | CallTransaction.Function cooperativeClose=channelContract.getByName("cooperativeClose");
424 | byte [] cooperativeCloseFunctionBytes=cooperativeClose.encode(receiverWallet.getAccountID(),
425 | new BigInteger(openBlockNum,10),tempBalance,balance_Msg_Hash_Sig_r,balance_Msg_Hash_Sig_s,new BigInteger(balance_Msg_Hash_Sig_v),closing_Msg_Hash_Sig_r,closing_Msg_Hash_Sig_s,new BigInteger(closing_Msg_Hash_Sig_v));
426 | String querycooperativeCloseGasString = "{\"method\":\"eth_estimateGas\"," +
427 | "\"params\":[" +
428 | "{" +
429 | "\"from\":\""+delegatorWallet.getAccountID()+"\"," +
430 | "\"to\":\""+channelAddr+"\"," +
431 | "\"value\":\""+"0x"+new BigInteger("0",10).toString(16)+"\","+
432 | "\"data\":\""+"0x" + new String(org.apache.commons.codec.binary.Hex.encodeHex(cooperativeCloseFunctionBytes))+"\"" +
433 | "}" +
434 | "]," +
435 | "\"id\":42,\"jsonrpc\":\"2.0\"}";
436 | if(debugInfo) {
437 | System.out.println("The request string of querycooperativeCloseGasString is "+querycooperativeCloseGasString);
438 | }
439 | String cooperativeCloseGasEstimate="";
440 | try {
441 | cooperativeCloseGasEstimate=(String)httpAgent.getHttpResponse(querycooperativeCloseGasString);
442 | }catch (IOException e) {
443 | System.out.println("Invoking function with given arguments is not allowed.");
444 | return;
445 | }
446 | if(debugInfo) {
447 | System.out.println("The estimatedGas of cooperative channel closing is "+cooperativeCloseGasEstimate+".");
448 | }
449 |
450 | Transaction cooperativeCloseTrans = new Transaction(Utility.bigIntegerToBytes(delegatorWallet.nonce()), // nonce
451 | Utility.bigIntegerToBytes(gasPrice), // gas price
452 | Utility.bigIntegerToBytes(new BigInteger(cooperativeCloseGasEstimate.substring(2),16)), // gas limit
453 | ByteUtil.hexStringToBytes(channelAddr), // to id
454 | Utility.bigIntegerToBytes(new BigInteger("0",10)), // value
455 | cooperativeCloseFunctionBytes, 42);// chainid
456 | delegatorWallet.signTransaction(cooperativeCloseTrans);
457 | String signedCooperativeCloseTranss = "0x" + new String(org.apache.commons.codec.binary.Hex.encodeHex(cooperativeCloseTrans.getEncoded()));
458 | String cooperativeCloseSendRawTransactionString = "{\"method\":\"eth_sendRawTransaction\",\"params\":[\""
459 | + signedCooperativeCloseTranss + "\"],\"id\":42,\"jsonrpc\":\"2.0\"}";
460 |
461 | String myTransactionID="";
462 | try {
463 | myTransactionID=(String)httpAgent.getHttpResponse(cooperativeCloseSendRawTransactionString);
464 | }catch (IOException e) {
465 | System.out.println("Fail to execute HTTP request.");
466 | return;
467 | }
468 |
469 | if(!"".equals(myTransactionID)) {
470 | System.out.println("Waiting for Kovan to mine transactions ... ");
471 | waitingForTransaction(myTransactionID);
472 | }
473 | //if(debugInfo) {
474 | System.out.println("\bChannel has been closed.");
475 | //}
476 | }
477 |
478 | public void getTokenBalance(String accountName){
479 | Wallet myWallet=null;
480 | try{
481 | myWallet=new Wallet(accountName);
482 | myWallet.update(httpAgent);
483 | }catch(Exception e) {
484 | System.out.println("The wallet cannot be retrived for "+accountName);
485 | return;
486 | }
487 |
488 | CallTransaction.Function balanceOf = tokenContract.getByName("balanceOf");
489 | byte [] functionBytes=balanceOf.encode(myWallet.getAccountID());
490 | String requestString = "{\"method\":\"eth_call\"," +
491 | "\"params\":[" +
492 | "{" +
493 | "\"to\":\""+tokenAddr+"\"," +
494 | "\"data\":\""+"0x" + new String(org.apache.commons.codec.binary.Hex.encodeHex(functionBytes))+"\"" +
495 | "}," +
496 | "\"latest\"" +
497 | "]," +
498 | "\"id\":42,\"jsonrpc\":\"2.0\"}";
499 | if(debugInfo) {
500 | System.out.println("Request in getTokenBalance = "+requestString);
501 | }
502 | String myTokenBalance="";
503 | try {
504 | myTokenBalance=(String)httpAgent.getHttpResponse(requestString);
505 | }catch (IOException e) {
506 | System.out.println("Cannot get token balance for "+accountName);
507 | return;
508 | }
509 | System.out.println("Balance of "+accountName+" = "+new Float(new BigInteger(myTokenBalance.substring(2),16).doubleValue()/(new BigInteger(appendingZerosForTKN,10).doubleValue())).toString()+" TKN");
510 |
511 | }
512 |
513 | /**
514 | * Create a channel from sender to receiver. The sender needs to sign the transactions of approve and channel creation
515 | * @param senderAccountName the name of the sender
516 | * @param receiverAccountName the name of the receiver
517 | * @param deposit the double literal as the initial deposit of the channel.
518 | */
519 | public void createChannel(String senderAccountName, String receiverAccountName, String deposit) {
520 | BigInteger initDeposit=null;
521 | try {
522 | initDeposit=Utility.decimalToBigInteger(deposit, appendingZerosForTKN);
523 | }catch(NumberFormatException e) {
524 | System.out.println("The provided balance is not valid.");
525 | return;
526 | }
527 | if(MAX_DEPOSIT.compareTo(initDeposit)<0) {
528 | System.out.println("Please choose a deposit <= "+MAX_DEPOSIT.toString(10));
529 | return;
530 | }
531 | Wallet senderWallet=null;
532 | Wallet receiverWallet=null;
533 | try {
534 | senderWallet=new Wallet(senderAccountName);
535 | senderWallet.update(httpAgent);
536 | receiverWallet=new Wallet(receiverAccountName);
537 | receiverWallet.update(httpAgent);
538 | }catch(Exception e) {
539 | System.out.println("The sender/receiver cannot be found.");
540 | return;
541 | }
542 |
543 |
544 | //if(debugInfo) {
545 | System.out.println("User "+senderAccountName+" tries to open a channel to pay "+receiverAccountName+" up to " + deposit +" Tokens at maximum.");
546 | //}
547 |
548 | CallTransaction.Function approve=tokenContract.getByName("approve");
549 | byte [] approveFunctionBytes=approve.encode(channelAddr,initDeposit);
550 | String queryApproveGasString = "{\"method\":\"eth_estimateGas\"," +
551 | "\"params\":[" +
552 | "{" +
553 | "\"from\":\""+senderWallet.getAccountID()+"\"," +
554 | "\"to\":\""+tokenAddr+"\"," +
555 | "\"value\":\""+"0x"+new BigInteger("0",10).toString(16)+"\","+
556 | "\"data\":\""+"0x" + new String(org.apache.commons.codec.binary.Hex.encodeHex(approveFunctionBytes))+"\"" +
557 | "}" +
558 | "]," +
559 | "\"id\":42,\"jsonrpc\":\"2.0\"}";
560 | if(debugInfo) {
561 | System.out.println("The request string of queryApproveGasString is "+queryApproveGasString);
562 | }
563 | String approveGasEstimate="";
564 | try {
565 | approveGasEstimate=(String)httpAgent.getHttpResponse(queryApproveGasString);
566 | }catch (IOException e) {
567 | System.out.println("Invoking function with given arguments is not allowed.");
568 | return;
569 | }
570 | if(debugInfo) {
571 | System.out.println("The estimatedGas of approve is "+approveGasEstimate+".");
572 | System.out.println("The nonce of "+senderAccountName+" is "+senderWallet.nonce().toString(10));
573 | }
574 |
575 | Transaction approveTrans = new Transaction(Utility.bigIntegerToBytes(senderWallet.nonce()), // nonce
576 | Utility.bigIntegerToBytes(gasPrice), // gas price
577 | Utility.bigIntegerToBytes(new BigInteger(approveGasEstimate.substring(2),16)), // gas limit
578 | ByteUtil.hexStringToBytes(tokenAddr), // to id
579 | Utility.bigIntegerToBytes(new BigInteger("0",10)), // value
580 | approveFunctionBytes, 42);// chainid
581 | senderWallet.signTransaction(approveTrans);
582 | String signedApproveTrans = "0x" + new String(org.apache.commons.codec.binary.Hex.encodeHex(approveTrans.getEncoded()));
583 | String approveSendRawTransactionString = "{\"method\":\"eth_sendRawTransaction\",\"params\":[\""
584 | + signedApproveTrans + "\"],\"id\":42,\"jsonrpc\":\"2.0\"}";
585 |
586 | String myTransactionID1="";
587 | try {
588 | myTransactionID1=(String)httpAgent.getHttpResponse(approveSendRawTransactionString);
589 | }catch (IOException e) {
590 | System.out.println("Fail to execute HTTP request.");
591 | return;
592 | }
593 |
594 | if(!"".equals(myTransactionID1)) {
595 | System.out.println("Waiting for Kovan to mine transactions ... ");
596 | waitingForTransaction(myTransactionID1);
597 | }
598 | if(debugInfo) {
599 | System.out.println("\bApproving funding transfer is done.");
600 | }
601 | try {
602 | senderWallet.updateNonce(httpAgent);
603 | }catch(Exception e){
604 | System.out.println("Updating nonce value is failed.");
605 | return;
606 | }
607 | if(debugInfo) {
608 | System.out.println("The nonce of "+senderAccountName+" is "+senderWallet.nonce().toString(10));
609 | }
610 |
611 | CallTransaction.Function createChannelERC20 = channelContract.getByName("createChannelERC20");
612 | byte [] createChannelERC20FunctionBytes=createChannelERC20.encode(receiverWallet.getAccountID(),initDeposit);
613 | String queryCreatChannelGasString = "{\"method\":\"eth_estimateGas\"," +
614 | "\"params\":[" +
615 | "{" +
616 | "\"from\":\""+senderWallet.getAccountID()+"\"," +
617 | "\"to\":\""+channelAddr+"\"," +
618 | "\"value\":\""+"0x"+new BigInteger("0",10).toString(16)+"\","+
619 | "\"data\":\""+"0x" + new String(org.apache.commons.codec.binary.Hex.encodeHex(createChannelERC20FunctionBytes))+"\"" +
620 | "}" +
621 | "]," +
622 | "\"id\":42,\"jsonrpc\":\"2.0\"}";
623 | if(debugInfo) {
624 | System.out.println("The request string of queryCreatChannelGasString is "+queryCreatChannelGasString);
625 | }
626 | String creatChannelGasEstimate="";
627 | try {
628 | creatChannelGasEstimate=(String)httpAgent.getHttpResponse(queryCreatChannelGasString);
629 | }catch (IOException e) {
630 | System.out.println("Invoking function with given arguments is not allowed.");
631 | return;
632 | }
633 |
634 | if(debugInfo) {
635 | System.out.println("The estimatedGas of createChannelERC20 is "+creatChannelGasEstimate);
636 | }
637 | Transaction createTrans = new Transaction(Utility.bigIntegerToBytes(senderWallet.nonce()), // nonce
638 | Utility.bigIntegerToBytes(gasPrice), // gas price
639 | Utility.bigIntegerToBytes(new BigInteger(creatChannelGasEstimate.substring(2),16)), // gas limit
640 | ByteUtil.hexStringToBytes(channelAddr), // to id
641 | Utility.bigIntegerToBytes(new BigInteger("0",10)), // value
642 | createChannelERC20FunctionBytes, 42);// chainid
643 | senderWallet.signTransaction(createTrans);
644 | String signedChannelCreationTrans = "0x" + new String(org.apache.commons.codec.binary.Hex.encodeHex(createTrans.getEncoded()));
645 | String createChannelSendRawTransactionString = "{\"method\":\"eth_sendRawTransaction\",\"params\":[\""
646 | + signedChannelCreationTrans + "\"],\"id\":42,\"jsonrpc\":\"2.0\"}";
647 |
648 | String myTransactionID2="";
649 | try {
650 | myTransactionID2=(String)httpAgent.getHttpResponse(createChannelSendRawTransactionString);
651 | }catch (IOException e) {
652 | System.out.println("Fail to execute HTTP request.");
653 | return;
654 | }
655 |
656 | if(!"".equals(myTransactionID2)) {
657 | String blockNumberHex=waitingForTransaction(myTransactionID2);
658 |
659 | System.out.println("\bChannel has been opened in block "+new BigInteger(blockNumberHex.substring(2),16).toString(10));
660 |
661 | Digest keccak256 = Digests.keccak256();
662 |
663 |
664 | String firstArgVal=senderWallet.getAccountID().substring(2).toLowerCase();
665 | String secondArgVal=receiverWallet.getAccountID().substring(2).toLowerCase();
666 | String thirdArgVal=Utility.prependingZeros(blockNumberHex.substring(2), 8);
667 | try{
668 | byte[] data = Utility.concatenateByteArrays(Hex.decodeHex(firstArgVal.toCharArray()),Hex.decodeHex(secondArgVal.toCharArray()),Hex.decodeHex(thirdArgVal.toCharArray()));
669 | if(debugInfo) {
670 | System.out.println("The keccak256 argument of bytes in string "+Hex.encodeHexString(data));
671 | }
672 | byte[] keyInBytes=keccak256.reset().update(data).digest();
673 | String channelKeyHex = "0x"+new String(Hex.encodeHexString(keyInBytes));
674 | System.out.println("\bChannel key = "+channelKeyHex);
675 | System.out.println("Channel on Koven can be found on page:\nhttps://kovan.etherscan.io/address/"+channelAddr+"#readContract");
676 | }catch (DecoderException e) {
677 | System.out.println("Hex string cannot be converted to byte array!");
678 | }
679 |
680 | }
681 | return;
682 |
683 | }
684 |
685 | /**
686 | * Allows user buy some token. If the user has no token, he can only put zero deposit when creating the channel.
687 | * @param accountName the name of the buyer
688 | * @param amountOfEther the double literal of Ethers would like to trade for tokens. 0.1 Ether OK for demo.
689 | */
690 | public void buyToken(String accountName,String amountOfEther){
691 | BigInteger value=null;
692 | try {
693 | value=Utility.decimalToBigInteger(amountOfEther, appendingZerosForETH);
694 | }catch(NumberFormatException e) {
695 | System.out.println("The provided balance is not valid.");
696 | return;
697 | }
698 |
699 | Wallet myWallet=null;
700 | try{
701 | myWallet=new Wallet(accountName);
702 | myWallet.update(httpAgent);
703 | }catch(Exception e) {
704 | System.out.println("Cannot retrive the wallet for "+accountName);
705 | return;
706 | }
707 |
708 | if(debugInfo) {
709 | System.out.println("User "+accountName+"("+myWallet.getAccountID()+") will trade "+value.toString()+" Wei to Token.");
710 | }
711 |
712 | CallTransaction.Function mint = tokenContract.getByName("mint");
713 | byte [] functionBytes=mint.encode();
714 | String queryGasString = "{\"method\":\"eth_estimateGas\"," +
715 | "\"params\":[" +
716 | "{" +
717 | "\"from\":\""+myWallet.getAccountID()+"\"," +
718 | "\"to\":\""+tokenAddr+"\"," +
719 | "\"value\":\""+"0x"+value.toString(16)+"\","+
720 | "\"data\":\""+"0x" + new String(org.apache.commons.codec.binary.Hex.encodeHex(functionBytes))+"\"" +
721 | "}" +
722 | "]," +
723 | "\"id\":42,\"jsonrpc\":\"2.0\"}";
724 | String gasEstimateResult="";
725 | try {
726 | gasEstimateResult=(String)httpAgent.getHttpResponse(queryGasString);
727 | }catch (IOException e) {
728 | System.out.println("Invoking function with given arguments is not allowed.");
729 | return;
730 | }
731 | if(debugInfo) {
732 | System.out.println("The estimatedGas of mint is "+gasEstimateResult);
733 | }
734 |
735 | if(debugInfo) {
736 | System.out.println("Total ether balance of "+accountName+" is "+myWallet.etherBalance().toString(10));
737 | }
738 | if(new BigInteger(gasEstimateResult.substring(2),16).multiply(gasPrice).add(value).compareTo(myWallet.etherBalance())>0) {
739 | System.out.println("Insufficient Ether to finish the transaction.");
740 | return;
741 | }
742 |
743 |
744 | if(debugInfo) {
745 | System.out.println("The nonce of "+accountName+" is "+myWallet.nonce());
746 | }
747 |
748 | Transaction t = new Transaction(Utility.bigIntegerToBytes(myWallet.nonce()), // nonce
749 | Utility.bigIntegerToBytes(gasPrice), // gas price
750 | Utility.bigIntegerToBytes(new BigInteger(gasEstimateResult.substring(2),16)), // gas limit
751 | ByteUtil.hexStringToBytes(tokenAddr), // to id
752 | Utility.bigIntegerToBytes(value), // value
753 | functionBytes, 42);// chainid
754 | myWallet.signTransaction(t);
755 | String signedTrans = "0x" + new String(org.apache.commons.codec.binary.Hex.encodeHex(t.getEncoded()));
756 | String mintSendRawTransactionString = "{\"method\":\"eth_sendRawTransaction\",\"params\":[\""
757 | + signedTrans + "\"],\"id\":42,\"jsonrpc\":\"2.0\"}";
758 |
759 | String myTransactionID="";
760 | try {
761 | myTransactionID=(String)httpAgent.getHttpResponse(mintSendRawTransactionString);
762 | }catch (IOException e) {
763 | System.out.println("Fail to execute HTTP request.");
764 | return;
765 | }
766 |
767 | if(!"".equals(myTransactionID)) {
768 | System.out.println("Waiting for Kovan to mine transactions ... ");
769 | waitingForTransaction(myTransactionID);
770 | }
771 | System.out.println("\bYou have been given 50 tokens.");
772 |
773 |
774 | }
775 |
776 | /**
777 | * Waiting for the transaction to get minded
778 | * @param myTransactionID
779 | * @return the blockNumber where the transaction is at
780 | */
781 | private static String waitingForTransaction(String myTransactionID) {
782 | if(debugInfo) {
783 | System.out.println("Transaction ID = "+myTransactionID);
784 | }
785 | boolean loop=true;
786 | String blockNumber=new String();
787 | Object tempObj=null;
788 | String queryTransactionString = "{\"method\":\"eth_getTransactionReceipt\"," +
789 | "\"params\":[\"" +
790 | myTransactionID +
791 | "\"]," +
792 | "\"id\":42,\"jsonrpc\":\"2.0\"}";
793 | while(loop){
794 |
795 | try {
796 | tempObj=httpAgent.getHttpResponse(queryTransactionString);
797 | }catch (IOException e) {
798 | System.out.println("Fail to execute HTTP request.");
799 | return "";
800 | }
801 | if(tempObj==null){
802 | //do nothing
803 | }else{
804 | loop=false;
805 | JSONObject jsonObject=(JSONObject) tempObj;
806 | //The jsonObject can be further parsed to get more information.
807 | blockNumber = (String)jsonObject.get("blockNumber");
808 | }
809 | try {
810 | int i=5;
811 | while(i-->0) {
812 | Thread.sleep(INTERVAL_CHECK_TRANS_DONE);
813 | System.out.print("\b\\");
814 | Thread.sleep(INTERVAL_CHECK_TRANS_DONE);
815 | System.out.print("\b|");
816 | Thread.sleep(INTERVAL_CHECK_TRANS_DONE);
817 | System.out.print("\b/");
818 | Thread.sleep(INTERVAL_CHECK_TRANS_DONE);
819 | System.out.print("\b-");
820 | }
821 | }catch (InterruptedException e) {
822 |
823 | }
824 | }
825 | return blockNumber;
826 | }
827 |
828 | /**
829 | *
830 | * @param accountName the name of the account would like to query.
831 | */
832 | public void getAccountInfo(String accountName) {
833 | Wallet myWallet=null;
834 | try {
835 | myWallet=new Wallet(accountName);
836 | myWallet.update(httpAgent);
837 | }catch(Exception e) {
838 | System.out.println("Cannot retrive for "+accountName);
839 | return;
840 | }
841 | System.out.println("**********************************************");
842 | System.out.println("AccountName:\t"+myWallet.accountName());
843 | System.out.println("AccountID:\t"+myWallet.getAccountID());
844 | System.out.println("AccountNonce:\t"+myWallet.nonce().toString(10));
845 | System.out.println("AccountBalance:\t"+myWallet.etherBalance().toString(10)+" (Wei)");
846 | System.out.println("**********************************************");
847 | }
848 |
849 | /**
850 | * Displays a list of all available functions
851 | */
852 | private static void displayFunctions() {
853 | System.out.println("Possible Functions: ");
854 | Class cls = MicroRaiden.class;
855 | Method methlist[] = cls.getDeclaredMethods();
856 | for (int i = 0; i < methlist.length; i++) {
857 | Method m = methlist[i];
858 | if(m.getName().equals("main")
859 | || m.getName().equals("displayFunctions")
860 | || m.getName().equals("getECKeyByName")
861 | || m.getName().equals("waitingForTransaction")
862 | || m.getName().equals("getBalanceMsgHashSig")
863 | || m.getName().equals("getClosingMsgHashSig")
864 | || m.getName().equals("getClosingMsgHash")
865 | || m.getName().equals("getBalanceMsgHash")) {
866 | continue;
867 | }
868 |
869 | String params = "";
870 | Class pvec[] = m.getParameterTypes();
871 | for (int j = 0; j < pvec.length; j++) {
872 | params = params + pvec[j];
873 | if(j < (pvec.length - 1)) {
874 | params = params + ", ";
875 | }
876 | }
877 |
878 | System.out.println(" " + m.getReturnType() + " " + m.getName() + "(" + params + ")");
879 | }
880 | }
881 |
882 | public static void main(String[] args) throws Exception {
883 |
884 | MicroRaiden mr = new MicroRaiden();
885 | JSONParser parser = new JSONParser();
886 |
887 | try {
888 | Object obj = parser.parse(new FileReader("rm-ethereum.conf"));
889 |
890 | JSONObject jsonObject = (JSONObject) obj;
891 | for (Object key : jsonObject.keySet()) {
892 | switch((String)key) {
893 | case "debugInfo":
894 | debugInfo=((String) jsonObject.get(key)).equals("true")?true:false;
895 | break;
896 | case "gasPrice":
897 | gasPrice=new BigInteger((String) jsonObject.get(key),10);
898 | if(debugInfo) {
899 | System.out.println("The global gas price is set to be "+gasPrice.toString(10));
900 | }
901 | break;
902 | case "rpcAddress":
903 | rpcAddress=((String) jsonObject.get(key));
904 | if(debugInfo) {
905 | System.out.println("rpcAddress = "+rpcAddress);
906 | }
907 | break;
908 | case "channelAddr":
909 | channelAddr=((String) jsonObject.get(key));
910 | if(debugInfo) {
911 | System.out.println("channelAddr = "+channelAddr);
912 | }
913 | break;
914 | case "tokenAddr":
915 | tokenAddr=((String) jsonObject.get(key));
916 | if(debugInfo) {
917 | System.out.println("tokenAddr = "+tokenAddr);
918 | }
919 | break;
920 | case "channelABI":
921 | channelABI=((String) jsonObject.get(key));
922 | if(debugInfo) {
923 | System.out.println("channelABI = "+channelABI);
924 | }
925 | channelContract = new CallTransaction.Contract(channelABI);
926 | break;
927 | case "tokenABI":
928 | tokenABI=((String) jsonObject.get(key));
929 | if(debugInfo) {
930 | System.out.println("tokenABI = "+tokenABI);
931 | }
932 | tokenContract = new CallTransaction.Contract(tokenABI);
933 | break;
934 | case "appendingZerosForETH":
935 | appendingZerosForETH=((String) jsonObject.get(key));
936 | if(debugInfo) {
937 | System.out.println("appendingZerosForETH = "+appendingZerosForETH);
938 | }
939 | break;
940 | case "appendingZerosForTKN":
941 | appendingZerosForTKN=((String) jsonObject.get(key));
942 | if(debugInfo) {
943 | System.out.println("appendingZerosForTKN = "+appendingZerosForTKN);
944 | }
945 | break;
946 | case "maxDepositBits":
947 | MAX_DEPOSIT=new BigInteger("2",10).pow(Integer.parseInt(((String) jsonObject.get(key))));
948 | gasPrice=new BigInteger((String) jsonObject.get(key),10);
949 | if(debugInfo) {
950 | System.out.println("MAX_DEPOSIT ="+MAX_DEPOSIT.toString(16));
951 | }
952 | break;
953 |
954 |
955 | default:
956 | System.out.println("Unknown key is detected when parsing the configuration files.");
957 | }
958 | httpAgent=new Http(rpcAddress,debugInfo);
959 |
960 | }
961 |
962 | } catch (FileNotFoundException e) {
963 |
964 | } catch (ParseException e) {
965 | System.out.println("Couldn't parse contents in m-ethereum.conf as a JSON object."+e);
966 | } catch (IOException e) {
967 | System.out.println("Couldn't parse contents in m-ethereum.conf as a JSON object."+e);
968 | }
969 |
970 | if(args.length < 1) {
971 | System.out.println("Usage: microraiden-java ");
972 | displayFunctions();
973 | return;
974 | }
975 |
976 | //get the function name - use reflection to call
977 | String functionName = args[0];
978 |
979 | //some trickery to get the method with the params (if we just
980 | //try to search for the method without the params specified it
981 | //will only look for parameter-less version
982 | Class cls = Class.forName("MicroRaiden");
983 | Method method = null;
984 | Method methlist[] = cls.getDeclaredMethods();
985 | for (int i = 0; i < methlist.length; i++) {
986 | Method m = methlist[i];
987 | if(m.getName().equals(functionName)) {
988 | method = m;
989 | break;
990 | }
991 | }
992 |
993 | //cast the args to the correct type for the function params
994 | //note if you use a weird type this will probably shit itself.
995 | Object arglist[] = new Object[args.length - 1];
996 | Class pvec[] = method.getParameterTypes();
997 | for(int i = 1; i < args.length; i++) {
998 | if(pvec.length < i) {
999 | break;
1000 | }
1001 |
1002 | String argtype = args[i].getClass().getName();
1003 | String actualType = pvec[i-1].getName();
1004 | if(!argtype.equals(actualType)) {
1005 | switch(actualType) {
1006 | case "int": {
1007 | arglist[i-1] = Integer.parseInt(args[i]);
1008 | break;
1009 | }
1010 | default: {
1011 | System.out.println("UNKNOWN PARAM TYPE: " + actualType);
1012 | return;
1013 | }
1014 | }
1015 | } else {
1016 | arglist[i-1] = args[i];
1017 | }
1018 | }
1019 |
1020 | Object retobj = method.invoke(mr, arglist);
1021 | }
1022 | }
1023 |
--------------------------------------------------------------------------------
/src/main/java/Utility.java:
--------------------------------------------------------------------------------
1 | import java.math.BigInteger;
2 |
3 | import org.kocakosm.pitaya.security.Digest;
4 | import org.kocakosm.pitaya.security.Digests;
5 |
6 | public class Utility {
7 | /**
8 | *
9 | * @param hexString string to be prepended zeros
10 | * @param totalWidth the width of the result
11 | * @return the required string with prepended zeros
12 | */
13 | public static String prependingZeros(String hexString, int totalWidth) {
14 | String result="";
15 | while(result.length()+hexString.length()19) {
64 | balance=balance.substring(0,balance.indexOf(".")+19);
65 | }
66 | String localAppendingZerosForTKN=template.substring(0, template.length()-balance.length()+1+balance.indexOf("."));
67 | tempBalance=new BigInteger(balance.replace(".", "")).multiply(new BigInteger(localAppendingZerosForTKN));
68 | }else {
69 | tempBalance=new BigInteger(balance,10).multiply(new BigInteger(template));
70 | }
71 | return tempBalance;
72 | }
73 |
74 | /**
75 | * Convert BigInteger to the byte array used as arguments of calling smart contract functions.
76 | * @param value the BigInteger to be changed to byte array.
77 | * @return the byte array sent to contract functions.
78 | */
79 | public static byte[] bigIntegerToBytes(BigInteger value) {
80 | if (value == null)
81 | return null;
82 |
83 | byte[] data = value.toByteArray();
84 |
85 | if (data.length != 1 && data[0] == 0) {
86 | byte[] tmp = new byte[data.length - 1];
87 | System.arraycopy(data, 1, tmp, 0, tmp.length);
88 | data = tmp;
89 | }
90 | return data;
91 | }
92 |
93 | /**
94 | * Calculate the SHA3 (a.k.a. Keccak) hash value of messageToBeHashed
95 | * @param messageToBeHashed the message to be hashed in byte array
96 | * @return
97 | */
98 | public static byte[] getSHA3HashHex(byte[] messageToBeHashed) {
99 | Digest keccak256 = Digests.keccak256();
100 | keccak256.reset();
101 | keccak256.update(messageToBeHashed);
102 | return keccak256.digest();
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/src/main/java/Wallet.java:
--------------------------------------------------------------------------------
1 | import java.io.FileNotFoundException;
2 | import java.io.FileReader;
3 | import java.io.IOException;
4 | import java.math.BigInteger;
5 |
6 | import org.apache.commons.codec.DecoderException;
7 | import org.apache.commons.codec.binary.Hex;
8 | import org.ethereum.core.Transaction;
9 | import org.ethereum.crypto.ECKey;
10 | import org.json.simple.JSONObject;
11 | import org.json.simple.parser.JSONParser;
12 | import org.json.simple.parser.ParseException;
13 |
14 | /**
15 | *
16 | * @author david
17 | * This class creates a wallet with the account name.
18 | */
19 | public class Wallet {
20 | private String accountName;
21 | private BigInteger nonce;
22 | private BigInteger etherBalance;
23 | private ECKey ecKeyPair;
24 |
25 | /**
26 | * Create a wallet with the account name
27 | * @param _accountName the account name used to retrieve the wallet.
28 | * @throws Exception
29 | */
30 | public Wallet(String _accountName) throws Exception {
31 | this.accountName=_accountName;
32 | this.ecKeyPair=getECKeyByName(accountName);
33 | }
34 |
35 | /**
36 | * Get the nonce of the account
37 | * @param httpAgent the HTTP agent used to get the nonce from a running peer via the RPC
38 | * @return the nonce in BigInteger
39 | * @throws IOException
40 | */
41 | private BigInteger getNonce(Http httpAgent) throws IOException{
42 | String queryNonceString="{\"method\":\"parity_nextNonce\",\"params\":[\"0x"+Hex.encodeHexString(ecKeyPair.getAddress())+"\"],\"id\":42,\"jsonrpc\":\"2.0\"}";
43 | String myNonceResult="";
44 | try {
45 | myNonceResult=(String)httpAgent.getHttpResponse(queryNonceString);
46 | }catch (IOException e) {
47 | throw e;
48 | }
49 | return new BigInteger(myNonceResult.substring(2),16);
50 | }
51 |
52 | /**
53 | * Get the balance of ether on the Ethereum network.
54 | * @param httpAgent the HTTP agent used to get the Ether balance from a running peer via the RPC
55 | * @return the Ether balance in BigInteger
56 | * @throws IOException
57 | */
58 | private BigInteger getEtherBalance(Http httpAgent) throws IOException{
59 | String queryEtherBalanceString="{\"method\":\"eth_getBalance\",\"params\":[\"0x"+Hex.encodeHexString(ecKeyPair.getAddress())+"\"],\"id\":42,\"jsonrpc\":\"2.0\"}";
60 | //System.out.println("The request string in getEtherBalance is "+requestString);
61 | String myEtherBalance="";
62 | try {
63 | myEtherBalance=(String)httpAgent.getHttpResponse(queryEtherBalanceString);
64 | }catch (IOException e) {
65 | throw e;
66 | }
67 | return new BigInteger(myEtherBalance.substring(2),16);
68 | }
69 |
70 | /**
71 | * Retrieve the wallet by using the account name.
72 | * @param accountName name of the account used to get the wallet
73 | * @return the key pair of elliptic curve
74 | * @throws DecoderException
75 | * @throws FileNotFoundException
76 | * @throws ParseException
77 | * @throws IOException
78 | */
79 | private ECKey getECKeyByName(String accountName) throws DecoderException,FileNotFoundException,ParseException,IOException{
80 | JSONParser parser = new JSONParser();
81 | JSONObject jobj=new JSONObject();
82 | try {
83 | jobj = (JSONObject)parser.parse(new FileReader(accountName+".pkey"));
84 |
85 | } catch (FileNotFoundException e) {
86 | throw e;
87 | } catch (ParseException e) {
88 | throw e;
89 | } catch (IOException e) {
90 | throw e;
91 | }
92 | try{
93 | return ECKey.fromPrivate(Hex.decodeHex(((String) jobj.get("privkey")).toCharArray()));
94 | }catch (DecoderException e) {
95 | throw e;
96 | }
97 | }
98 |
99 | /**
100 | * Update both nonce and etherBalance via RPC
101 | * @param httpAgent httpAgent the HTTP agent used to get account information from a running peer via the RPC
102 | * @throws IOException
103 | */
104 | public void update(Http httpAgent) throws IOException{
105 | try {
106 | nonce=getNonce(httpAgent);
107 | etherBalance=getEtherBalance(httpAgent);
108 | }catch(IOException e){
109 | throw e;
110 | }
111 | }
112 |
113 | /**
114 | * Get the account ID in Hex with "0x" prefix.
115 | * @return the AccountID in HEX format with "0x" prefix
116 | */
117 | public String getAccountID() {
118 | return "0x"+Hex.encodeHexString(ecKeyPair.getAddress());
119 | }
120 |
121 | /**
122 | * Sign a message with this account's private key
123 | * @param message the message in byte array to be signed
124 | * @return the signature
125 | */
126 | public byte[] signMessage(byte[] message) {
127 | return ecKeyPair.sign(message).toByteArray();
128 | }
129 |
130 | /**
131 | * Sign a transaction with this account pricate key
132 | * @param trans transaction to be signed
133 | */
134 | public void signTransaction(Transaction trans) {
135 | trans.sign(ecKeyPair);
136 | }
137 |
138 | /**
139 | * Get the nonce of this account.
140 | * @return the nonce of this account in Ethereum network.
141 | */
142 | public BigInteger nonce() {
143 | return nonce;
144 | }
145 |
146 | /**
147 | * Get Ether balance of this account
148 | * @return the balance in Ether of this account.
149 | */
150 | public BigInteger etherBalance() {
151 | return etherBalance;
152 | }
153 |
154 | /**
155 | * Get name of this account
156 | * @return account name of this account.
157 | */
158 | public String accountName() {
159 | return accountName;
160 | }
161 |
162 | /**
163 | * Update nonce of this account via RPC
164 | * @param httpAgent the HTTP agent send the RPC request
165 | * @throws IOException
166 | */
167 | public void updateNonce(Http httpAgent) throws IOException{
168 | try {
169 | nonce=getNonce(httpAgent);
170 | }catch(IOException e){
171 | throw e;
172 | }
173 | }
174 |
175 | /**
176 | * Update ether balance of this account via RPC
177 | * @param httpAgent the HTTP agent send the RPC request
178 | * @throws IOException
179 | */
180 | public void updateEtherBalance(Http httpAgent) throws IOException{
181 | try {
182 | etherBalance=getEtherBalance(httpAgent);
183 | }catch(IOException e){
184 | throw e;
185 | }
186 | }
187 |
188 |
189 |
190 | }
191 |
--------------------------------------------------------------------------------
/src/test/java/MicroRaidenTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * This Java source file was generated by the Gradle 'init' task.
3 | */
4 | import org.junit.Test;
5 | import static org.junit.Assert.*;
6 |
7 | public class MicroRaidenTest {
8 | @Test public void test() {
9 | MicroRaiden classUnderTest = new MicroRaiden();
10 | assert(true);
11 | }
12 | }
13 |
--------------------------------------------------------------------------------