├── .gitignore
├── LICENSE
├── README.md
├── assets
├── ApplyTransaction_process.png
├── cosmos
│ ├── abci.png
│ └── tm-transaction-flow.png
├── fomo3d
│ ├── affiliate.png
│ ├── affiliate2.png
│ ├── buyXaddr.png
│ ├── ethLimiter.png
│ ├── ethLimiter2.png
│ ├── fomo3d上线.png
│ └── p3d部署.jpg
└── 群入口.png
├── posts
├── cosmos
│ └── cosmos_sdk_1.md
├── ethereum_handle_tx_1.md
├── ethereum_handle_tx_2.md
├── fomo3d-上线部署要点.md
├── fomo3d-钱都去哪儿了.md
├── tokenMapping.md
└── why_choose_rn.md
└── temp
└── enb.sol
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea/
2 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # blockservice's blog
2 |
3 | Just record our life.
4 |
5 | * [以太坊-交易的处理过程上篇](/posts/ethereum_handle_tx_1.md)
6 | * [以太坊-交易的处理过程下篇](/posts/ethereum_handle_tx_2.md)
7 | * [ecoinWallet为什么选择React-Native](/posts/why_choose_rn.md)
8 |
9 | 所有的blog详见[posts](/posts)目录 ...
10 |
11 | 有任何想讨论的问题,欢迎建立issue来探讨
12 |
13 | 也可扫码加群技术交流
14 |
15 | 
16 |
--------------------------------------------------------------------------------
/assets/ApplyTransaction_process.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/blockservice/blog/72742ed59e6bb5577ae7f8f82aff4b27e2afcd50/assets/ApplyTransaction_process.png
--------------------------------------------------------------------------------
/assets/cosmos/abci.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/blockservice/blog/72742ed59e6bb5577ae7f8f82aff4b27e2afcd50/assets/cosmos/abci.png
--------------------------------------------------------------------------------
/assets/cosmos/tm-transaction-flow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/blockservice/blog/72742ed59e6bb5577ae7f8f82aff4b27e2afcd50/assets/cosmos/tm-transaction-flow.png
--------------------------------------------------------------------------------
/assets/fomo3d/affiliate.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/blockservice/blog/72742ed59e6bb5577ae7f8f82aff4b27e2afcd50/assets/fomo3d/affiliate.png
--------------------------------------------------------------------------------
/assets/fomo3d/affiliate2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/blockservice/blog/72742ed59e6bb5577ae7f8f82aff4b27e2afcd50/assets/fomo3d/affiliate2.png
--------------------------------------------------------------------------------
/assets/fomo3d/buyXaddr.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/blockservice/blog/72742ed59e6bb5577ae7f8f82aff4b27e2afcd50/assets/fomo3d/buyXaddr.png
--------------------------------------------------------------------------------
/assets/fomo3d/ethLimiter.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/blockservice/blog/72742ed59e6bb5577ae7f8f82aff4b27e2afcd50/assets/fomo3d/ethLimiter.png
--------------------------------------------------------------------------------
/assets/fomo3d/ethLimiter2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/blockservice/blog/72742ed59e6bb5577ae7f8f82aff4b27e2afcd50/assets/fomo3d/ethLimiter2.png
--------------------------------------------------------------------------------
/assets/fomo3d/fomo3d上线.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/blockservice/blog/72742ed59e6bb5577ae7f8f82aff4b27e2afcd50/assets/fomo3d/fomo3d上线.png
--------------------------------------------------------------------------------
/assets/fomo3d/p3d部署.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/blockservice/blog/72742ed59e6bb5577ae7f8f82aff4b27e2afcd50/assets/fomo3d/p3d部署.jpg
--------------------------------------------------------------------------------
/assets/群入口.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/blockservice/blog/72742ed59e6bb5577ae7f8f82aff4b27e2afcd50/assets/群入口.png
--------------------------------------------------------------------------------
/posts/cosmos/cosmos_sdk_1.md:
--------------------------------------------------------------------------------
1 | # 解读cosmos-sdk系列(1)
2 |
3 | 通过本系列,可以了解tendermint共识和cosmos-sdk架构的设计思想,并学习到如何通过Cosmos-SDK来快速开发自己的区块链应用。
4 |
5 | cosmos团队把区块链分成了三层
6 |
7 | * 网络层 - p2p负责广播交易
8 | * 共识层 - 对哪些交易打包进块形成共识
9 | * 应用层 - 执行交易,负责交易结果落盘(状态一致)
10 |
11 | >这里的应用层可能会有误解,并非是Dapp层,对于SDK底层的Tendermint来说,除p2p网络和打包块共识外,其他都算是应用部分,
12 | 拿实现比特币公链的例子来讲,应用部分就是维护账户的UTXO数据库,如果对比以太的话,keystore账户和EVM虚机部分就是应用范畴,所以SDK内置了账户、质押、治理、权限等应用模块,可以帮助我们简单地实现底层链的开发。
13 |
14 | 可以把这几层简单理解成各节点通过同步交易集(块)日志,实现数据(状态)一致性。数据库的主从模式不也是同步binlog日志,各自执行(replay,回放)日志后,实现数据(状态)最终落盘,区块节点本身同步块的时候,默认就是去下载交易日志,把执行结果按照逻辑链的形式写入本地leveldb的,然后才能对外提供各类RPC服务。
15 |
16 | ## tendermint共识
17 |
18 | 为后续更好的利用cosmos-sdk,要先了解下Tendermint。
19 |
20 | Tendermint Core 提供了网络和共识层功能,而应用层要通过ABCI协议和Core互通消息msg,简单讲tendermint负责起一个replication engine进程,而应用层要运行一个state macheine进程,进程间通过ABCI消息来通信。
21 |
22 | ABCI协议的消息体用protobuf定义在[这里](https://github.com/tendermint/tendermint/blob/master/abci/types/types.proto),app侧可以响应的request如下:
23 |
24 | ```golang
25 | message Request {
26 | oneof value {
27 | RequestEcho echo = 2;
28 | RequestFlush flush = 3;
29 | RequestInfo info = 4;
30 | RequestSetOption set_option = 5;
31 | RequestInitChain init_chain = 6;
32 | RequestQuery query = 7;
33 | RequestBeginBlock begin_block = 8;
34 | RequestCheckTx check_tx = 9;
35 | RequestDeliverTx deliver_tx = 19;
36 | RequestEndBlock end_block = 11;
37 | RequestCommit commit = 12;
38 | }
39 | }
40 | ```
41 |
42 | ABCI的设计主要有以下几个特点:
43 |
44 | * 消息协议
45 | * 成对出现的消息: `request`/`reponse`
46 | * tendermint发起Request, app来响应
47 | * 使用protobuf定义
48 |
49 | * server/client
50 | * tendermint运行client
51 | * app侧运行server端
52 | * 可以由TSP(支持checkTx和DeliverTx消息的异步处理)、grpc两种方式实现
53 |
54 | * 区块相关
55 | * abci是面向连接的
56 | * tendermint会创建三个socket连接来和app通信,分别是`Mempool`, `Cosensus`, `Query`连接
57 | * `Mempool连接`: 钱包客户端发起交易,会首先进入钱包后台连接的节点的local mempool,该节点通过发送`checkTx`消息来通知app,去检验交易签名是否有效等等,如果OK节点则会p2p广播该交易到其他节点的mempool里。
58 |
59 | * `Cosensus连接`: 出块节点从mempool的交易集里选出一个块提案(proposer),之后会经过3阶段提交(pre-vote, pre-commit, commit)处理,这个块才能说达成共识(上链了),,只有块被commited了,app侧才会更新状态,比如改变某地址余额等等。app更新状态的时候,是通过Core发送`BeginBlock`, `DeliverTx ...`, `EndBlock`, `Commit`消息给app侧来完成的,任何写入操作都是通过此连接完成的。
60 |
61 | * `Query连接`: 主要负责一些和共识无关的查询操作,比如块信息,地址余额等等,主要用到`Info`, `SetOption`, `Query`消息
62 |
63 | 整个abci的信息流大致如下:
64 | 
65 |
66 | 关于Tendermint和app间数据流的更多细节见下:
67 |
68 | 
69 |
70 | [高清图地址](https://github.com/mobfoundry/hackatom/blob/master/tminfo.pdf)
71 |
72 |
73 | ## 总结
74 |
75 | 可以理解成,Tendermint主要负责在BFT环境下同步app间的块交易日志,无论任何交易类型,只要交易块的执行结果是确定性的(唯一性),Tendermint就可以为我们形成区块的共识。
76 |
77 | 比如说,一个交易的内容在合约里创建一个真随机数,这种交易,tendermint是无法为我们形成共识的,因为多个节点的执行结果是不一样的, 因为这个结果是要在下个区块头的,这样就无法对下个区块形成共识了,所有节点都认为对方在恶意“搞分叉”了。
78 |
79 | 目前基于tendermint的项目有很多:
80 |
81 | 我个人看到好的是`BigchainDB`和超级账本`Burrow`项目,更多可以看[这里](https://tendermint.com/ecosystem)
82 |
83 |
84 | 后续源码介绍,如何基于tendermint创建一个区块链
--------------------------------------------------------------------------------
/posts/ethereum_handle_tx_1.md:
--------------------------------------------------------------------------------
1 | # 以太坊节点是如何处理交易的-上篇
2 |
3 | 今天在这里从代码的层面和朋友们分享下以太坊的交易处理流程,如果能帮助新手朋友快速上手,那是我的荣幸,嘿嘿, 直接进入主题吧.
4 | 以太坊对交易的处理过程比较复杂,大致分成以下几步执行:
5 |
6 | - **调用RPC接口,将交易发送到tx_pool的pending队列中.**
7 | - **将pending队列中的txs 在网络中广播出去,让矿机节点收到.**
8 | - **矿机节点创建区块前会从tx pool的pending队列中取出交易并执行;然后将交易,以及交易执行后的receipts等信息封装到区块内,出块,并广播到网络中.**
9 | - **网络中的其他以太坊节点收到区块后,对区块内的交易进行验证,确认无误后,将区块插入到本地的链上.如果校验失败,则区块不能被接受,tx信息同样也不能在网络中同步.**
10 |
11 |
12 | 当用户通过命令行,或者其他方式发送一笔转账交易的时候,node节点会收到RPC请求,经过节点的RPC Server解析处理后,会发送到SendTransaction函数.下面是这个函数的处理过程
13 | ```
14 | go-etherueum/internal/ethapi/api.go
15 | func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args SendTxArgs) (common.Hash, error) {
16 |
17 | //从参数args 中获得发送交易的账户信息,发送交易要用这个账户为交易签名.
18 | account := accounts.Account{Address: args.From}
19 |
20 | //找到跟这个account相关的wallet,account可以动态的从钱包中添加或者删除;wallet也可以有很多个,有可能是usb wallet,有可能是mobile wallet,还可能是keystore节点上的wallet.具体的查找经过交给下面的接口函数就好了
21 | wallet, err := s.b.AccountManager().Find(account)
22 | if err != nil {
23 | return common.Hash{}, err
24 | }
25 |
26 | if args.Nonce == nil {
27 | // Hold the addresse's mutex around signing to prevent concurrent assignment of
28 | // the same nonce to multiple accounts.
29 | s.nonceLock.LockAddr(args.From)
30 | defer s.nonceLock.UnlockAddr(args.From)
31 | }
32 |
33 | //设置一笔交易需要的默认参数,比如获取nonce, 预计消耗的gas, gasprice等等.
34 | if err := args.setDefaults(ctx, s.b); err != nil {
35 | return common.Hash{}, err
36 | }
37 | //根据传入的参数,组装出一笔交易,如果是合约types.NewContractCreation,否则调用types.NewTransaction
38 | tx := args.toTransaction()
39 |
40 | var chainID *big.Int
41 | if config := s.b.ChainConfig(); config.IsEIP155(s.b.CurrentBlock().Number()) {
42 | chainID = config.ChainID
43 | }
44 | //调用wallet的签名函数,给交易签名;只有签名的交易才可以被发送成功.
45 | signed, err := wallet.SignTx(account, tx, chainID)
46 | if err != nil {
47 | return common.Hash{}, err
48 | }
49 | //最后执行submit函数,将交易发送到交易池中.
50 | return submitTransaction(ctx, s.b, signed)
51 | }
52 | ```
53 | 对转发普通交易(本文不涉及合约交易)来说submitTransaction函数的的核心就是执行SendTx
54 | ```
55 | func submitTransaction(ctx context.Context, b Backend, tx *types.Transaction) (common.Hash, error) {
56 | if err := b.SendTx(ctx, tx); err != nil {
57 | return common.Hash{}, err
58 | }
59 | ...
60 | ...
61 | ...
62 | return tx.Hash(), nil
63 | }
64 |
65 | func (b *EthAPIBackend) SendTx(ctx context.Context, signedTx *types.Transaction) error {
66 | //调用AddLocal将这笔签名交易添加到本地的txpool的pending队列中. 接口是简单的,背后实现的过程是复杂的,^_^.
67 | return b.eth.txPool.AddLocal(signedTx)
68 | }
69 | ```
70 | **下面开始一步步剖析一笔tx是如何进入tx_pool的pending队列中的,这段过程稍微漫长.**
71 | 咱们首先介绍下tx pool在以太坊中的作用
72 | txpool主要用来存放当前提交的等待写入区块的交易,有远端和本地的。
73 | txpool里面的交易分为两种,
74 | 1. 提交但是还不能执行的,放在queue里面等待能够执行(比如说nonce太高)。
75 | 2. 等待执行的,放在pending里面等待执行。
76 |
77 | 从txpool的测试案例来看,txpool主要功能有下面几点。
78 | 1. 交易验证的功能,包括余额不足,Gas不足,Nonce太低, value值是合法的,不能为负数。
79 | 2. 能够缓存Nonce比当前本地账号状态高的交易。 存放在queue字段。 如果是能够执行的交易存放在pending字段
80 | 3. 相同用户的相同Nonce的交易只会保留一个GasPrice最大的那个。 其他的插入不成功。
81 | 4. 如果账号没有钱了,那么queue和pending中对应账号的交易会被删除。
82 | 5. 如果账号的余额小于一些交易的额度,那么对应的交易会被删除,同时有效的交易会从pending移动到queue里面。防止被广播。
83 | 6. txPool支持一些限制PriceLimit(remove的最低GasPrice限制),PriceBump(替换相同Nonce的交易的价格的百分比) AccountSlots(每个账户的pending的槽位的最小值) GlobalSlots(全局pending队列的最大值)AccountQueue(每个账户的queueing的槽位的最大值) GlobalQueue(全局queueing的最大值) Lifetime(在queue队列的最长等待时间)
84 | 7. 有限的资源情况下按照GasPrice的优先级进行替换。
85 | 8. 本地的交易会使用journal的功能存放在磁盘上,重启之后会重新导入。 远程的交易不会。
86 | [摘自 go-ethereum-code-analysis](https://github.com/ZtesoftCS/go-ethereum-code-analysis/blob/master/core-txpool%E4%BA%A4%E6%98%93%E6%B1%A0%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90.md)
87 |
88 | 从代码中可以看到,AddLocal很简单,就执行了一行addTx.
89 | ```
90 | func (pool *TxPool) AddLocal(tx *types.Transaction) error {
91 | return pool.addTx(tx, !pool.config.NoLocals)
92 | }
93 | ```
94 | addTx函数主要调用了add和promoteExecutables 两个方法.这两个方法是txpool的重点,值得仔细推敲一遍.
95 | ```
96 | func (pool *TxPool) addTx(tx *types.Transaction, local bool) error {
97 | pool.mu.Lock()
98 | defer pool.mu.Unlock()
99 |
100 | //add方法会对tx进行初步的校验,如果没问题,将tx 加入到txpool的queue中.
101 | replace, err := pool.add(tx, local)
102 | if err != nil {
103 | return err
104 | }
105 | //通过执行promoteExecutables函数,一笔交易才会加入到pending队列,同时会通知网络协程pending队列更新,网络协程会将新的pengding队列广播到整个网络中.
106 | if !replace {
107 | from, _ := types.Sender(pool.signer, tx) // already validated
108 | pool.promoteExecutables([]common.Address{from})
109 | }
110 | return nil
111 | }
112 | ```
113 | ```
114 | func (pool *TxPool) add(tx *types.Transaction, local bool) (bool, error) {
115 | //先检查pool中是否存在交易的哈希,如果存在,则不需要再次加入了,直接报错
116 | hash := tx.Hash()
117 | if pool.all.Get(hash) != nil {
118 | log.Trace("Discarding already known transaction", "hash", hash)
119 | return false, fmt.Errorf("known transaction: %x", hash)
120 | }
121 | //调用validateTx方法对tx进行校验,校验内容包括:
122 | tx占用的存储空间大小,
123 | 签名是否正确,
124 | tx的gas消耗是否合理,
125 | 签名者是否正确,
126 | 该笔交易的nonce值是否合理,
127 | 发送交易账户的金额是否充足等几个方面.
128 | if err := pool.validateTx(tx, local); err != nil {
129 | log.Trace("Discarding invalid transaction", "hash", hash, "err", err)
130 | invalidTxCounter.Inc(1)
131 | return false, err
132 | }
133 | //如果本地的交易队列满了,那么从2方面处理这笔tx
134 | if uint64(pool.all.Count()) >= pool.config.GlobalSlots+pool.config.GlobalQueue {
135 | //如果新的tx的消耗的gas小于本地队列中gas最小的那笔交易,那么这笔新tx就会被丢弃
136 | if !local && pool.priced.Underpriced(tx, pool.locals) {
137 | log.Trace("Discarding underpriced transaction", "hash", hash, "price", tx.GasPrice())
138 | underpricedTxCounter.Inc(1)
139 | return false, ErrUnderpriced
140 | }
141 | //新的tx消耗的gas比本地队列中最少的多,那么删掉本地消耗gas最少的那些交易.如果all.Count()正好等于int(pool.config.GlobalSlots+pool.config.GlobalQueue) 那么Discard函数的参数count最小值是1;count值应该恒>=1
142 | drop := pool.priced.Discard(pool.all.Count()-int(pool.config.GlobalSlots+pool.config.GlobalQueue-1), pool.locals)
143 | for _, tx := range drop {
144 | log.Trace("Discarding freshly underpriced transaction", "hash", tx.Hash(), "price", tx.GasPrice())
145 | underpricedTxCounter.Inc(1)
146 | pool.removeTx(tx.Hash(), false)
147 | }
148 | }
149 | //先获得tx的账户地址,根据账户地址获得相关的pending list. Overlaps函数返回一个布尔值,它会判断新tx的nonce值是否在pending队列中存在,如果存在返回true.
150 | from, _ := types.Sender(pool.signer, tx) // already validated
151 | if list := pool.pending[from]; list != nil && list.Overlaps(tx) {
152 | //新tx的nonce值在pending已经存在了,list.Add会根据PriceBump计算新tx的gas是否超过旧tx,如果新tx的gas超过旧tx的gas量的百分之PriceBump,就用新的tx替换掉旧的tx.这样设计是为了保证矿工的利益最大化.
153 | inserted, old := list.Add(tx, pool.config.PriceBump)
154 | if !inserted {
155 | pendingDiscardCounter.Inc(1)
156 | return false, ErrReplaceUnderpriced
157 | }
158 | //删除掉旧的tx.
159 | if old != nil {
160 | pool.all.Remove(old.Hash())
161 | pool.priced.Removed()
162 | pendingReplaceCounter.Inc(1)
163 | }
164 | pool.all.Add(tx) //将新tx添加到all队列中
165 | pool.priced.Put(tx) //基于tx的price大小,添加到priced队列中,这个队列是顺序排列的
166 | pool.journalTx(from, tx)//将新的tx写入到本地的日志文件中.
167 |
168 | log.Trace("Pooled new executable transaction", "hash", hash, "from", from, "to", tx.To())
169 |
170 | //通知网络系统,队列中的交易更新了
171 | go pool.txFeed.Send(NewTxsEvent{types.Transactions{tx}})
172 | 将拥有相同nonce值的旧tx替换掉,就可以返回了.
173 | return old != nil, nil
174 | }
175 | // 如果新的tx没有替换掉旧的tx,那么通过执行enqueueTx将tx先存放到txpool的queue队列中,
176 | replace, err := pool.enqueueTx(hash, tx)
177 | if err != nil {
178 | return false, err
179 | }
180 | // Mark local addresses and journal local transactions
181 | if local {
182 | pool.locals.add(from)
183 | }
184 | //将tx添加到本地的日志文件中
185 | pool.journalTx(from, tx)
186 |
187 | log.Trace("Pooled new future transaction", "hash", hash, "from", from, "to", tx.To())
188 | return replace, nil
189 | }
190 | ```
191 |
192 | 经过add函数将tx添加到queue队列后,执行promoteExecutables函数,将queue队列中的tx转移到pending队列中.这个函数很长,在进入分析之前,先简单说下它的工作流程,以及相关的数据结构,这样比较便于快速理解.
193 | 这里面主要的数据结构有以下三种:
194 | ```
195 | //这里声明了一个uint64的切片,用这个切片模拟了一个堆,在tx_list.go文件中,还实现了简单的pop,push操作方法.这个数据结构用来存储每笔交易的nonce值.每次产生一笔交易,交易的nonce值就存储到这个切片中.
196 | type nonceHeap []uint64
197 |
198 | //txSortedMap这是个核心数据结构,txList的各种操作逻辑也是封装的txSortedMap,txSortedMap这个结构实现了各种操作nonce堆栈的方法供txList调用,下面会对这些方法进行简单介绍.
199 | type txSortedMap struct {
200 | items map[uint64]*types.Transaction //这个map结构的key 是交易的nonce值,value是该笔交易的交易数据
201 | index *nonceHeap //items中的key也就是nonce都会存储到index数组切片中,按照heap的pop,push方式管理.
202 | cache types.Transactions //这是个Transactions的数组切片,这里暂存已经排好序的交易数据;tx_list.go中调用了golang源码包的快速排序算法
203 | }
204 |
205 | //txList 是基于account的关系维护的,在type TxPool 结构中有两个域pending 和queue,这两个结构都是字典结构map[common.Address]*txList;每个以太节点上txpool的交易队列中的交易都是基于account的txList维护的,这样的设计很容易统计管理.
206 | type txList struct {
207 | strict bool //一个标识符,true表示存储的nonce都是连续,false是不连续的.
208 | txs *txSortedMap //交易队列的核心结构,采用堆栈式管理.
209 | costcap *big.Int //交易花费的最高价格(仅在超出余额时重置)
210 | gascap uint64 //交易消耗的最高gas limit(仅在超过限额时重置)
211 | }
212 |
213 | 个人觉得tx_list.go中代码设计的很精美,他们将数组采用堆栈化的操作,对数组内容增删改查以及排序的手法值得初学golang的朋友们吸收学习下.
214 | ```
215 | 下面简单介绍下操作txSortedMap结构的方法,由于篇幅限制代码细节就不详细描述了,感兴趣的童鞋可以自己看.
216 |
217 | ```
218 | func (m *txSortedMap) Get(nonce uint64) *types.Transaction
219 | Get方法根据传入的交易nonce值,从哈希map中获取到对应的Transaction数据.
220 |
221 | func (m *txSortedMap) Put(tx *types.Transaction)
222 | Put方法将一笔新的交易插入到map结构中,同时将tx的nonce值push到index堆栈中.
223 |
224 | func (m *txSortedMap) Forward(threshold uint64) types.Transactions
225 | Forward方法将nonce值低于阈值threshold的交易从队列中删除;Forward操作的index对象是已经排好顺序的,按照nonce值从小到大排列.
226 |
227 | func (m *txSortedMap) Filter(filter func(*types.Transaction) bool) types.Transactions
228 | Filter方法遍历整个交易map, 将符合过滤函数条件的交易从map中删除.
229 |
230 | func (m *txSortedMap) Cap(threshold int) types.Transactions
231 | Cap方法设置一个阈值nonce,先将整个index数组切片用快速排序算法从小到大排序,然后将超过阈值nonce的交易从map中删除,并更新index数组切片.
232 |
233 | func (m *txSortedMap) Remove(nonce uint64) bool
234 | Remove根据nonce参数,从map中删除相关的tx
235 |
236 | func (m *txSortedMap) Ready(start uint64) types.Transactions
237 | Ready方法返回一个nonce值顺序连续增长的的tx队列.这个ready队列中的交易会被promoteTx处理,添加到txpool中的pending队列上,这些交易将来会被矿机封装到区块中.
238 |
239 | func (m *txSortedMap) Flatten() types.Transactions
240 | Flatten方法先将交易队列中的所有tx存放到cache结构中,然后将cache中的tx队列按照nonce值大小快速排序.
241 |
242 | txList结构也有上面的那些方法,但都是基于txSortMap封装的.
243 | promoteExecutables函数主要就是在用各种业务逻辑操作各个account的txList,也就是调用上面列出的Get,Put,Forward,Filter,Cap,Remove,Ready,Flatten等各种方法,啰嗦了半天就为了这里做铺垫.
244 | ```
245 | promoteExecutables函数的工作逻辑如下:
246 | 先从pool.queue中获得每个accout的list
247 |
248 | 1. 清理相关accout的老旧tx
249 | 2. 清理消耗成本或者gaslimit过高的交易和无效的交易
250 | 3. 收集可执行的交易,存到txpool的pending队列中
251 | 4. 清理非本地accout上的queue队列,使其不超过默认配置.
252 | 5. 通知其他子系统,txpool pending队列已经更新.
253 | 6. 如果txpool的pending队列过长,调整非本地的account的pending队列,将过多txs删除,调整到代码配置许可的范围内. (因为是P2P网络,其他节点上account中的交易也会被广播到本地,这些交易也会存在本地txpool的queue中,但是每个节点要优先要保证本地account发送的交易先上链,所以在超出配置限制的时候,先拿外部account中的交易开刀,这就是其中蕴含的设计思想)
254 | 7. 如果txpool的queue队列过长,根据accout的活跃时间排序,会清理最老的account的queue队列,直到达到系统设置的阈值.
255 |
256 | 下面是具体的执行流程:
257 | ```
258 | func (pool *TxPool) promoteExecutables(accounts []common.Address) {
259 | //跟踪promoted数组切片的长度,一旦更新会立即在网络中广播出去.
260 | var promoted []*types.Transaction
261 |
262 | // 如果accounts 参数为nil ,那么收集pool.queue中所有的account信息.
263 | if accounts == nil {
264 | accounts = make([]common.Address, 0, len(pool.queue))
265 | for addr := range pool.queue {
266 | accounts = append(accounts, addr)
267 | }
268 | }
269 | //遍历accounts中所有的可执行交易,将这些txs 追加到promoted 数组切片中.
270 | for _, addr := range accounts {
271 | list := pool.queue[addr] //从pool.queue中获得每个account的txList.
272 | if list == nil {
273 | continue // Just in case someone calls with a non existing account
274 | }
275 | //先获取当前account的nonce值,将nonce值低于当前nonce的tx,也就是已经失效的tx全部从队列中删除掉
276 | list.Forward返回的是一个切片,符合删除条件的tx都存在这个切片中.
277 | for _, tx := range list.Forward(pool.currentState.GetNonce(addr)) {
278 | hash := tx.Hash()
279 | log.Trace("Removed old queued transaction", "hash", hash)
280 | pool.all.Remove(hash)
281 | pool.priced.Removed() //从priced的heap上删除,每笔tx也存到priced的heap
282 | }
283 | //清除掉花费太高的tx
284 | drops, _ := list.Filter(pool.currentState.GetBalance(addr), pool.currentMaxGas)
285 | for _, tx := range drops {
286 | hash := tx.Hash()
287 | log.Trace("Removed unpayable queued transaction", "hash", hash)
288 | pool.all.Remove(hash)
289 | pool.priced.Removed()
290 | queuedNofundsCounter.Inc(1)
291 | }
292 | //收集所有可执行的交易,存到promoted数组切片中
293 | for _, tx := range list.Ready(pool.pendingState.GetNonce(addr)) {
294 | hash := tx.Hash()
295 | if pool.promoteTx(addr, hash, tx) {//给pending队列添加新的txs.
296 | log.Trace("Promoting queued transaction", "hash", hash)
297 | promoted = append(promoted, tx)
298 | }
299 | }
300 | //AccountQueue是txpool允许的每个account最大可以维护的queue队列长度,如果非本地的account的 tx queue长度超过限制,那么清除掉超过限制的那部分txs.
301 | if !pool.locals.contains(addr) {
302 | for _, tx := range list.Cap(int(pool.config.AccountQueue)) {
303 | hash := tx.Hash()
304 | pool.all.Remove(hash)
305 | pool.priced.Removed()
306 | queuedRateLimitCounter.Inc(1)
307 | log.Trace("Removed cap-exceeding queued transaction", "hash", hash)
308 | }
309 | }
310 | //如果txList是空的,就从queue队列中清除相关account的所有信息.
311 | if list.Empty() {
312 | delete(pool.queue, addr)
313 | }
314 | }
315 | //这里会通知其他子模块,新的tx已经准备好了;比如网络模块收到这个消息后,会在
316 | P2P网络中广播promoted中的交易.
317 | if len(promoted) > 0 {
318 | go pool.txFeed.Send(NewTxsEvent{promoted})
319 | }
320 | // 如果txpool的pending超过限制了.那么调整pending的长度,使其回到允许的范围.
321 | pending := uint64(0)
322 | //统计txpool中所有account的list之和.
323 | for _, list := range pool.pending {
324 | pending += uint64(list.Len())
325 | }
326 | //GlobalSlots是txpool允许的所有account可执行的tx之和,以太坊默认的值是4096
327 | 如果各个账户的pending长度之和超过4096,就执行下面的if分支
328 | if pending > pool.config.GlobalSlots {
329 | pendingBeforeCap := pending
330 | //这里创建一个堆栈,专门用来存储大交易量的外来account,嗯哼,就是喜欢欺负外来户.
331 | spammers := prque.New()
332 | for addr, list := range pool.pending {
333 | //AccountSlots是txpool允许的每个账户最小可执行的tx数量,这个参数是为非本 地节点上的account准备的, local的account莫担心,不会受到它的限制.这个值默认是16,也就是说在txpool的pending超过GlobalSlots的时候,txpool要清理外来户,外来户交易量超过16这个值,要被制裁的,交税也不行,哎,北漂真苦啊!(感慨下人生,O(∩_∩)O~)
334 | if !pool.locals.contains(addr) && uint64(list.Len()) > pool.config.AccountSlots {
335 | //将所有超过限制的非本地的account压栈.给这些account打上了一个logo:offender (中文翻译:坏人)
336 | 这个压栈其实是存在排序的,不是按照时间顺序排的,是按照list的长度排列的.list最长的排在栈尾
337 | spammers.Push(addr, float32(list.Len()))
338 | }
339 | }
340 | //下面开始动手了~~
341 | offenders := []common.Address{}
342 | for pending > pool.config.GlobalSlots && !spammers.Empty() {
343 | //第一次循环,会把list最长的,也就是交易量最大的accout从栈上弹出来
344 | offender, _ := spammers.Pop()
345 | //把offender填到offenders切片中,做个新的黑名单.
346 | 存储的顺序是酱紫的:offenders[0].Len()>offenders[1].Len()>offender[2].Len()...
347 | offenders = append(offenders, offender.(common.Address))
348 |
349 | //如果黑名单的长度达到2以上,开始削减相关account的tx.
350 | if len(offenders) > 1 {
351 | //以当前offenders数组中的最后一个account的txList长度当做阈值,这个值是目前数组中最小的值
352 | threshold := pool.pending[offender.(common.Address)].Len()
353 |
354 | //开始迭代删除offender account的交易数量,直到达到limit或者达到当前的阈值.举个栗子吧: offenders数组有2个account的时候,offenders[0].Len()>offenders[1].Len() 以offenders[1]的.Len()做阈值,删掉offender[0]中超过阈值的txs,直到offender[0].Len()==offenders[1].Len();当offenders数组有3个accounts的时候,以offenders[2].Len()最小,以它做阈值,让offender[0].Len()==offender[1].Len()==offender[2].Len(),以此类推.
355 |
356 | for pending > pool.config.GlobalSlots && pool.pending[offenders[len(offenders)-2]].Len() > threshold {
357 | for i := 0; i < len(offenders)-1; i++ {
358 | list := pool.pending[offenders[i]]
359 | for _, tx := range list.Cap(list.Len() - 1) {
360 | // Drop the transaction from the global pools too
361 | hash := tx.Hash()
362 | pool.all.Remove(hash)
363 | pool.priced.Removed()
364 |
365 | // Update the account nonce to the dropped transaction
366 | if nonce := tx.Nonce(); pool.pendingState.GetNonce(offenders[i]) > nonce {
367 | pool.pendingState.SetNonce(offenders[i], nonce)
368 | }
369 | log.Trace("Removed fairness-exceeding pending transaction", "hash", hash)
370 | }
371 | pending--
372 | }
373 | }
374 | }
375 | }
376 | //迭代删除之后,如果pending总数还是超过limit,继续减少非本地account的txs
377 | if pending > pool.config.GlobalSlots && len(offenders) > 0 {
378 | for pending > pool.config.GlobalSlots && uint64(pool.pending[offenders[len(offenders)-1]].Len()) > pool.config.AccountSlots {
379 | //遍历所有的黑名单account,每个account依次每次删除一条tx,直到满足限制条件.
380 | for _, addr := range offenders {
381 | list := pool.pending[addr]
382 | for _, tx := range list.Cap(list.Len() - 1) {
383 | // Drop the transaction from the global pools too
384 | hash := tx.Hash()
385 | pool.all.Remove(hash)
386 | pool.priced.Removed()
387 |
388 | // Update the account nonce to the dropped transaction
389 | if nonce := tx.Nonce(); pool.pendingState.GetNonce(addr) > nonce {
390 | pool.pendingState.SetNonce(addr, nonce)
391 | }
392 | log.Trace("Removed fairness-exceeding pending transaction", "hash", hash)
393 | }
394 | pending--
395 | }
396 | }
397 | }
398 | pendingRateLimitCounter.Inc(int64(pendingBeforeCap - pending))
399 | }
400 | //这里开始统计txpool的queue总量.
401 | queued := uint64(0)
402 | for _, list := range pool.queue {
403 | queued += uint64(list.Len())
404 | }
405 | //如果queue超过限制,又一次开始准备削减非本地的account!
406 | if queued > pool.config.GlobalQueue {
407 | // Sort all accounts with queued transactions by heartbeat
408 | addresses := make(addresssByHeartbeat, 0, len(pool.queue))
409 | for addr := range pool.queue {
410 | if !pool.locals.contains(addr) { // don't drop locals
411 | //遍历queue中的所有account,为非本地的account们建立个黑名单.
412 | addresses = append(addresses, addressByHeartbeat{addr, pool.beats[addr]})
413 | }
414 | }
415 | //这里采用了golang系统包的快速排序算法,以account的活跃时间排序的.addresses
416 | 切片数组最末尾的成员是最久没有活跃过的account.
417 | sort.Sort(addresses)
418 |
419 | //先从最不活跃的account删减,直到符合limit.
420 | for drop := queued - pool.config.GlobalQueue; drop > 0 && len(addresses) > 0; {
421 | addr := addresses[len(addresses)-1]
422 | list := pool.queue[addr.address]
423 |
424 | addresses = addresses[:len(addresses)-1]
425 |
426 | // Drop all transactions if they are less than the overflow
427 | if size := uint64(list.Len()); size <= drop {
428 | for _, tx := range list.Flatten() {
429 | pool.removeTx(tx.Hash(), true)
430 | }
431 | drop -= size
432 | queuedRateLimitCounter.Inc(int64(size))
433 | continue
434 | }
435 | // Otherwise drop only last few transactions
436 | txs := list.Flatten()
437 | for i := len(txs) - 1; i >= 0 && drop > 0; i-- {
438 | pool.removeTx(txs[i].Hash(), true)
439 | drop--
440 | queuedRateLimitCounter.Inc(1)
441 | }
442 | }
443 | }
444 | }
445 |
446 | 以上就是promoteExecutables函数的工作过程,是tx_pool.go中最复杂的函数,也是维护以太坊交易池正常运行的核心函数,它的工作主旨就是在txpool资源紧张的时候,要优先保证本地account的交易先上链;刚开始看的时候,很容易懵逼,此时需要静下心来,慢慢梳理才会找到头绪.
447 | ```
448 | 以太坊普通节点发交易的交易要广播到矿机的txpool中才会被最终验证执行.promoteExecutables函数在调用完promoteTx函数之后,执行
449 | ```
450 | go pool.txFeed.Send(NewTxsEvent{promoted})
451 |
452 | 这里发送了一个信号'NewTxsEvent'给网络部分,通知网络模块接收准备就绪的交易,将其广播出去.
453 | ```
454 |
455 | 看下eth/handler.go 这个文件
456 | ```
457 | func (pm *ProtocolManager) Start(maxPeers int) {
458 | pm.maxPeers = maxPeers
459 |
460 | //这里创建了接收新交易的channl,并设置了相关的处理函数
461 | pm.txsCh = make(chan core.NewTxsEvent, txChanSize)
462 | pm.txsSub = pm.txpool.SubscribeNewTxsEvent(pm.txsCh)
463 | go pm.txBroadcastLoop()
464 |
465 | // broadcast mined blocks
466 | pm.minedBlockSub = pm.eventMux.Subscribe(core.NewMinedBlockEvent{})
467 | go pm.minedBroadcastLoop()
468 |
469 | // start sync handlers
470 | go pm.syncer()
471 | go pm.txsyncLoop()
472 | }
473 |
474 | func (pm *ProtocolManager) txBroadcastLoop() {
475 | for {
476 | select {
477 | case event := <-pm.txsCh:
478 | pm.BroadcastTxs(event.Txs)
479 |
480 | // Err() channel will be closed when unsubscribing.
481 | case <-pm.txsSub.Err():
482 | return
483 | }
484 | }
485 | }
486 | ```
487 | 最终调用到peer.go文件中的这个函数,将交易队列发送出去;"TxMsg" 是msg type,其他节点要接收txs要识别这个消息码.
488 | ```
489 | func (p *peer) SendTransactions(txs types.Transactions) error {
490 | for _, tx := range txs {
491 | p.knownTxs.Add(tx.Hash())
492 | }
493 | return p2p.Send(p.rw, TxMsg, txs)
494 | }
495 | ```
496 | 交易队列就这样会发送到矿机上,等待矿机执行交易后,出块上链,未完待续......
497 |
--------------------------------------------------------------------------------
/posts/ethereum_handle_tx_2.md:
--------------------------------------------------------------------------------
1 | # 以太坊交易的处理过程 下篇
2 |
3 | 上篇文章讲述了一笔交易是如何在以太坊节点的本地创建,处理,发出的;今天这篇文章讲述下以太坊的矿机是如何处理接收到的交易的;交易的真正执行其实是在矿机上完成的.
4 | 矿机在eth/handler.go文件中处理接受到的消息
5 | ```
6 | // handleMsg is invoked whenever an inbound message is received from a remote
7 | // peer. The remote connection is torn down upon returning any error.
8 | func (pm *ProtocolManager) handleMsg(p *peer) error {
9 | //这里是读取从远端节点发过来的消息,确保完整接收.
10 | msg, err := p.rw.ReadMsg()
11 | if err != nil {
12 | return err
13 | }
14 | if msg.Size > ProtocolMaxMsgSize { //一次接收最长的msg是10M,超过10M,就返回错误.
15 | return errResp(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
16 | }
17 | defer msg.Discard()
18 |
19 | // Handle the message depending on its contents
20 | switch {
21 | --
22 | --
23 | --
24 | case msg.Code == TxMsg:
25 | //处理接收到的交易数据,保证原子操作
26 | if atomic.LoadUint32(&pm.acceptTxs) == 0 {
27 | break
28 | }
29 | // 解析交易数据,主要是rlp解码,将解码数据存到txs数组中
30 | var txs []*types.Transaction
31 | if err := msg.Decode(&txs); err != nil {
32 | return errResp(ErrDecode, "msg %v: %v", msg, err)
33 | }
34 | for i, tx := range txs {
35 | // Validate and mark the remote transaction
36 | if tx == nil {
37 | return errResp(ErrDecode, "transaction %d is nil", i)
38 | }
39 | p.MarkTransaction(tx.Hash())
40 | }//AddRemotes函数定义在tx_pool.go文件中,处理流程和AddLocal类似(参考上篇文章),唯一的区别是,矿机处理的交易数据大都不是本地账户发出的,这些交易数据在处理过程中不落盘.只有处理本地账户的交易数据才会落盘.经过AddRemotes处理后,矿机tx.pool的pending队列上的交易数据就准备就绪了,等待打包出块.
41 | pm.txpool.AddRemotes(txs)
42 | }
43 |
44 | ```
45 | 在矿机准备组装新的block的时候,会从pending队列中收集交易数据.看下面这段代码,commitNewWork函数的功能是准备下一个区块,在这个函数中完成blocke header,block body的封装;在封装完成前,要执行txpool的pending队列中的每笔交易.
46 |
47 | ```
48 | func (self *worker) commitNewWork() {
49 | ---
50 | ---
51 | ---
52 | //获取txpool的pending队列,其实这个pending是个map的数据结构,是按照accout为key,每个accout的Transactions队列为value的大字典,包含了所有待处理的交易.每个accout的交易队列都是按照nonce值的大小排好序的.
53 | pending, err := self.eth.TxPool().Pending()
54 | if err != nil {
55 | log.Error("Failed to fetch pending transactions", "err", err)
56 | return
57 | }
58 | //NewTransactionsByPriceAndNonce函数创建了一个新的交易集合;新的交易集合实现了一个heap操作,将各个accout的交易队列的第一笔交易,按照price高低存入到了heap中.这个heap是个优先级队列,队列头永远是最小值(有点懵逼是么,等看到func (t *TransactionsByPriceAndNonce) Shift方法的时候就前后贯通了^_^)
59 | txs := types.NewTransactionsByPriceAndNonce(self.current.signer, pending)
60 | //执行这个txs交易集合中的每笔交易,获得每笔交易的状态
61 | work.commitTransactions(self.mux, txs, self.chain, self.coinbase)
62 | ---
63 | ---
64 | ---
65 | //用block header,交易集,交易产生的收据,状态等参数组装出一个新的block.这个block仅仅是组装完成,还没完成最后的Seal操作;
66 | if work.Block, err = self.engine.Finalize(self.chain, header, work.state, work.txs, uncles, work.receipts); err != nil {
67 | log.Error("Failed to finalize block for sealing", "err", err)
68 | return
69 | }
70 | ---
71 | ---
72 | ---
73 |
74 | }
75 |
76 | func NewTransactionsByPriceAndNonce(signer Signer, txs map[common.Address]Transactions) *TransactionsByPriceAndNonce {
77 | //初始化一个切片,len(txs)是account的个数.
78 | heads := make(TxByPrice, 0, len(txs))
79 | for from, accTxs := range txs {
80 | //将各个accout队列中的第一个交易存到heads切片中.
81 | heads = append(heads, accTxs[0])
82 | //调用Sender函数,从交易中解析出发送交易的accout,判断其是否和from一致;
83 | acc, _ := Sender(signer, accTxs[0])
84 | txs[acc] = accTxs[1:]
85 | if from != acc {
86 | delete(txs, from)
87 | }
88 | }
89 | //将heads初始化成一个heap优先级队列,这个队列是用最小完全二叉树实现的.root节点值最小,每个叶子节点的值都大于等于其父节点
90 | heap.Init(&heads)
91 | // Assemble and return the transaction set
92 | return &TransactionsByPriceAndNonce{
93 | txs: txs,
94 | heads: heads,
95 | signer: signer,
96 | }
97 | }
98 | ```
99 |
100 | 讨论下commitTransactions方法做的事情,这个方法主要遍历执行了交易集合中的所有交易
101 | ```
102 | func (env *Work) commitTransactions(mux *event.TypeMux, txs *types.TransactionsByPriceAndNonce, bc *core.BlockChain, coinbase common.Address){
103 | if env.gasPool == nil {
104 | //根据header.GasLimit创建gaspool, GasLimit的值和父块相关,是根据父块消耗的gas值推导计算出来的.
105 | env.gasPool = new(core.GasPool).AddGas(env.header.GasLimit)
106 | }
107 |
108 | var coalescedLogs []*types.Log
109 |
110 | for {
111 | //检查是否有足够的gas,进行下一笔交易的执行,如果gas不足,结束执行交易集合的循环.
112 | if env.gasPool.Gas() < params.TxGas {
113 | log.Trace("Not enough gas for further transactions", "have", env.gasPool, "want", params.TxGas)
114 | break
115 | }
116 | //从heap结构中获取下一笔交易;Peek方法就做了一件事情"return t.heads[0]",永远返回堆中price值最小的那笔交易.
117 | tx := txs.Peek()
118 | if tx == nil {
119 | break
120 | }
121 | // Error may be ignored here. The error has already been checked
122 | // during transaction acceptance is the transaction pool.
123 | //
124 | // We use the eip155 signer regardless of the current hf.
125 | from, _ := types.Sender(env.signer, tx)
126 | // DAO事件发生后,以太坊分裂为ETH和ETC,因为两个链上的东西一摸一样,所以在ETC上面发生的交易可以拿到ETH上面进行重放,反之亦然.所以Vitalik提出了EIP155来避免这种情况.
127 | if tx.Protected() && !env.config.IsEIP155(env.header.Number) {
128 | log.Trace("Ignoring reply protected transaction", "hash", tx.Hash(), "eip155", env.config.EIP155Block)
129 |
130 | txs.Pop()
131 | continue
132 | }
133 | // Start executing the transaction
134 | env.state.Prepare(tx.Hash(), common.Hash{}, env.tcount)
135 | //在此处执行单笔交易,稍后会展开这个函数,这个函数也是嵌套了很深,才真正执行完一笔交易
136 | err, logs := env.commitTransaction(tx, bc, coinbase, env.gasPool)
137 | switch err {
138 | case core.ErrGasLimitReached:
139 | //达到消耗gas的上限,丢弃该账户所有的交易
140 | log.Trace("Gas limit exceeded for current block", "sender", from)
141 | txs.Pop() //pop()弹出了堆栈中最小的值,因为heap中最小值存放的是正在处理的account.pop执行之后,该account从head中被删除了,这样也就不会再处理该account下的其他交易了,详情见"func (t *TransactionsByPriceAndNonce) Shift()"方法.
142 |
143 | case core.ErrNonceTooLow:
144 | //nonce值太低了,放弃当前这笔,处理该account的下一笔交易.
145 | log.Trace("Skipping transaction with low nonce", "sender", from, "nonce", tx.Nonce())
146 | //shift方法主要处理最小完全二叉树的root值,也就是heads[0];heads切片中存储了各个account的交易队列的第一笔交易,这些交易按照price值的大小组成了最小完全二叉树;交易集总是处理heads[0],处理完这笔交易后,将该account交易队列中的下一笔交易,赋值给heads[0],然后再对heap结构进行修正排序,保证heads[0]的值是所有account中最小的.
147 | txs.Shift()
148 |
149 | case core.ErrNonceTooHigh:
150 | //nonce值太高,丢弃该account下的所有交易队列.
151 | log.Trace("Skipping account with hight nonce", "sender", from, "nonce", tx.Nonce())
152 | txs.Pop()
153 |
154 | case nil:
155 | //交易执行正常,收集logs,把当前account交易队列中的下一笔交易移动到heads中
156 | coalescedLogs = append(coalescedLogs, logs...)
157 | env.tcount++ //执行交易总数值加1
158 | txs.Shift()
159 |
160 | default:
161 | // Strange error, discard the transaction and get the next in line (note, the
162 | // nonce-too-high clause will prevent us from executing in vain).
163 | log.Debug("Transaction failed, account skipped", "hash", tx.Hash(), "err", err)
164 | txs.Shift()
165 | }
166 | }
167 |
168 | if len(coalescedLogs) > 0 || env.tcount > 0 {
169 | //复制一份log副本,将副本通知其他模块
170 | cpy := make([]*types.Log, len(coalescedLogs))
171 | for i, l := range coalescedLogs {
172 | cpy[i] = new(types.Log)
173 | *cpy[i] = *l
174 | }
175 | go func(logs []*types.Log, tcount int) {
176 | if len(logs) > 0 {
177 | mux.Post(core.PendingLogsEvent{Logs: logs})
178 | }
179 | if tcount > 0 {
180 | mux.Post(core.PendingStateEvent{})
181 | }
182 | }(cpy, env.tcount)
183 | }
184 | }
185 |
186 | func (env *Work) commitTransaction(tx *types.Transaction, bc *core.BlockChain, coinbase common.Address, gp *core.GasPool) (error, []*types.Log) {
187 | snap := env.state.Snapshot()
188 | //ApplyTransaction才是真正执行一笔交易的函数;这个函数会创建交易/合约执行的EVM环境,预估交易消耗的gas,扣除交易发起方的gas,给矿工分配gas等操作.
189 | receipt, _, err := core.ApplyTransaction(env.config, bc, &coinbase, gp, env.state, env.header, tx, &env.header.GasUsed, vm.Config{})
190 | if err != nil {
191 | env.state.RevertToSnapshot(snap)
192 | return err, nil
193 | }
194 | env.txs = append(env.txs, tx)
195 | env.receipts = append(env.receipts, receipt)
196 |
197 | return nil, receipt.Logs
198 | }
199 | ```
200 | ApplyTransaction 函数虽然不长,但是为了完整的执行一笔交易,做了很多工作,如图所示:
201 | 
202 |
203 | 看下代码
204 | ```
205 | func ApplyTransaction(config *params.ChainConfig, bc ChainContext, author *common.Address, gp *GasPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, usedGas *uint64, cfg vm.Config) (*types.Receipt, uint64, error) {
206 | //将tx包含的信息转换成message结构
207 | msg, err := tx.AsMessage(types.MakeSigner(config, header.Number))
208 | if err != nil {
209 | return nil, 0, err
210 | }
211 | //根据msg,创建一个EVM执行的上下文环境
212 | context := NewEVMContext(msg, header, bc, author)
213 | //创建一个新的EVM,用来执行交易
214 | vmenv := vm.NewEVM(context, statedb, config, cfg)
215 | // ApplyMessage要计算gas,完成交易转账,稍后会对这个函数展开讨论。
216 | _, gas, failed, err := ApplyMessage(vmenv, msg, gp)
217 | if err != nil {
218 | return nil, 0, err
219 | }
220 | // Update the state with pending changes
221 | var root []byte
222 | if config.IsByzantium(header.Number) {
223 | statedb.Finalise(true)
224 | } else {
225 | root = statedb.IntermediateRoot(config.IsEIP158(header.Number)).Bytes()
226 | }
227 | *usedGas += gas
228 |
229 | // 为tx创建一个收据;
230 | receipt := types.NewReceipt(root, failed, *usedGas)
231 | receipt.TxHash = tx.Hash()
232 | receipt.GasUsed = gas
233 | // if the transaction created a contract, store the creation address in the receipt.
234 | if msg.To() == nil {
235 | receipt.ContractAddress = crypto.CreateAddress(vmenv.Context.Origin, tx.Nonce())
236 | }
237 | // 为收据创建log和布隆过滤器;
238 | //布隆过滤器是一种快速的哈希查找算法,它可以判断出某个元素肯定不在集合里或者可能在集合里,即它不会漏报,但可能会误报。这里用布隆过滤器可以快速的从大量的txs中查找指定的tx.
239 | receipt.Logs = statedb.GetLogs(tx.Hash())
240 | receipt.Bloom = types.CreateBloom(types.Receipts{receipt})
241 |
242 | return receipt, gas, err
243 | }
244 | ```
245 | 从上面的流程图可以看出 ApplyMessage函数做了很多事情;它先创建了StateTransition结构,然后执行了这个结构的TransitionDb()方法。
246 | ```
247 | func (st *StateTransition) TransitionDb() (ret []byte, usedGas uint64, failed bool, err error) {
248 | //先在precheck函数检查这笔交易的nonce值是否合理,太大,太小都不可以。
249 | 然后根据tx中,用户输入的gas limit,gas price等参数,预购gas,从from账户中完成扣费,该步骤通过调用buyGas()方法完成。
250 | if err = st.preCheck(); err != nil {
251 | return
252 | }
253 | msg := st.msg
254 | sender := vm.AccountRef(msg.From())
255 | homestead := st.evm.ChainConfig().IsHomestead(st.evm.BlockNumber)
256 | contractCreation := msg.To() == nil
257 |
258 | //计算该笔交易实际需要消耗的gas。IntrinsicGas函数执行流程如下:
259 | 1、判断tx是合约还是普通转账交易;合约交易的gas limit起步价是53000;普通交易起步价21000
260 | 2、计算tx占用的字节长度;统计tx中非零字节的总长度,和零字节的总长度;因为计费标准不一样;非零字节每字节68个gas,零字节每字节4个gas。二者相加计算出消耗的总的gas数。
261 | 3、gas数量 乘以 gas price就是要支付的手续费;如果用户想要快速的把自己的交易发送出去,适当的提高gas price,矿工的tx pool会对price较高的交易优先打包的。这点在上篇中提到过。
262 | gas, err := IntrinsicGas(st.data, contractCreation, homestead)
263 | if err != nil {
264 | return nil, 0, false, err
265 | }
266 | //如果预购的gas小于要消耗的gas,这里返回一个error:"out of gas".
267 | if err = st.useGas(gas); err != nil {
268 | return nil, 0, false, err
269 | }
270 |
271 | var (
272 | evm = st.evm
273 | // vm errors do not effect consensus and are therefor
274 | // not assigned to err, except for insufficient balance
275 | // error.
276 | vmerr error
277 | )
278 | if contractCreation {
279 | ret, _, st.gas, vmerr = evm.Create(sender, st.data, st.gas, st.value)
280 | } else {
281 | //增加from账户的nonce值,为下一笔交易做准备。
282 | st.state.SetNonce(msg.From(), st.state.GetNonce(sender.Address())+1)
283 | //Call()方法在完成转账交易,调用执行了下面2行
284 | // db.SubBalance(sender, amount)
285 | // db.AddBalance(recipient, amount)
286 |
287 | ret, st.gas, vmerr = evm.Call(sender, st.to(), st.data, st.gas, st.value)
288 | }
289 | if vmerr != nil {
290 | log.Debug("VM returned with error", "err", vmerr)
291 | // The only possible consensus-error would be if there wasn't
292 | // sufficient balance to make the transfer happen. The first
293 | // balance transfer may never fail.
294 | if vmerr == vm.ErrInsufficientBalance {
295 | return nil, 0, false, vmerr
296 | }
297 | }
298 | //退税,退税是为了奖励大家运行一些能够减轻区块链负担的指令。
299 | 这里会把用户剩下的gas,以及退税的gas(退税的gas不会超过消耗gas总额的1/2)总和返回给 from账户
300 | st.refundGas()
301 | //给矿工的账户添加gas手续费。
302 | st.state.AddBalance(st.evm.Coinbase, new(big.Int).Mul(new(big.Int).SetUint64(st.gasUsed()), st.gasPrice))
303 |
304 | return ret, st.gasUsed(), vmerr != nil, err
305 | }
306 | ```
307 | 交易到这里就算执行完成了。这里只是阐述了为了执行一笔tx要经过哪些流程,没过多描述EVM的执行细节。所有交易执行完成后会打包上块。区块最终会被矿工广播出去。广播出去的区块,也要经过其他节点的验证,验证无误后才会插入到本地的链上。验证的时候也要调用到ApplyTransaction函数。
308 | 其他节点同步区块的代码调用栈如下,供大家参考:
309 |
310 | ```
311 | pm.syncer()
312 | pm.synchronise(pm.peers.BestPeer())
313 | pm.downloader.Synchronise(peer.id, pHead, pTd, mode)
314 | d.synchronise(id, head, td, mode)
315 | d.syncWithPeer(p, hash, td)
316 | func (d *Downloader) processFastSyncContent(latest *types.Header)
317 | func (d *Downloader) importBlockResults(results []*fetchResult)
318 | d.blockchain.InsertChain(blocks)
319 | func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error)
320 | bc.insertChain(chain)
321 | func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg vm.Config) (types.Receipts, []*types.Log, uint64, error)
322 | ApplyTransaction()
323 | ```
--------------------------------------------------------------------------------
/posts/fomo3d-上线部署要点.md:
--------------------------------------------------------------------------------
1 | # fomo3d-上线部署要点
2 |
3 |
4 | fomo3d游戏一出,国内疯狂clone上线,这里谈下我上线的思路和部署方法(纯手动的^_^,落伍了)
5 |
6 | 通过[原版合约地址](https://etherscan.io/address/0xa62142888aba8370742be823c1782d17a0389da1#code),可以一层一层的拔下所有涉及到的合约代码。
7 |
8 | 目前据我统计共有8个合约,其中有两个闭源合约:
9 |
10 | - F3DexternalSettingsInterface
11 | - JIincInterfaceForForwarder
12 |
13 | 闭源合约不可怕,看明白什么功能,自己hack掉是不影响游戏本身的。
14 |
15 | 提前预警,合约的内容细节还是要自己研究的,没时间写太细,
16 |
17 | 其实这个游戏本身只需要2个合约就可以跑起来,且没实质影响,只是单纯改变了部分利益分配方式。
18 |
19 | 下面说明,我尽可能少改动原版的情况下,部署上线合约,移除p3d修改后的原版合约代码[在这里](https://github.com/ChungkueiBlock/fomo3d/tree/master/sols)
20 |
21 | ## 部署前的准备
22 |
23 | 我一般使用[在线remix](https://remix.ethereum.org/#optimize=true&version=soljson-v0.4.24)工具部署合约在自己的私链上调试,私链建议如下启动(一键解万忧的方式,推荐创世块采用[POA共识](https://github.com/ChungkueiBlock/tools/tree/master/privateEth)-不消耗CPU),这样可以使用remix的debug功能
24 | ```
25 | geth \
26 | --datadir ./node0\
27 | --ws\
28 | --wsaddr 0.0.0.0\
29 | --wsapi "eth,net,web3,admin,personal,txpool,miner,clique,debug"\
30 | --wsport 8546\
31 | --wsorigins "*"\
32 | --rpc\
33 | --rpcapi "eth,net,web3,admin,personal,txpool,miner,clique,debug"\
34 | --rpccorsdomain "*"\
35 | --rpcaddr 0.0.0.0\
36 | --rpcport 8545\
37 | --rpcvhosts "*"\
38 | --mine\
39 | --etherbase 0xdbeb69c655b666b3e17b8061df7ea4cc2399df11\
40 | --unlock 0xdbeb69c655b666b3e17b8061df7ea4cc2399df11\
41 | --password ./password\
42 | --nodiscover\
43 | --maxpeers '50'\
44 | --networkid 378\
45 | --targetgaslimit 471238800\
46 | &
47 | ```
48 |
49 | ## 部署合约
50 |
51 | 按先后顺序如下部署
52 |
53 | 1. [p3d合约](https://github.com/ChungkueiBlock/sols/blob/master/fomo3d/Hourglass.sol)
54 |
55 | 真心不推荐部署带有p3d合约的游戏,这样项目方就可以吃掉本来要流到这里25%左右的流水资金了
56 |
57 | 我对p3d的合约内容还没有很深的研究,只知道它
58 | - 是一个自带“交易所”、发行总量为0的Token,
59 | - 通过Eth买入会自动增发,卖出会销毁
60 | - 买入和卖出都会扣掉10%的费用给仍持有Token的人
61 | - 每买一次都会使Token升值
62 | - 每卖一次会使Token降价
63 |
64 | 这个合约不需要改动,贴源码,编译后部署截图如下,点击红色记录下来部署后的合约地址
65 |
66 | 
67 |
68 | 2. 部署divies合约
69 |
70 | 这个合约专门往p3d持有者发分红的。
71 |
72 | 把刚才记录的p3d合约地址,替换到`HourglassInterface`后面的地址。如上贴源码,编译后部署`Divies`合约,
73 |
74 | 记录下divies的地址,并替换fomo3dlong.sol里的`DiviesInterface`地址
75 |
76 | 3. ~~部署JIincForwarder合约~~
77 |
78 | 这个合约是管理流向社区2%的资金的,被fomo3dlong里调用,
79 | 这里需要hack,因为其中涉及到一个闭源的合约,既然知道它是管理2%资金流向的,那直接在fomo3dLong的合约如下hack
80 |
81 | - 把定义`Jekyll_Island_Inc`的地方,直接定义成一个普通地址 `address reward = 0xxxxxxx;`
82 | - 把调用Jekyll_Island_Inc的地方, 写成`reward.transfer(_com);`, 注意有两个地方调用(都要换),一个是游戏进行时调用,一个是本轮结束后调用
83 |
84 | ```javascript
85 | // // community rewards
86 | // if (!address(Jekyll_Island_Inc).call.value(_com)(bytes4(keccak256("deposit()"))))
87 | // {
88 | // // This ensures Team Just cannot influence the outcome of FoMo3D with
89 | // // bank migrations by breaking outgoing transactions.
90 | // // Something we would never do. But that's not the point.
91 | // // We spent 2000$ in eth re-deploying just to patch this, we hold the
92 | // // highest belief that everything we create should be trustless.
93 | // // Team JUST, The name you shouldn't have to trust.
94 | // _p3d = _p3d.add(_com);
95 | // _com = 0;
96 | // }
97 |
98 | reward.transfer(_com);
99 | ```
100 |
101 | 所以不需要部署这个合约,你只要想办法把流到这里的ETH,流到平台方就可以了。(流到开发者,我觉得也是可以的,哈哈~)
102 |
103 | 4. 部署Team合约
104 |
105 | 这个合约利用多签技术限制了影响团队的操作,需要改的地方就是把这些地址全部换成自己的,
106 |
107 | 把下面这些地址,改成你自己的地址,最好把`deployer`地址写成你用来部署合约的那个地址,后面调用playbook合约的`addGame`需要这里的权限
108 |
109 | ```javascript
110 | address inventor = 0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C;
111 | address mantso = 0x8b4DA1827932D71759687f925D17F81Fc94e3A9D;
112 | address justo = 0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53;
113 | address sumpunk = 0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C;
114 | address deployer = 0xF39e044e1AB204460e06E87c6dca2c6319fC69E3;
115 |
116 | admins_[inventor] = Admin(true, true, "inventor");
117 | admins_[mantso] = Admin(true, true, "mantso");
118 | admins_[justo] = Admin(true, true, "justo");
119 | admins_[sumpunk] = Admin(true, true, "sumpunk");
120 | admins_[deployer] = Admin(true, true, "deployer");
121 | ```
122 |
123 | 改完后,如上贴源码,编译后部署`TeamJust`合约,记录地址,替换playbook合约的`TeamJustInterface`地址
124 |
125 | 5. 部署playerBook合约
126 |
127 | 很有意思的合约,这里就是上面说的整个游戏其实只需要两个合约中的一个。
128 | 不解读细节了,直接改吧
129 |
130 | 你会发现这里怎么还有个`JIincForwarderInterface`地址,第三步不是说不部署这个了么 ?
131 |
132 | 这里的主要是收取别人注册名字开启邀请返佣机制时需要支付的那0.01ETH的
133 |
134 | 知道了这个,就跟第3步一样加个reward收款地址吧,细节不标
135 |
136 | 如上贴源码,编译后部署`PlayBook`合约,记录下地址, 替换fomo3d合约里的`PlayerBookInterface`地址。
137 |
138 |
139 | 6. 部署fomo3dLong合约
140 |
141 | 这个是另一个核心合约之一,这里也有个闭源合约,用来初始化控制时间的参数
142 |
143 | 直接注释掉,然后如下改动
144 |
145 | ```javascript
146 | uint256 private rndExtra_ = 30; // 和rndInit一起控制第一轮游戏开始的初始时间的,单位是秒
147 | uint256 private rndGap_ = 30; // 和rndInit一起控制下轮游戏开始的初始时间的,单位是秒
148 | ```
149 |
150 | 还有两个改动点就是`activate`和`setOtherFomo`里加上自己的deployer地址,
151 |
152 | 额外把setOtherFomo里的往另一个游戏池子里输血的功能改到,因为我们没有其他的游戏,如第三步一样,换个收款码吧
153 |
154 | ```javascript
155 | otherF3D_.transfer(_long);
156 | ```
157 |
158 | 部署吧!!!
159 |
160 | 最后部署这一步,很有可能遇到`errored: oversized data`的错误,刷新remix页面即可。
161 |
162 |
163 | ## 合约设置
164 |
165 | 先setOtherFomo,然后再设置playbook里的addgame,最后activate即可。
166 |
167 |
168 | ## 页面
169 |
170 | 页面直接Ctrl+s下载原版界面,把最后的fomo3dLong的合约地址替换下,另外那个后台API,其实没什么,自己试下就知道了,然后就可以上线了。。。
171 |
172 | 
173 |
174 | # 感受
175 |
176 | - 合约debug难如上青天
177 | - 要替换一大堆合约里的地址,除了Interface类的要替成依赖的合约地址,其他的全可以写成你自己地址(即使都一样的也OK)就可以。
178 |
179 | 目前我们搞出来的定制版有:
180 | - 多级返佣模式, 可自定义级数
181 | - 空投fix版
182 | - 去除战队版
183 | - 移除p3d版本
184 | - 原版
--------------------------------------------------------------------------------
/posts/fomo3d-钱都去哪儿了.md:
--------------------------------------------------------------------------------
1 | # ETH进入fomo3d后都去哪儿了
2 |
3 | fomo3d里有战队系统、邀请分佣机制、持key分红、空投系统、持p3d分红等玩法, 相信通过之前各类媒体的解读都有所了解。
4 |
5 | 下面通过分析合约代码,以讲解ETH数据流向的方式串下所有流程,让大家明明白白的知道自己的ETH都去了哪里。
6 |
7 | 以10ETH充币到fomod3d合约举例,分三种情况
8 |
9 | - 早期用户(游戏刚启动时的激进者)
10 | - 中期用户(为了赚分红、返佣的用户)
11 | - 晚期用户(为了赢48%大奖的人)
12 |
13 | ## 早期
14 | 当合约被激活后,开发者做了一个很“仇富”的举动,每个地址在合约收到100ETH之前,只能购买1ETH的keys,防止被资本大鳄收割本轮后面入场的玩家。这里有个小hack的点,就是提前多准备些小号,多个地址去投,也可以做到比别人便宜多的价格买到keys。
15 |
16 | 这个阶段以买入10ETH举例,你只会买到等同于1ETH价值的keys,其余9个ETH会直接进入你的收益里,
17 | 演示如下:
18 |
19 | 
20 |
21 | 下面是实现此功能的代码
22 |
23 | 
24 |
25 | 代码里的规则(不限阶段)梳理:
26 | - 提款功能可以无限次提,不影响本轮接下来的分红收益,你的收益来自于你持有keys的分红。
27 | - 最低可以支付1e-09个Ether,当购买的Key数量大于或者等于1个时,倒计时会加30秒。
28 | - 当支付的eth不小于0.1时,会送一次“彩票”,买key支付的金额越大,中奖的奖金也越大,最大可中“彩票池”里额度的75%,直译过来这个功能叫空投。
29 |
30 | ## 中期
31 |
32 | 所有阶段的用户如果是直接打开的官网,充币买keys时会触发合约的这个接口,
33 |
34 | 
35 |
36 | 其中_affcode是值邀请人的地址,_team是指用户所有购买key所选的战队,默认的2是指蛇队。
37 |
38 | 如果是从别人的邀请进入的官网,要看邀请人给你发的是哪个链接,有三种形式的链接:
39 |
40 | ,
41 |
42 | 从上到下,分别会走`buyXaddr`、`buyXid`、`buyXname`的接口,比如我给人发了[exitscam.me/xxp](http://exitscam.me/xxp)的邀请链接,被邀的人买keys时会触发如下接口:
43 |
44 | 
45 |
46 | 这其中我个人会收到他买key总额度的10%佣金,这里还有个隐藏的点:
47 |
48 | 如果用户是直接从官网进入买key的,那同样会有10%佣金的产生,只不过是流向p3d的持有者。
49 |
50 |
51 | ## 晚期
52 |
53 | 当有人买key时,都会选择一个战队,默认会被勾选蛇队的,当买到keys数量不小于1个时,会使所选战队成为本轮的潜在获胜队。
54 |
55 | 说了这么多废话,回归正体,你的10ETH到底去了哪里???
56 |
57 | 如果支付10ETH时,选的是蛇队,你10个ETH里的5.6个会被持keys的人均分,1个看情况是给p3d的人还是给邀请你的人,还有1个必定会分给持有p3d的人,另外2个会进入大池子,其中0.2个会分给社区贡献人,0.1个会给TeamJust的另一个游戏合约,还有0.1个会流到“彩票池”里。
58 |
59 | 这里面根据你选的战队不通,分配比例不一样,具体看下的代码,执行这些ETH分配的是走`distributeExternal`,`distributeInternal` 出去的。
60 |
61 | 后面的PotSpit是本轮游戏结束后,如何分配大池子里的金额。
62 |
63 | ```javascript
64 | // Team allocation structures
65 | // 0 = whales
66 | // 1 = bears
67 | // 2 = sneks
68 | // 3 = bulls
69 |
70 | // Team allocation percentages
71 | // (F3D, P3D) + (Pot , Referrals, Community)
72 | // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot.
73 | fees_[0] = F3Ddatasets.TeamFee(30,6); //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
74 | fees_[1] = F3Ddatasets.TeamFee(43,0); //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
75 | fees_[2] = F3Ddatasets.TeamFee(56,10); //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
76 | fees_[3] = F3Ddatasets.TeamFee(43,8); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
77 |
78 | // how to split up the final pot based on which team was picked
79 | // (F3D, P3D)
80 | potSplit_[0] = F3Ddatasets.PotSplit(15,10); //48% to winner, 25% to next round, 2% to com
81 | potSplit_[1] = F3Ddatasets.PotSplit(25,0); //48% to winner, 25% to next round, 2% to com
82 | potSplit_[2] = F3Ddatasets.PotSplit(20,20); //48% to winner, 10% to next round, 2% to com
83 | potSplit_[3] = F3Ddatasets.PotSplit(30,10); //48% to winner, 10% to next round, 2% to com
84 | ```
85 |
86 | 还有很多细节要分享,碍于时间有限,不过我会持续更新这里的
87 |
88 |
89 | ## 感想
90 |
91 | - 持有p3d的人和早期进入的才是最大的受益者
92 | - 后期进入的人只有通过拉人赚佣金的方式回本了
93 | - 这轮游戏应该是结束不了的: 总有人赔了,要拉人进来捞本,被拉的人周而复始。。。
94 | - 结束只有两个可能: 1. 合约有重大漏洞,资金被盗 2. 当大池子里48%的收益足以对整个以太网络发动51%攻击。。。
95 | - 矿工在背后偷着乐
96 | - 你们谁知道TeamJust的下个游戏的合约地址么? 我知道!!!
97 |
98 | 如果你也找到了,可以加我微信`yiyemeishui`, 加好友时请输入TeamJust的下个游戏合约地址,我们一起来票大的。。。
99 |
100 |
--------------------------------------------------------------------------------
/posts/tokenMapping.md:
--------------------------------------------------------------------------------
1 | 谈到token的映射,这是一个在实际当中比较容易遇到的问题,即在以太的ERC20中发放代币,然后待公链上线后,从ERC20的token中把已经发放的代币映射到主网上面。
2 |
3 | 这里一共谈论了两种方法,其实有第三种,具体我们后面在讲。
4 |
5 | 第一种是需要一个可以提供rpc服务访问的full node,然后attach到他的console或者用http or https方法从远端通过网络访问,执行第一个nodejs脚本即可以获取所有关于这个合约的holder地址。
6 |
7 | 优点:可信性高,所有交易记录和地址余额都是从链上直接获取。
8 |
9 | 缺点:速度相对较慢,我在4Core 8G的阿里云上大概1秒钟遍历一个块(实际速度视块的大小及网络带宽而定)
10 |
11 | ```
12 | var Web3 = require("web3");
13 | var fs = require('fs');
14 | var web3 =new Web3();
15 |
16 | var contractAddress = "0x0a25c807291e58716ab78752f8bb15eae8370e7d"; //合约地址
17 | web3.setProvider(new Web3.providers.HttpProvider("http://xxx.xxx.xxx.xxx:xxx"));一个全节点的rpc端口
18 |
19 | var abi=[{"constant":true,"inputs":[],"name":"mintingFinished","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","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,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"plockFlag","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_amount","type":"uint256"}],"name":"mint","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_value","type":"uint256"}],"name":"burn","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_addr","type":"address"}],"name":"removeLock","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"transferEnabled","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_addr","type":"address"}],"name":"setExclude","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_subtractedValue","type":"uint256"}],"name":"decreaseApproval","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"renounceOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"withdrawEther","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"finishMinting","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_addr","type":"address"}],"name":"addLock","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_owners","type":"address[]"},{"name":"_values","type":"uint256[]"}],"name":"allocateTokens","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_enable","type":"bool"}],"name":"enableLockFlag","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_addedValue","type":"uint256"}],"name":"increaseApproval","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_enable","type":"bool"}],"name":"enableTransfer","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"amount","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[],"name":"MintFinished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"previousOwner","type":"address"}],"name":"OwnershipRenounced","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"previousOwner","type":"address"},{"indexed":true,"name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"burner","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Burn","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"}] //合约的abi
20 |
21 | function checkTx(transaction) {
22 | var toRow = new Array();
23 | var inputRow = new Array();
24 | toRow[0] = "to";
25 | inputRow[0] = "input";
26 | transaction = transaction.toString().replace(/("*)/g, "")
27 | var transactionTo = JSON.stringify(web3.eth.getTransaction(transaction), toRow)
28 | var transactionInput = JSON.stringify(web3.eth.getTransaction(transaction), inputRow)
29 | if (transactionTo.search(contractAddress) > 0) {
30 | transfer = transactionInput.substring(10, 43);
31 | account = transactionInput.substring(44, 84);
32 | account = "0x" + account;
33 | balance = metacoin.balanceOf.call(account);
34 | console.log("=======writing TX:" + transactionInput + "write account:" + account + "write balance:" + balance.toNumber())
35 | writeAccountAndBalance(account, balance)
36 | }else{
37 | console.log("SKIP TX:" + "transactionTo:" + transactionTo + "transactionInput:" + transactionInput.substring(0, 100))
38 | }
39 | }
40 |
41 | function writeAccountAndBalance(account, balance) {
42 | fs.writeFileSync(fileName, account + " " + Number(balance) + "\n", { 'flag': 'a' }, function(err) {
43 | if (err) {
44 | throw err;
45 | }
46 | });
47 | }
48 |
49 | function splitTX(transactionInfo) {
50 | if (transactionInfo.search ("0x") < 0 ) {
51 | console.log("there is no any transactoins\n");
52 | return 0;
53 | }
54 | tmpString = transactionInfo.toString().split('[')
55 | tmpString = tmpString[1].toString().split(']')
56 | trancationArray = tmpString[0].toString().split(',')
57 |
58 | return trancationArray
59 | }
60 |
61 | function run (){
62 | var currentBlock = 6038014; //此合约部署的起始区块
63 |
64 | var latestBlock = web3.eth.blockNumber;
65 | console.log("currentBlock:", currentBlock + "lastestBlock" + latestBlock);
66 | var displayRow = new Array();
67 | displayRow[0] = "transactions"
68 |
69 | for (var j = 0; currentBlock < latestBlock; j++) {
70 | console.log("current block:" + currentBlock)
71 | if (transactionArray < 1) continue;
72 | transactionInfo = JSON.stringify(web3.eth.getBlock(currentBlock), displayRow)
73 | var transactionArray = splitTX(transactionInfo)
74 | if (transactionArray < 1) continue;
75 | console.log("\nIn the block:" + currentBlock + ", there are: " + transactionArray.length + " trancations")
76 | for (var k = 0; k < trancationArray.length; k++) {
77 | checkTx(transactionArray[k])
78 | }
79 | currentBlock = Number(currentBlock) + 1
80 | }
81 | }
82 |
83 | var fileName = process.argv[2];
84 | var metacoin = web3.eth.contract(abi).at(contractAddress);
85 | run();
86 | ```
87 | 第二种是利用https://etherscan.io提供的api,提取所有关于这个token的tx,然后根据tx的input参数得到每一笔转账的参数中的to的部分,也就是账户地址,然后运行web3接口跟据账户地址去调用合约里的balanceof 方法最后得到每个账户的余额
88 |
89 | 优点:速度快,4000多个tx大概8分钟左右就可以算出余额
90 |
91 | 缺点:tx来源于第三方,不是直接从链上读数据,可信性值得商榷。
92 |
93 | 下面就是两种方法的具体实现:
94 | ```
95 | var URL = "http://api.etherscan.io/api?module=account&action=txlist&address=0x0a25c807291e58716ab78752f8bb15eae8370e7d&startblock=0&endblock=99999999&sort=asc&apikey=FXHHTPFXJPKAI1IZ35WQZSIJQG4KMIJZZ" //apikey是你在etherscan上的apikey,这个key需要自己去申请,如果发现访问异常,尝试翻墙
96 | //wget "http://api.etherscan.io/api?module=account&action=txlist&address=0x0a25c807291e58716ab78752f8bb15eae8370e7d&startblock=0&endblock=99999999&sort=asc&apikey=FXHHTPFXJPKAIIZ35WQZSIJRXQG4KMIJZZ" -o tx.lst
97 | var request = require("request");
98 | var fs = require('fs');
99 | var prefix = "\"input\"\:\"0xa9059cbb000000000000000000000000"; //合约里的交易方法
100 | var lines = new Array();
101 | var accounts = new Map();
102 |
103 | request.get(URL, function(err, response, body){
104 | console.log(response.body);
105 |
106 | var abi=[{"constant":true,"inputs":[],"name":"mintingFinished","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","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,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"plockFlag","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_amount","type":"uint256"}],"name":"mint","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_value","type":"uint256"}],"name":"burn","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_addr","type":"address"}],"name":"removeLock","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"transferEnabled","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_addr","type":"address"}],"name":"setExclude","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_subtractedValue","type":"uint256"}],"name":"decreaseApproval","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"renounceOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"withdrawEther","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"finishMinting","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_addr","type":"address"}],"name":"addLock","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_owners","type":"address[]"},{"name":"_values","type":"uint256[]"}],"name":"allocateTokens","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_enable","type":"bool"}],"name":"enableLockFlag","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_addedValue","type":"uint256"}],"name":"increaseApproval","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_enable","type":"bool"}],"name":"enableTransfer","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"amount","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[],"name":"MintFinished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"previousOwner","type":"address"}],"name":"OwnershipRenounced","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"previousOwner","type":"address"},{"indexed":true,"name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"burner","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Burn","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"}]
107 | var Web3 = require("web3");
108 | var web3 =new Web3();
109 | var contractAddress = "0x0a25c807291e58716ab78752f8bb15eae8370e7d"; //合约地址
110 | web3.setProvider(new Web3.providers.HttpProvider("http://xxx.xxx.xxx:xxx"));
111 |
112 | var metacoin = web3.eth.contract(abi).at(contractAddress);
113 |
114 | lines = response.body.split(",");
115 |
116 | for(var n = 0; n < lines.length; n++) {
117 |
118 | if (lines[n].search(prefix) > -1){
119 | account = lines[n].substr(prefix.length, 40);
120 | accounts.set(account, "00");
121 | }
122 | }
123 | for (var key of accounts.keys()) {
124 | var balance = metacoin.balanceOf.call("0x" + key);
125 | console.log(key + ":" + balance.toNumber());
126 | fs.writeFileSync("account.lst", key + ":" + Number(balance) + "\n", { 'flag': 'a' }, function(err) {
127 | if (err) {
128 | throw err;
129 | }
130 | });
131 |
132 | }
133 | });
134 | ```
135 |
--------------------------------------------------------------------------------
/posts/why_choose_rn.md:
--------------------------------------------------------------------------------
1 | # ecoinWallet为什么使用React-Native开发
2 | 首先,这不是一篇严肃的技术讨论,只说明了我们团队为何选择React-Native.
3 | 目前市场上Native的开发已经非常成熟,开发一款类似ecoinWallet的应用并不复杂.但是会写Native并且懂得区块链知识的开发人员稀缺.我们将围绕APP开发和区块链开发两部分来论述.
4 |
5 | ### APP开发
6 | React-Native的优缺点:
7 | - 优点:
8 | - React-Native使用js发开, 门槛低
9 | - React-Native调试非常快速(增量编译), 开发体验更好
10 | - 对发布的应用支持code-push热更新(苹果/谷歌都支持code-push,具体规则看官方说明)
11 | - React-Native跨平台(一份代码同时在android/ios上运行)
12 | - React-Native的UI是native的(js代码会通过JsBridge转成native的代码), 界面流畅度和原生一致
13 |
14 | - 缺点:
15 | - React-Native当前仍然是beta版
16 | - 一些增强功能,定制功能需要native开发人员特别编写React-Native扩展供js调用
17 | - 在一个APP中同时存在native和React-Native是及其艰巨的任务(可以看看Airbnb的[React Native at Airbnb](https://medium.com/airbnb-engineering/react-native-at-airbnb-f95aa460be1c))
18 | - native开发人员通常不认同js语言, 让他们重新学习React-Native不容易
19 |
20 | ### 区块链开发
21 | - 使用React-Native开发ethereum library
22 | 在区块链领域, NodeJS的生态非常完善. 而React-Native是运行在JavascriptCore上, 一部分代码近乎可以直接运行.同时也因为JavascriptCore缺少Node扩展如:Buffer/Crypto等, 需要使用native编写的第三方代码来扩展React-Native.好在这部分代码在社区都有实现.
23 |
24 | - 使用native开发ethereum library
25 | native开发区块链library,需要同时在android/ios上保持两条分支独自开发(需要的人手比React-Native多了不少);同时native开发区块链能借鉴的项目目前并不多,要实现诸如abi encode/decode, RLP encode/decode, offline sign transaction并保证代码质量绝非易事.
26 |
27 | ### ecoinWallet的选择
28 | ecoinWallet团队成员有丰富的Golang开发经验, 对[ethereum/go-ethereum](https://github.com/ethereum/go-ethereum)较熟悉.
29 | 同时,团队在NodeJS上也有较多经验, 移植NodeJS代码到React-Native也还算顺利.
30 | 最关键的是,团队成员不多,我们觉得对于一个从0到1的过程, 还是更应该追求开发效率.在今后React-Native不能满足我们的业务需求时,再使用native重写.
31 |
--------------------------------------------------------------------------------
/temp/enb.sol:
--------------------------------------------------------------------------------
1 | pragma solidity ^0.4.24;
2 |
3 | /**xxp 校验防止溢出情况
4 | * @title SafeMath
5 | * @dev Math operations with safety checks that throw on error
6 | */
7 | library SafeMath {
8 |
9 | /**
10 | * @dev Multiplies two numbers, throws on overflow.
11 | */
12 | function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
13 | // Gas optimization: this is cheaper than asserting 'a' not being zero, but the
14 | // benefit is lost if 'b' is also tested.
15 | // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
16 | if (a == 0) {
17 | return 0;
18 | }
19 |
20 | c = a * b;
21 | assert(c / a == b);
22 | return c;
23 | }
24 |
25 | /**
26 | * @dev Integer division of two numbers, truncating the quotient.
27 | */
28 | function div(uint256 a, uint256 b) internal pure returns (uint256) {
29 | // assert(b > 0); // Solidity automatically throws when dividing by 0
30 | // uint256 c = a / b;
31 | // assert(a == b * c + a % b); // There is no case in which this doesn't hold
32 | return a / b;
33 | }
34 |
35 | /**
36 | * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
37 | */
38 | function sub(uint256 a, uint256 b) internal pure returns (uint256) {
39 | assert(b <= a);
40 | return a - b;
41 | }
42 |
43 | /**
44 | * @dev Adds two numbers, throws on overflow.
45 | */
46 | function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
47 | c = a + b;
48 | assert(c >= a);
49 | return c;
50 | }
51 | }
52 |
53 | /**
54 | * @title ERC20Basic
55 | * @dev Simpler version of ERC20 interface
56 | * See https://github.com/ethereum/EIPs/issues/179
57 | */
58 | contract ERC20Basic {
59 | function totalSupply() public view returns (uint256);
60 | function balanceOf(address who) public view returns (uint256);
61 | function transfer(address to, uint256 value) public returns (bool);
62 | event Transfer(address indexed from, address indexed to, uint256 value);
63 |
64 | function allowance(address owner, address spender) public view returns (uint256);
65 | function transferFrom(address from, address to, uint256 value) public returns (bool);
66 | function approve(address spender, uint256 value) public returns (bool);
67 | event Approval(address indexed owner, address indexed spender, uint256 value);
68 | }
69 |
70 | /**
71 | * @title Ownable
72 | * @dev The Ownable contract has an owner address, and provides basic authorization control
73 | * functions, this simplifies the implementation of "user permissions".
74 | */
75 | contract Ownable {
76 | address public owner;
77 |
78 |
79 | event OwnershipRenounced(address indexed previousOwner);
80 | event OwnershipTransferred(
81 | address indexed previousOwner,
82 | address indexed newOwner
83 | );
84 |
85 |
86 | /**
87 | * @dev The Ownable constructor sets the original `owner` of the contract to the sender
88 | * account.
89 | */
90 | constructor() public {
91 | owner = msg.sender;
92 | }
93 |
94 | /**
95 | * @dev Throws if called by any account other than the owner.
96 | */
97 | modifier onlyOwner() {
98 | require(msg.sender == owner);
99 | _;
100 | }
101 |
102 | /**
103 | * @dev Allows the current owner to relinquish control of the contract.
104 | * @notice Renouncing to ownership will leave the contract without an owner.
105 | * It will not be possible to call the functions with the `onlyOwner`
106 | * modifier anymore.
107 | */
108 | function renounceOwnership() public onlyOwner {
109 | emit OwnershipRenounced(owner);
110 | owner = address(0);
111 | }
112 |
113 | /**
114 | * @dev Allows the current owner to transfer control of the contract to a newOwner.
115 | * @param _newOwner The address to transfer ownership to.
116 | */
117 | function transferOwnership(address _newOwner) public onlyOwner {
118 | _transferOwnership(_newOwner);
119 | }
120 |
121 | /**
122 | * @dev Transfers control of the contract to a newOwner.
123 | * @param _newOwner The address to transfer ownership to.
124 | */
125 | function _transferOwnership(address _newOwner) internal {
126 | require(_newOwner != address(0));
127 | emit OwnershipTransferred(owner, _newOwner);
128 | owner = _newOwner;
129 | }
130 | }
131 |
132 | /**
133 | * @title Standard ERC20 token
134 | *
135 | * @dev Implementation of the basic standard token.
136 | * @dev https://github.com/ethereum/EIPs/issues/20
137 | * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
138 | */
139 | contract StandardToken is ERC20Basic {
140 |
141 | using SafeMath for uint256;
142 |
143 | mapping(address => uint256) balances;
144 |
145 | uint256 totalSupply_;
146 |
147 | /**
148 | * @dev Total number of tokens in existence
149 | */
150 | function totalSupply() public view returns (uint256) {
151 | return totalSupply_;
152 | }
153 |
154 | /**
155 | * @dev Transfer token for a specified address
156 | * @param _to The address to transfer to.
157 | * @param _value The amount to be transferred.
158 | */
159 | function transfer(address _to, uint256 _value) public returns (bool) {
160 | require(_value <= balances[msg.sender]);
161 | require(_to != address(0));
162 |
163 | balances[msg.sender] = balances[msg.sender].sub(_value);
164 | balances[_to] = balances[_to].add(_value);
165 | emit Transfer(msg.sender, _to, _value);
166 | return true;
167 | }
168 |
169 | /**
170 | * @dev Gets the balance of the specified address.
171 | * @param _owner The address to query the the balance of.
172 | * @return An uint256 representing the amount owned by the passed address.
173 | */
174 | function balanceOf(address _owner) public view returns (uint256) {
175 | return balances[_owner];
176 | }
177 |
178 | mapping (address => mapping (address => uint256)) internal allowed;
179 |
180 |
181 | /**
182 | * @dev Transfer tokens from one address to another
183 | * @param _from address The address which you want to send tokens from
184 | * @param _to address The address which you want to transfer to
185 | * @param _value uint256 the amount of tokens to be transferred
186 | */
187 | function transferFrom(
188 | address _from,
189 | address _to,
190 | uint256 _value
191 | )
192 | public
193 | returns (bool)
194 | {
195 | require(_value <= balances[_from]);
196 | require(_value <= allowed[_from][msg.sender]);
197 | require(_to != address(0));
198 |
199 | balances[_from] = balances[_from].sub(_value);
200 | balances[_to] = balances[_to].add(_value);
201 | allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
202 | emit Transfer(_from, _to, _value);
203 | return true;
204 | }
205 |
206 | /**
207 | * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
208 | * Beware that changing an allowance with this method brings the risk that someone may use both the old
209 | * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
210 | * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
211 | * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
212 | * @param _spender The address which will spend the funds.
213 | * @param _value The amount of tokens to be spent.
214 | */
215 | function approve(address _spender, uint256 _value) public returns (bool) {
216 | allowed[msg.sender][_spender] = _value;
217 | emit Approval(msg.sender, _spender, _value);
218 | return true;
219 | }
220 |
221 | /**
222 | * @dev Function to check the amount of tokens that an owner allowed to a spender.
223 | * @param _owner address The address which owns the funds.
224 | * @param _spender address The address which will spend the funds.
225 | * @return A uint256 specifying the amount of tokens still available for the spender.
226 | */
227 | function allowance(
228 | address _owner,
229 | address _spender
230 | )
231 | public
232 | view
233 | returns (uint256)
234 | {
235 | return allowed[_owner][_spender];
236 | }
237 |
238 | /**
239 | * @dev Increase the amount of tokens that an owner allowed to a spender.
240 | * approve should be called when allowed[_spender] == 0. To increment
241 | * allowed value is better to use this function to avoid 2 calls (and wait until
242 | * the first transaction is mined)
243 | * From MonolithDAO Token.sol
244 | * @param _spender The address which will spend the funds.
245 | * @param _addedValue The amount of tokens to increase the allowance by.
246 | */
247 | function increaseApproval(
248 | address _spender,
249 | uint256 _addedValue
250 | )
251 | public
252 | returns (bool)
253 | {
254 | allowed[msg.sender][_spender] = (
255 | allowed[msg.sender][_spender].add(_addedValue));
256 | emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
257 | return true;
258 | }
259 |
260 | /**
261 | * @dev Decrease the amount of tokens that an owner allowed to a spender.
262 | * approve should be called when allowed[_spender] == 0. To decrement
263 | * allowed value is better to use this function to avoid 2 calls (and wait until
264 | * the first transaction is mined)
265 | * From MonolithDAO Token.sol
266 | * @param _spender The address which will spend the funds.
267 | * @param _subtractedValue The amount of tokens to decrease the allowance by.
268 | */
269 | function decreaseApproval(
270 | address _spender,
271 | uint256 _subtractedValue
272 | )
273 | public
274 | returns (bool)
275 | {
276 | uint256 oldValue = allowed[msg.sender][_spender];
277 | if (_subtractedValue >= oldValue) {
278 | allowed[msg.sender][_spender] = 0;
279 | } else {
280 | allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
281 | }
282 | emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
283 | return true;
284 | }
285 | }
286 |
287 | /**
288 | * @title Burnable Token
289 | * @dev Token that can be irreversibly burned (destroyed).
290 | */
291 | contract BurnableToken is StandardToken {
292 |
293 | event Burn(address indexed burner, uint256 value);
294 |
295 | /**
296 | * @dev Burns a specific amount of tokens.
297 | * @param _value The amount of token to be burned.
298 | */
299 | function burn(uint256 _value) public {
300 | _burn(msg.sender, _value);
301 | }
302 |
303 | function _burn(address _who, uint256 _value) internal {
304 | require(_value <= balances[_who]);
305 | // no need to require value <= totalSupply, since that would imply the
306 | // sender's balance is greater than the totalSupply, which *should* be an assertion failure
307 |
308 | balances[_who] = balances[_who].sub(_value);
309 | totalSupply_ = totalSupply_.sub(_value);
310 | emit Burn(_who, _value);
311 | emit Transfer(_who, address(0), _value);
312 | }
313 | }
314 |
315 | /**
316 | * @title Mintable token
317 | * @dev Simple ERC20 Token example, with mintable token creation
318 | * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
319 | */
320 | contract MintableToken is StandardToken, Ownable {
321 | event Mint(address indexed to, uint256 amount);
322 | event MintFinished();
323 |
324 | bool public mintingFinished = false;
325 |
326 |
327 | modifier canMint() {
328 | require(!mintingFinished);
329 | _;
330 | }
331 |
332 | modifier hasMintPermission() {
333 | require(msg.sender == owner);
334 | _;
335 | }
336 |
337 | /**
338 | * @dev Function to mint tokens
339 | * @param _to The address that will receive the minted tokens.
340 | * @param _amount The amount of tokens to mint.
341 | * @return A boolean that indicates if the operation was successful.
342 | */
343 | function mint(
344 | address _to,
345 | uint256 _amount
346 | )
347 | hasMintPermission
348 | canMint
349 | public
350 | returns (bool)
351 | {
352 | totalSupply_ = totalSupply_.add(_amount);
353 | balances[_to] = balances[_to].add(_amount);
354 | emit Mint(_to, _amount);
355 | emit Transfer(address(0), _to, _amount);
356 | return true;
357 | }
358 |
359 | /**
360 | * @dev Function to stop minting new tokens.
361 | * @return True if the operation was successful.
362 | */
363 | function finishMinting() onlyOwner canMint public returns (bool) {
364 | mintingFinished = true;
365 | emit MintFinished();
366 | return true;
367 | }
368 | }
369 |
370 | contract Controlled is Ownable{
371 |
372 | constructor() public {
373 | setExclude(msg.sender);
374 | }
375 |
376 | // Flag that determines if the token is transferable or not.
377 | bool public transferEnabled = false;
378 |
379 | // flag that makes locked address effect
380 | bool public plockFlag=true;
381 | mapping(address => bool) locked;
382 | mapping(address => bool) exclude;
383 |
384 | // 控制全局全局锁
385 | function enableTransfer(bool _enable) public onlyOwner{
386 | transferEnabled = _enable;
387 | }
388 |
389 | // 控制个人锁功能
390 | function enableLockFlag(bool _enable) public onlyOwner returns (bool success){
391 | plockFlag = _enable;
392 | return true;
393 | }
394 |
395 | function addLock(address _addr) public onlyOwner returns (bool success){
396 | require(_addr!=msg.sender);
397 | locked[_addr] = true;
398 | return true;
399 | }
400 |
401 | function setExclude(address _addr) public onlyOwner returns (bool success){
402 | exclude[_addr] = true;
403 | return true;
404 | }
405 |
406 | function removeLock(address _addr) public onlyOwner returns (bool success){
407 | locked[_addr] = false;
408 | return true;
409 | }
410 |
411 | modifier transferAllowed(address _addr) {
412 | if (!exclude[_addr]) {
413 | // flase抛异常,并扣除gas消耗
414 | assert(transferEnabled);
415 | if(plockFlag){
416 | assert(!locked[_addr]);
417 | }
418 | }
419 |
420 | _;
421 | }
422 |
423 | }
424 |
425 | /**
426 | * @title Pausable token
427 | *
428 | * @dev StandardToken modified with pausable transfers.
429 | **/
430 |
431 | contract PausableToken is StandardToken, Controlled {
432 |
433 | function transfer(address _to, uint256 _value) public transferAllowed(msg.sender) returns (bool) {
434 | return super.transfer(_to, _value);
435 | }
436 |
437 | function transferFrom(address _from, address _to, uint256 _value) public transferAllowed(msg.sender) returns (bool) {
438 | return super.transferFrom(_from, _to, _value);
439 | }
440 |
441 | function approve(address _spender, uint256 _value) public transferAllowed(msg.sender) returns (bool) {
442 | return super.approve(_spender, _value);
443 | }
444 | }
445 |
446 | /*
447 | * @title ENBToken
448 | */
449 | contract ENBToken is BurnableToken, MintableToken, PausableToken {
450 | // Public variables of the token
451 | string public name;
452 | string public symbol;
453 | // decimals is the strongly suggested default, avoid changing it
454 | uint8 public decimals;
455 |
456 | constructor() public {
457 | name = "Energy Block";
458 | symbol = "ENBi";
459 | decimals = 18;
460 | totalSupply_ = 1000000000 * 10 ** uint256(decimals);
461 |
462 | // Allocate initial balance to the owner
463 | balances[msg.sender] = totalSupply_;
464 | }
465 |
466 | // transfer balance to owner
467 | function withdrawEther() onlyOwner public {
468 | address addr = this;
469 | owner.transfer(addr.balance);
470 | }
471 |
472 | // can accept ether
473 | function() payable public { }
474 |
475 | // Allocate tokens to the users
476 | // @param _owners The owners list of the token
477 | // @param _values The value list of the token
478 | function allocateTokens(address[] _owners, uint256[] _values) public onlyOwner {
479 |
480 | require(_owners.length == _values.length, "data length mismatch");
481 | address from = msg.sender;
482 |
483 | for(uint256 i = 0; i < _owners.length ; i++){
484 | address to = _owners[i];
485 | uint256 value = _values[i];
486 | require(value <= balances[from]);
487 |
488 | balances[to] = balances[to].add(value);
489 | balances[from] = balances[from].sub(value);
490 | emit Transfer(from, to, value);
491 | }
492 | }
493 | }
--------------------------------------------------------------------------------