├── .gitignore
├── LICENSE
├── README.md
├── requirements.txt
├── setup.py
└── virtualchain
├── __init__.py
├── impl_ref
├── __init__.py
└── reference.py
├── lib
├── __init__.py
├── blockchain
│ ├── __init__.py
│ ├── address.py
│ ├── bitcoin_blockchain
│ │ ├── __init__.py
│ │ ├── authproxy.py
│ │ ├── bech32.py
│ │ ├── bits.py
│ │ ├── blocks.py
│ │ ├── fees.py
│ │ ├── keys.py
│ │ ├── multisig.py
│ │ ├── opcodes.py
│ │ └── spv.py
│ ├── keys.py
│ ├── scripts.py
│ ├── session.py
│ └── transactions.py
├── config.py
├── ecdsalib.py
├── encoding.py
├── hashing.py
├── indexer.py
└── merkle.py
├── version.py
└── virtualchain.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 |
5 | # C extensions
6 | *.so
7 |
8 | # Distribution / packaging
9 | .Python
10 | env/
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib64/
18 | parts/
19 | sdist/
20 | var/
21 | *.egg-info/
22 | .installed.cfg
23 | *.egg
24 |
25 | # PyInstaller
26 | # Usually these files are written by a python script from a template
27 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
28 | *.manifest
29 | *.spec
30 |
31 | # Installer logs
32 | pip-log.txt
33 | pip-delete-this-directory.txt
34 |
35 | # Unit test / coverage reports
36 | htmlcov/
37 | .tox/
38 | .coverage
39 | .coverage.*
40 | .cache
41 | nosetests.xml
42 | coverage.xml
43 | *,cover
44 |
45 | # Translations
46 | *.mo
47 | *.pot
48 |
49 | # Django stuff:
50 | *.log
51 |
52 | # Sphinx documentation
53 | docs/_build/
54 |
55 | # PyBuilder
56 | target/
57 |
58 | # vim
59 | *.swp
60 |
--------------------------------------------------------------------------------
/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 | # Virtualchain
2 |
3 | Virtualchain is a on-chain protocol, where additional data can be embedded on an existing blockchain like Bitcoin to construct a virtual blockchain with new features. Virtualchain can add new functionality to Bitcoin without modifying the Bitcoin protocol.
4 |
5 | This repository has a virtualchain implementation in Python 2.7 for processing and maintaining virtual blockchains. You can read more about the design and implementation of virtualchain in our [DCCL 2016 paper](https://www.zurich.ibm.com/dccl/papers/nelson_dccl.pdf).
6 |
7 | ## What is a virtual blockchain?
8 |
9 | A *virtual blockchain* is a layer that sits on top of a blockchain that introduces new functionality and operations without requiring changes to the underlying blockchain. The nodes of the underlying blockchain network are not aware of the presence of virtual blockchains. New operations are defined in the virtual blockchain layer and are encoded in the metadata of valid blockchain transactions. Blockchain nodes do see the raw transactions, but the logic for processing the virtual blockchain operations only exists at the virtual blockchain level.
10 |
11 | The rules for accepting or rejecting virtual blockchain operations are also defined in the Virtualchain library. Accepted operations are processed by Virtualchain to construct a database that stores information on the global state of the system along with state changes at any given blockchain block. The resulting Virtualchain processes obtain a [fork\*-consistent](http://www.scs.stanford.edu/~jinyuan/bft2f.pdf) view of the database.
12 |
13 | In a sense, a virtual blockchain is a state machine on top of an underlying blockchain, and the Virtualchain library can be used to build a variety of state machines. One such example can be seen in the .id namespace on Bitcoin through Blockstack, which defined a global naming system as a virtual blockchain state machine. You can use this library to create any type of state machine that you can think of.
14 |
15 | One way to think of these state machines is as standalone smart contracts. When defining state machines with the Virtualchain library, programmers have the flexibility and boundless potential at their fingertips that they do when working with a Turing complete smart contract system, and at the same time, once a state machine is defined and operational, developers have the benefits of working with a specialized and operationally-efficient environment.
16 |
17 | ## How scalable is virtualchain?
18 |
19 | The scalability of virtualchain really depends on the scalability of the underlying blockchain. In our implementation on Bitcoin, every virtualchain transaction is a Bitcoin transaction. In 2017, we saw that Bitcoin transaction fees went up to $40-$50 even for low-value virtualchain transactions. Also, embedding a lot of additional data directly in the Bitcoin blockchain is not scalable in general. Lessons from the virtualchain work led to the design of the [Stacks programming layer](https://github.com/stacks-network/stacks), which maintains a separate ledger from Bitcoin and only stores hashes of data at the Bitcoin layer. An additional benefit of using a separate ledger with Stacks is that fully-expressive smart contracts can be introduced (Stacks implemented the [Clarity language](https://clarity-lang.org/) for smart contracts).
20 |
21 | ## Installation
22 |
23 | This package provides the `virtualchain` Python package. To install from
24 | source, do the following:
25 |
26 | ```
27 | $ git clone https://github.com/stacks-network/virtualchain
28 | $ cd virtualchain
29 | $ python2 ./setup.py build
30 | $ sudo python2 ./setup.py install
31 | ```
32 |
33 | This package is also available via `pip`. Be sure that your `pip` is configured
34 | to install packages for Python 2.7.x.
35 |
36 | ```
37 | $ pip install virtualchain
38 | ```
39 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | commontools==0.1.0
2 | ecdsa==0.13
3 | bitcoin==1.1.39
4 | python-bitcoinrpc==0.1
5 | requests==2.20.0
6 | utilitybelt==0.2.6
7 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | """
4 | Virtualchain
5 | ~~~~~
6 | copyright: (c) 2014-15 by Halfmoon Labs, Inc.
7 | copyright: (c) 2016 by Blockstack.org
8 |
9 | This file is part of Virtualchain
10 |
11 | Virtualchain is free software: you can redistribute it and/or modify
12 | it under the terms of the GNU General Public License as published by
13 | the Free Software Foundation, either version 3 of the License, or
14 | (at your option) any later version.
15 |
16 | Virtualchain is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | GNU General Public License for more details.
20 | You should have received a copy of the GNU General Public License
21 | along with Virtualchain. If not, see .
22 | """
23 |
24 | from setuptools import setup, find_packages
25 |
26 | # to set __version__
27 | exec(open('virtualchain/version.py').read())
28 |
29 | setup(
30 | name='virtualchain',
31 | version=__version__,
32 | url='https://github.com/blockstack/virtualchain',
33 | license='GPLv3',
34 | author='Blockstack.org',
35 | author_email='support@blockstack.org',
36 | description='A library for constructing virtual blockchains within a cryptocurrency\'s blockchain',
37 | keywords='blockchain bitcoin btc cryptocurrency data',
38 | packages=find_packages(),
39 | download_url='https://github.com/blockstack/virtualchain/archive/master.zip',
40 | zip_safe=False,
41 | include_package_data=True,
42 | install_requires=[
43 | 'protocoin>=0.2',
44 | 'simplejson>=3.8.2',
45 | 'jsonschema>=2.5.1, <=2.99',
46 | 'cryptography>=1.9',
47 | 'ecdsa>=0.13',
48 | 'six>=1.10.0',
49 | 'keylib>=0.1.1',
50 | 'requests>=2.20',
51 | ],
52 | classifiers=[
53 | 'Intended Audience :: Developers',
54 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
55 | 'Operating System :: OS Independent',
56 | 'Programming Language :: Python',
57 | 'Topic :: Internet',
58 | 'Topic :: Security :: Cryptography',
59 | 'Topic :: Software Development :: Libraries :: Python Modules',
60 | ],
61 | )
62 |
--------------------------------------------------------------------------------
/virtualchain/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | """
4 | Virtualchain
5 | ~~~~~
6 | copyright: (c) 2014 by Halfmoon Labs, Inc.
7 | copyright: (c) 2015 by Blockstack.org
8 |
9 | This file is part of Virtualchain
10 |
11 | Virtualchain is free software: you can redistribute it and/or modify
12 | it under the terms of the GNU General Public License as published by
13 | the Free Software Foundation, either version 3 of the License, or
14 | (at your option) any later version.
15 |
16 | Virtualchain is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | GNU General Public License for more details.
20 | You should have received a copy of the GNU General Public License
21 | along with Virtualchain. If not, see .
22 | """
23 | from virtualchain import sync_virtualchain, virtualchain_set_opfields, connect_bitcoind
24 |
25 | from .lib import *
26 | from .version import __version__
27 |
--------------------------------------------------------------------------------
/virtualchain/impl_ref/__init__.py:
--------------------------------------------------------------------------------
1 | # required callbacks
2 | from .reference import get_virtual_chain_name, get_virtual_chain_version, get_first_block_id, get_db_state, db_parse, db_check, db_commit, db_save, db_serialize
3 |
4 | # optional
5 | try:
6 | from .reference import get_op_processing_order
7 | except:
8 | def get_op_processing_order():
9 | return None
10 |
--------------------------------------------------------------------------------
/virtualchain/impl_ref/reference.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | """
4 | Virtualchain
5 | ~~~~~
6 | copyright: (c) 2014 by Halfmoon Labs, Inc.
7 | copyright: (c) 2015 by Blockstack.org
8 |
9 | This file is part of Virtualchain
10 |
11 | Virtualchain is free software: you can redistribute it and/or modify
12 | it under the terms of the GNU General Public License as published by
13 | the Free Software Foundation, either version 3 of the License, or
14 | (at your option) any later version.
15 |
16 | Virtualchain is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | GNU General Public License for more details.
20 | You should have received a copy of the GNU General Public License
21 | along with Virtualchain. If not, see .
22 | """
23 |
24 |
25 | # example plugin to a virtual chain that defines its behavior.
26 |
27 | def get_virtual_chain_name():
28 | """
29 | Get the name of the virtual chain we're building.
30 | """
31 | print "\nreference implementation of get_virtual_chain_name\n"
32 | return "virtualchain-test"
33 |
34 |
35 | def get_virtual_chain_version():
36 | """
37 | Get the version string for this virtual chain.
38 | """
39 | print "\nreference implementation of get_virtual_chain_version\n"
40 | return "v0.01-beta"
41 |
42 |
43 | def get_first_block_id():
44 | """
45 | Get the id of the first block to start indexing.
46 | """
47 | print "\nreference implementation of get_first_block_id\n"
48 | return 50000
49 |
50 |
51 | def get_db_state():
52 | """
53 | Return an opaque 'state' object that will be preserved across calls
54 | to the blockchain indexing callbacks.
55 | """
56 | print "\nreference implementation of get_db_state\n"
57 | return None
58 |
59 |
60 | def get_opcodes():
61 | """
62 | Return the set of opcodes we're looking for.
63 | """
64 | print "\nreference implementation of get_opcodes\n"
65 | return ["a", "b", "c", "d", "e"]
66 |
67 |
68 | def get_magic_bytes():
69 | """
70 | Return the magic byte sequence we're scanning OP_RETURNs for.
71 | """
72 | print "\nreference implementation of get_magic_bytes\n"
73 | return "vv"
74 |
75 |
76 | def db_parse( block_id, opcode, op_payload, senders, inputs, outputs, fee, db_state=None ):
77 | """
78 | Given the block ID, and information from what looks like
79 | an OP_RETURN transaction that is part of the virtual chain, parse the
80 | transaction's OP_RETURN nulldata into a dict.
81 |
82 | Return the dict if this is a valid op.
83 | Return None if not.
84 |
85 | NOTE: the virtual chain indexer reserves all keys that start with 'virtualchain_'
86 | """
87 | print "\nreference implementation of db_parse\n"
88 | return None
89 |
90 |
91 | def db_scan_block( block_id, op_list, db_state=None ):
92 | """
93 | Given the block ID and a tx-ordered list of operations, do any
94 | block-level initial preprocessing. This method does not
95 | affect the operations (the op_list will be discarded), nor
96 | does it return anything. It is only meant to give the state
97 | engine implementation information on what is to come in the
98 | sequence of db_check() calls.
99 | """
100 | print "\nreference implementation of db_check_block\n"
101 | return
102 |
103 |
104 | def db_check( block_id, opcode, op, txid, vtxindex, checked, db_state=None ):
105 | """
106 | Given the block ID and a parsed operation, check to see if this is a *valid* operation
107 | for the purposes of this virtual chain's database.
108 |
109 | Return True if so; False if not.
110 | """
111 | print "\nreference implementation of db_check\n"
112 | return False
113 |
114 |
115 | def db_commit( block_id, opcode, op, txid, vtxindex, db_state=None ):
116 | """
117 | Given a block ID and checked opcode, record it as
118 | part of the database. This does *not* need to write
119 | the data to persistent storage, since save() will be
120 | called once per block processed.
121 |
122 | This method must return either the updated op with the
123 | data to pass on to db_serialize, or False if the op
124 | is to be rejected.
125 | """
126 | print "\nreference implementation of db_commit\n"
127 | return False
128 |
129 |
130 | def db_save( block_id, filename, db_state=None ):
131 | """
132 | Save all persistent state to stable storage.
133 |
134 | Return True on success
135 | Return False on failure.
136 | """
137 | print "\nreference implementation of db_save\n"
138 | return True
139 |
140 |
141 | def db_continue( block_id, consensus_hash ):
142 | """
143 | Signal to the implementation that all state for this block
144 | has been saved, and that this is now the new consensus hash.
145 |
146 | Return value indicates whether or not we should continue indexing.
147 | """
148 | print "\nreference implementation of db_continue\n"
149 | return True
150 |
--------------------------------------------------------------------------------
/virtualchain/lib/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | """
4 | Virtualchain
5 | ~~~~~
6 | copyright: (c) 2014 by Halfmoon Labs, Inc.
7 | copyright: (c) 2015 by Blockstack.org
8 |
9 | This file is part of Virtualchain
10 |
11 | Virtualchain is free software: you can redistribute it and/or modify
12 | it under the terms of the GNU General Public License as published by
13 | the Free Software Foundation, either version 3 of the License, or
14 | (at your option) any later version.
15 |
16 | Virtualchain is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | GNU General Public License for more details.
20 | You should have received a copy of the GNU General Public License
21 | along with Virtualchain. If not, see .
22 | """
23 |
24 | import ecdsalib
25 | import encoding
26 | import hashing
27 | import merkle
28 |
29 | import config
30 | import blockchain
31 | import indexer
32 |
33 | from config import *
34 | from blockchain import *
35 | from blockchain.bitcoin_blockchain import BitcoinPublicKey, BitcoinPrivateKey, hex_hash160_to_address, version_byte, \
36 | multisig_version_byte, make_multisig_info, parse_multisig_redeemscript, parse_multisig_scriptsig, hex_hash160_to_address, \
37 | AuthServiceProxy
38 |
39 | from indexer import StateEngine, get_index_range, RESERVED_KEYS, sqlite3_find_tool, sqlite3_backup, state_engine_replay, state_engine_verify
40 |
--------------------------------------------------------------------------------
/virtualchain/lib/blockchain/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | """
4 | Virtualchain
5 | ~~~~~
6 | copyright: (c) 2014 by Halfmoon Labs, Inc.
7 | copyright: (c) 2015 by Blockstack.org
8 |
9 | This file is part of Virtualchain
10 |
11 | Virtualchain is free software: you can redistribute it and/or modify
12 | it under the terms of the GNU General Public License as published by
13 | the Free Software Foundation, either version 3 of the License, or
14 | (at your option) any later version.
15 |
16 | Virtualchain is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | GNU General Public License for more details.
20 | You should have received a copy of the GNU General Public License
21 | along with Virtualchain. If not, see .
22 | """
23 |
24 | import transactions
25 | import session
26 |
27 | from session import BitcoindConnection, create_bitcoind_connection
28 | from session import connect_bitcoind_impl as default_connect_bitcoind
29 |
30 | from address import *
31 | from keys import *
32 | from scripts import *
33 | from transactions import *
34 |
35 | from bitcoin_blockchain import *
36 |
--------------------------------------------------------------------------------
/virtualchain/lib/blockchain/address.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | """
4 | Virtualchain
5 | ~~~~~
6 | copyright: (c) 2014 by Halfmoon Labs, Inc.
7 | copyright: (c) 2015-2018 by Blockstack.org
8 |
9 | This file is part of Virtualchain
10 |
11 | Virtualchain is free software: you can redistribute it and/or modify
12 | it under the terms of the GNU General Public License as published by
13 | the Free Software Foundation, either version 3 of the License, or
14 | (at your option) any later version.
15 |
16 | Virtualchain is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | GNU General Public License for more details.
20 | You should have received a copy of the GNU General Public License
21 | along with Virtualchain. If not, see .
22 | """
23 | from bitcoin_blockchain import btc_address_reencode
24 |
25 | def address_reencode(address, blockchain='bitcoin', **blockchain_opts):
26 | """
27 | Reencode an address
28 | """
29 | if blockchain == 'bitcoin':
30 | return btc_address_reencode(address, **blockchain_opts)
31 | else:
32 | raise ValueError("Unknown blockchain '{}'".format(blockchain))
33 |
--------------------------------------------------------------------------------
/virtualchain/lib/blockchain/bitcoin_blockchain/__init__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | """
4 | Virtualchain
5 | ~~~~~
6 | copyright: (c) 2014-2015 by Halfmoon Labs, Inc.
7 | copyright: (c) 2016 by Blockstack.org
8 |
9 | This file is part of Virtualchain
10 |
11 | Virtualchain is free software: you can redistribute it and/or modify
12 | it under the terms of the GNU General Public License as published by
13 | the Free Software Foundation, either version 3 of the License, or
14 | (at your option) any later version.
15 |
16 | Virtualchain is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | GNU General Public License for more details.
20 | You should have received a copy of the GNU General Public License
21 | along with Virtualchain. If not, see .
22 | """
23 |
24 | from .keys import BitcoinPublicKey, BitcoinPrivateKey, hex_hash160_to_address, btc_script_hex_to_address, version_byte, btc_is_multisig_script, \
25 | btc_make_payment_script, btc_make_data_script, btc_address_reencode, btc_is_p2sh_script, btc_is_p2sh_address, MAX_DATA_LEN
26 |
27 | from .fees import get_tx_fee_per_byte, get_tx_fee, tx_estimate_signature_len
28 |
29 | from .multisig import *
30 | from .authproxy import *
31 |
32 | from .spv import SPVClient
33 | from .blocks import BlockchainDownloader, get_bitcoin_blockchain_height
34 | from .bits import *
35 |
--------------------------------------------------------------------------------
/virtualchain/lib/blockchain/bitcoin_blockchain/authproxy.py:
--------------------------------------------------------------------------------
1 |
2 | """
3 | Copyright 2011 Jeff Garzik
4 |
5 | AuthServiceProxy has the following improvements over python-jsonrpc's
6 | ServiceProxy class:
7 |
8 | - HTTP connections persist for the life of the AuthServiceProxy object
9 | (if server supports HTTP/1.1)
10 | - sends protocol 'version', per JSON-RPC 1.1
11 | - sends proper, incrementing 'id'
12 | - sends Basic HTTP authentication headers
13 | - parses all JSON numbers that look like floats as Decimal
14 | - uses standard Python json lib
15 |
16 | Previous copyright, from python-jsonrpc/jsonrpc/proxy.py:
17 |
18 | Copyright (c) 2007 Jan-Klaas Kollhof
19 |
20 | This file is part of jsonrpc.
21 |
22 | jsonrpc is free software; you can redistribute it and/or modify
23 | it under the terms of the GNU Lesser General Public License as published by
24 | the Free Software Foundation; either version 2.1 of the License, or
25 | (at your option) any later version.
26 |
27 | This software is distributed in the hope that it will be useful,
28 | but WITHOUT ANY WARRANTY; without even the implied warranty of
29 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
30 | GNU Lesser General Public License for more details.
31 |
32 | You should have received a copy of the GNU Lesser General Public License
33 | along with this software; if not, write to the Free Software
34 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
35 | """
36 |
37 | try:
38 | import http.client as httplib
39 | except ImportError:
40 | import httplib
41 | import base64
42 | import decimal
43 | import json
44 | import logging
45 | try:
46 | import urllib.parse as urlparse
47 | except ImportError:
48 | import urlparse
49 |
50 | USER_AGENT = "AuthServiceProxy/0.1"
51 |
52 | HTTP_TIMEOUT = 30
53 |
54 | log = logging.getLogger("BitcoinRPC")
55 |
56 | class JSONRPCException(Exception):
57 | def __init__(self, rpc_error):
58 | parent_args = []
59 | try:
60 | parent_args.append(rpc_error['message'])
61 | except:
62 | pass
63 | Exception.__init__(self, *parent_args)
64 | self.error = rpc_error
65 | self.code = rpc_error['code'] if 'code' in rpc_error else None
66 | self.message = rpc_error['message'] if 'message' in rpc_error else None
67 |
68 | def __str__(self):
69 | return '%d: %s' % (self.code, self.message)
70 |
71 | def __repr__(self):
72 | return '<%s \'%s\'>' % (self.__class__.__name__, self)
73 |
74 |
75 | def EncodeDecimal(o):
76 | if isinstance(o, decimal.Decimal):
77 | return float(round(o, 8))
78 | raise TypeError(repr(o) + " is not JSON serializable")
79 |
80 | class AuthServiceProxy(object):
81 | __id_count = 0
82 |
83 | def __init__(self, service_url, service_name=None, timeout=HTTP_TIMEOUT, connection=None, legacy=False):
84 | self.__service_url = service_url
85 | self.__service_name = service_name
86 | self.__url = urlparse.urlparse(service_url)
87 | self.__legacy = legacy
88 | assert self.__url.port, 'Bitcoin URL requires a port'
89 | port = self.__url.port
90 |
91 | (user, passwd) = (self.__url.username, self.__url.password)
92 | try:
93 | user = user.encode('utf8')
94 | except AttributeError:
95 | pass
96 | try:
97 | passwd = passwd.encode('utf8')
98 | except AttributeError:
99 | pass
100 | authpair = user + b':' + passwd
101 | self.__auth_header = b'Basic ' + base64.b64encode(authpair)
102 |
103 | self.__timeout = timeout
104 |
105 | if connection:
106 | # Callables re-use the connection of the original proxy
107 | self.__conn = connection
108 | elif self.__url.scheme == 'https':
109 | self.__conn = httplib.HTTPSConnection(self.__url.hostname, port,
110 | timeout=timeout)
111 | else:
112 | self.__conn = httplib.HTTPConnection(self.__url.hostname, port,
113 | timeout=timeout)
114 |
115 | def __getattr__(self, name):
116 | if name.startswith('__') and name.endswith('__'):
117 | # Python internal stuff
118 | raise AttributeError
119 | if name == 'getinfo' and not self.__legacy:
120 | return self.getinfo
121 | if self.__service_name is not None:
122 | name = "%s.%s" % (self.__service_name, name)
123 | return AuthServiceProxy(self.__service_url, name, self.__timeout, self.__conn)
124 |
125 |
126 | def __call__(self, *args):
127 | AuthServiceProxy.__id_count += 1
128 |
129 | log.debug("-%s-> %s %s"%(AuthServiceProxy.__id_count, self.__service_name,
130 | json.dumps(args, default=EncodeDecimal)))
131 | postdata = json.dumps({'version': '1.1',
132 | 'method': self.__service_name,
133 | 'params': args,
134 | 'id': AuthServiceProxy.__id_count}, default=EncodeDecimal)
135 | self.__conn.request('POST', self.__url.path, postdata,
136 | {'Host': self.__url.hostname,
137 | 'User-Agent': USER_AGENT,
138 | 'Authorization': self.__auth_header,
139 | 'Content-type': 'application/json'})
140 | self.__conn.sock.settimeout(self.__timeout)
141 |
142 | response = self._get_response()
143 | if response.get('error') is not None:
144 | raise JSONRPCException(response['error'])
145 | elif 'result' not in response:
146 | raise JSONRPCException({
147 | 'code': -343, 'message': 'missing JSON-RPC result'})
148 |
149 | return response['result']
150 |
151 |
152 | def batch_(self, rpc_calls):
153 | """Batch RPC call.
154 | Pass array of arrays: [ [ "method", params... ], ... ]
155 | Returns array of results.
156 | """
157 | batch_data = []
158 | for rpc_call in rpc_calls:
159 | AuthServiceProxy.__id_count += 1
160 | m = rpc_call.pop(0)
161 | batch_data.append({"jsonrpc":"2.0", "method":m, "params":rpc_call, "id":AuthServiceProxy.__id_count})
162 |
163 | postdata = json.dumps(batch_data, default=EncodeDecimal)
164 | log.debug("--> "+postdata)
165 | self.__conn.request('POST', self.__url.path, postdata,
166 | {'Host': self.__url.hostname,
167 | 'User-Agent': USER_AGENT,
168 | 'Authorization': self.__auth_header,
169 | 'Content-type': 'application/json'})
170 | results = []
171 | responses = self._get_response()
172 | for response in responses:
173 | if response['error'] is not None:
174 | raise JSONRPCException(response['error'])
175 | elif 'result' not in response:
176 | raise JSONRPCException({
177 | 'code': -343, 'message': 'missing JSON-RPC result'})
178 | else:
179 | results.append(response['result'])
180 | return results
181 |
182 |
183 | def _get_response(self):
184 | http_response = self.__conn.getresponse()
185 | if http_response is None:
186 | raise JSONRPCException({
187 | 'code': -342, 'message': 'missing HTTP response from server'})
188 |
189 | content_type = http_response.getheader('Content-Type')
190 | if content_type != 'application/json':
191 | raise JSONRPCException({
192 | 'code': -342, 'message': 'non-JSON HTTP response with \'%i %s\' from server %s' % (http_response.status, http_response.reason, self.__service_url)})
193 |
194 | responsedata = http_response.read().decode('utf8')
195 | response = json.loads(responsedata, parse_float=decimal.Decimal)
196 | if "error" in response and response["error"] is None:
197 | log.debug("<-%s- %s"%(response["id"], json.dumps(response["result"], default=EncodeDecimal)))
198 | else:
199 | log.debug("<-- "+responsedata)
200 | return response
201 |
202 |
203 | def getinfo(self):
204 | """
205 | Backwards-compatibility for 0.14 and later
206 | """
207 | try:
208 | old_getinfo = AuthServiceProxy(self.__service_url, 'getinfo', self.__timeout, self.__conn, True)
209 | res = old_getinfo()
210 | if 'error' not in res:
211 | # 0.13 and earlier
212 | return res
213 |
214 | except JSONRPCException:
215 | pass
216 |
217 | network_info = self.getnetworkinfo()
218 | blockchain_info = self.getblockchaininfo()
219 | try:
220 | wallet_info = self.getwalletinfo()
221 | except:
222 | wallet_info = {
223 | 'walletversion': None,
224 | 'balance': None,
225 | 'keypoololdest': None,
226 | 'keypoolsize': None,
227 | 'paytxfee': None,
228 | }
229 |
230 | res = {
231 | 'version': network_info['version'],
232 | 'protocolversion': network_info['protocolversion'],
233 | 'walletversion': wallet_info['walletversion'],
234 | 'balance': wallet_info['balance'],
235 | 'blocks': blockchain_info['blocks'],
236 | 'timeoffset': network_info['timeoffset'],
237 | 'connections': network_info['connections'],
238 | 'proxy': network_info['networks'],
239 | 'difficulty': blockchain_info['difficulty'],
240 | 'testnet': blockchain_info['chain'] == 'testnet',
241 | 'keypoololdest': wallet_info['keypoololdest'],
242 | 'keypoolsize': wallet_info['keypoolsize'],
243 | 'paytxfee': wallet_info['paytxfee'],
244 | 'errors': network_info['warnings'],
245 | }
246 |
247 | for k in ['unlocked_until', 'relayfee', 'paytxfee']:
248 | if wallet_info.has_key(k):
249 | res[k] = wallet_info[k]
250 |
251 | return res
252 |
253 |
254 |
255 |
--------------------------------------------------------------------------------
/virtualchain/lib/blockchain/bitcoin_blockchain/bech32.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | """
4 | Virtualchain
5 | ~~~~~
6 | copyright: (c) 2014-2015 by Halfmoon Labs, Inc.
7 | copyright: (c) 2016-2017 by Blockstack.org
8 |
9 | This file is part of Virtualchain
10 |
11 | Virtualchain is free software: you can redistribute it and/or modify
12 | it under the terms of the GNU General Public License as published by
13 | the Free Software Foundation, either version 3 of the License, or
14 | (at your option) any later version.
15 |
16 | Virtualchain is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | GNU General Public License for more details.
20 | You should have received a copy of the GNU General Public License
21 | along with Virtualchain. If not, see .
22 | """
23 |
24 | # depending on whether or not we're talking to
25 | # -testnet/-regtest or mainnet, determine which human-readible
26 | # prefix to use
27 | import os
28 |
29 | if os.environ.get("BLOCKSTACK_TESTNET", None) == "1" or os.environ.get("BLOCKSTACK_TESTNET3", None) == "1":
30 | bech32_prefix = 'tb'
31 |
32 | else:
33 | bech32_prefix = 'bc'
34 |
35 | bech32_witver = '1'
36 |
37 | CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
38 |
39 | # taken from BIP173
40 | def bech32_polymod(values):
41 | GEN = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]
42 | chk = 1
43 | for v in values:
44 | b = (chk >> 25)
45 | chk = (chk & 0x1ffffff) << 5 ^ v
46 | for i in range(5):
47 | chk ^= GEN[i] if ((b >> i) & 1) else 0
48 | return chk
49 |
50 |
51 | # taken from BIP173
52 | def bech32_hrp_expand(s):
53 | return [ord(x) >> 5 for x in s] + [0] + [ord(x) & 31 for x in s]
54 |
55 |
56 | # taken from BIP173
57 | def bech32_verify_checksum(hrp, data):
58 | return bech32_polymod(bech32_hrp_expand(hrp) + data) == 1
59 |
60 |
61 | # taken from BIP173
62 | def bech32_create_checksum(hrp, data):
63 | values = bech32_hrp_expand(hrp) + data
64 | polymod = bech32_polymod(values + [0,0,0,0,0,0]) ^ 1
65 | return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)]
66 |
67 |
68 | # taken from https://github.com/sipa/bech32/blob/master/ref/python/segwit_addr.py
69 | def bech32_encode(hrp, data):
70 | """Compute a Bech32 string given HRP and data values."""
71 | combined = data + bech32_create_checksum(hrp, data)
72 | return hrp + '1' + ''.join([CHARSET[d] for d in combined])
73 |
74 |
75 | # taken from https://github.com/sipa/bech32/blob/master/ref/python/segwit_addr.py
76 | def bech32_decode(bech):
77 | """Validate a Bech32 string, and determine HRP and data."""
78 | if ((any(ord(x) < 33 or ord(x) > 126 for x in bech)) or
79 | (bech.lower() != bech and bech.upper() != bech)):
80 | return (None, None)
81 | bech = bech.lower()
82 | pos = bech.rfind('1')
83 | if pos < 1 or pos + 7 > len(bech) or len(bech) > 90:
84 | return (None, None)
85 | if not all(x in CHARSET for x in bech[pos+1:]):
86 | return (None, None)
87 | hrp = bech[:pos]
88 | data = [CHARSET.find(x) for x in bech[pos+1:]]
89 | if not bech32_verify_checksum(hrp, data):
90 | return (None, None)
91 | return (hrp, data[:-6])
92 |
93 |
94 | # taken from https://github.com/sipa/bech32/blob/master/ref/python/segwit_addr.py
95 | def convertbits(data, frombits, tobits, pad=True):
96 | """General power-of-2 base conversion."""
97 | acc = 0
98 | bits = 0
99 | ret = []
100 | maxv = (1 << tobits) - 1
101 | max_acc = (1 << (frombits + tobits - 1)) - 1
102 | for value in data:
103 | if value < 0 or (value >> frombits):
104 | return None
105 | acc = ((acc << frombits) | value) & max_acc
106 | bits += frombits
107 | while bits >= tobits:
108 | bits -= tobits
109 | ret.append((acc >> bits) & maxv)
110 | if pad:
111 | if bits:
112 | ret.append((acc << (tobits - bits)) & maxv)
113 | elif bits >= frombits or ((acc << (tobits - bits)) & maxv):
114 | return None
115 | return ret
116 |
117 |
118 | # taken from https://github.com/sipa/bech32/blob/master/ref/python/segwit_addr.py
119 | def segwit_addr_decode(addr, hrp=bech32_prefix):
120 | """
121 | Decode a segwit address.
122 | Returns (version, hash_bin) on success
123 | Returns (None, None) on error
124 | """
125 | hrpgot, data = bech32_decode(addr)
126 | if hrpgot != hrp:
127 | return (None, None)
128 | decoded = convertbits(data[1:], 5, 8, False)
129 | if decoded is None or len(decoded) < 2 or len(decoded) > 40:
130 | return (None, None)
131 | if data[0] > 16:
132 | return (None, None)
133 | if data[0] == 0 and len(decoded) != 20 and len(decoded) != 32:
134 | return (None, None)
135 | return (data[0], ''.join([chr(x) for x in decoded]))
136 |
137 |
138 | # taken from https://github.com/sipa/bech32/blob/master/ref/python/segwit_addr.py
139 | def segwit_addr_encode(witprog_bin, hrp=bech32_prefix, witver=bech32_witver):
140 | """
141 | Encode a segwit script hash to a bech32 address.
142 | Returns the bech32-encoded string on success
143 | """
144 | witprog_bytes = [ord(c) for c in witprog_bin]
145 | ret = bech32_encode(hrp, [int(witver)] + convertbits(witprog_bytes, 8, 5))
146 | assert segwit_addr_decode(hrp, ret) is not (None, None)
147 | return ret
148 |
--------------------------------------------------------------------------------
/virtualchain/lib/blockchain/bitcoin_blockchain/fees.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | """
4 | Virtualchain
5 | ~~~~~
6 | copyright: (c) 2014-2015 by Halfmoon Labs, Inc.
7 | copyright: (c) 2016-2017 by Blockstack.org
8 |
9 | This file is part of Virtualchain
10 |
11 | Virtualchain is free software: you can redistribute it and/or modify
12 | it under the terms of the GNU General Public License as published by
13 | the Free Software Foundation, either version 3 of the License, or
14 | (at your option) any later version.
15 |
16 | Virtualchain is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | GNU General Public License for more details.
20 | You should have received a copy of the GNU General Public License
21 | along with Virtualchain. If not, see .
22 | """
23 |
24 | import os
25 | import keylib
26 | import logging
27 |
28 | from .authproxy import JSONRPCException
29 |
30 | from .bits import btc_tx_deserialize, btc_tx_is_segwit, btc_witness_script_serialize
31 |
32 | from .keys import btc_is_singlesig, btc_is_multisig, btc_is_singlesig_segwit, btc_is_multisig_segwit, \
33 | btc_make_p2sh_p2wsh_redeem_script, btc_make_p2sh_p2wpkh_redeem_script
34 |
35 | from .multisig import parse_multisig_redeemscript
36 | from ..session import get_bitcoind_client
37 | from ....lib.ecdsalib import ecdsa_private_key
38 | from ....lib.config import get_logger
39 |
40 | log = get_logger('virtualchain')
41 |
42 | def calculate_tx_fee( tx_hex, fee_per_byte ):
43 | """
44 | High-level API call (meant to be blockchain-agnostic)
45 | What is the fee for the transaction?
46 | """
47 | txobj = btc_tx_deserialize(tx_hex)
48 | tx_num_bytes = len(tx_hex) / 2
49 | num_virtual_bytes = None
50 |
51 | if btc_tx_is_segwit(tx_hex):
52 | # segwit--discount witness data
53 | witness_len = 0
54 | for inp in txobj['ins']:
55 | witness_len += len(inp['witness_script']) / 2
56 |
57 | # see https://bitcoincore.org/en/segwit_wallet_dev/#transaction-fee-estimation
58 | tx_num_bytes_original = tx_num_bytes - witness_len
59 | num_virtual_bytes = 3 * tx_num_bytes_original + tx_num_bytes
60 |
61 | else:
62 | # non-segwit
63 | num_virtual_bytes = tx_num_bytes * 4
64 |
65 | return (fee_per_byte * num_virtual_bytes) / 4
66 |
67 |
68 | def get_tx_fee_per_byte(bitcoind_opts=None, config_path=None, bitcoind_client=None):
69 | """
70 | Get the tx fee per byte from the underlying blockchain
71 | Return the fee on success
72 | Return None on error
73 | """
74 | if bitcoind_client is None:
75 | bitcoind_client = get_bitcoind_client(bitcoind_opts=bitcoind_opts, config_path=config_path)
76 |
77 | try:
78 | # try to confirm in 2-3 blocks
79 | try:
80 | fee_info = bitcoind_client.estimatesmartfee(2)
81 | if 'errors' in fee_info and len(fee_info['errors']) > 0:
82 | fee = -1
83 | else:
84 | fee = fee_info['feerate']
85 |
86 | except JSONRPCException as je:
87 | fee = bitcoind_client.estimatefee(2)
88 |
89 | if fee < 0:
90 | # if we're testing, then use our own fee
91 | if os.environ.get("BLOCKSTACK_TEST") == '1' or os.environ.get("BLOCKSTACK_TESTNET", None) == "1":
92 | fee = 5500.0 / 10**8
93 |
94 | else:
95 | log.error("Failed to estimate tx fee")
96 | return None
97 | else:
98 | log.debug("Bitcoin estimatefee(2) is {}".format(fee))
99 |
100 | fee = float(fee)
101 |
102 | # fee is BTC/kb. Return satoshis/byte
103 | ret = int(round(fee * 10**8 / 1024.0))
104 | log.debug("Bitcoin estimatefee(2) is {} ({} satoshi/byte)".format(fee, ret))
105 | return ret
106 |
107 | except Exception as e:
108 | if os.environ.get("BLOCKSTACK_DEBUG") == '1':
109 | log.exception(e)
110 |
111 | log.error("Failed to estimate tx fee per byte")
112 | return None
113 |
114 |
115 | def get_tx_fee(tx_hex, config_path=None, bitcoind_opts=None, bitcoind_client=None):
116 | """
117 | Get the tx fee for a tx
118 | Return the fee on success
119 | Return None on error
120 | """
121 | tx_fee_per_byte = get_tx_fee_per_byte(config_path=config_path, bitcoind_opts=bitcoind_opts, bitcoind_client=bitcoind_client)
122 | if tx_fee_per_byte is None:
123 | return None
124 |
125 | return calculate_tx_fee(tx_hex, tx_fee_per_byte)
126 |
127 |
128 | def tx_estimate_signature_len(privkey_info):
129 | """
130 | Estimate how long a signature is going to be, given a private key.
131 | privkey_info is a private key or a multisig/segwit bundle.
132 |
133 | This accounts for both the scriptsig and witness data. The return
134 | value is the number of actual *bytes* (not vbytes) that the signature
135 | will count for in bitcoin (i.e. witness bytes are discounted)
136 |
137 | Return the number of bytes on success
138 | Raise ValueError of the key is not recognized
139 | """
140 | if btc_is_singlesig(privkey_info):
141 | # one signature produces a scriptsig of ~71 bytes (signature) + pubkey + encoding (4)
142 | log.debug("Single private key makes a ~73 byte signature")
143 | pubkey = ecdsa_private_key(privkey_info).public_key().to_hex().decode('hex')
144 | return 71 + len(pubkey) + 4
145 |
146 | elif btc_is_multisig(privkey_info):
147 | # one signature produces a scriptsig of redeem_script + (num_pubkeys * ~74 bytes) + encoding (~6)
148 | m, _ = parse_multisig_redeemscript( privkey_info['redeem_script'] )
149 | siglengths = 74 * m
150 | scriptlen = len(privkey_info['redeem_script']) / 2
151 | siglen = 6 + scriptlen + siglengths
152 |
153 | log.debug("Multisig private key makes ~{} byte signature".format(siglen))
154 | return siglen
155 |
156 | elif btc_is_singlesig_segwit(privkey_info):
157 | # bitcoin p2sh-p2wpkh script
158 | # one signature produces (pubkey + signature (~74 bytes)) + scriptsig len
159 | privkey = privkey_info['private_keys'][0]
160 | pubkey_hex = keylib.key_formatting.compress(ecdsa_private_key(privkey).public_key().to_hex())
161 | redeem_script = btc_make_p2sh_p2wpkh_redeem_script(pubkey_hex)
162 | witness_script = btc_witness_script_serialize(['00' * 74, pubkey_hex])
163 |
164 | scriptsig_len = 6 + len(redeem_script) / 2
165 | witness_len = len(witness_script) / 2
166 | siglen = int(round(float(3 * scriptsig_len + (scriptsig_len + witness_len)) / 4))
167 |
168 | log.debug("Segwit p2sh-p2wpkh private key makes ~{} byte signature".format(siglen))
169 | return siglen
170 |
171 | elif btc_is_multisig_segwit(privkey_info):
172 | # bitcoin p2sh-p2wsh script
173 | # one signature produces (witness script len + num_pubkeys * ~74) + scriptsig len
174 | witness_script = privkey_info['redeem_script']
175 | m, _ = parse_multisig_redeemscript(witness_script)
176 | redeem_script = btc_make_p2sh_p2wsh_redeem_script(witness_script)
177 |
178 | siglengths = 74 * m
179 | scriptsig_len = 6 + len(redeem_script) / 2
180 | witness_len = len(witness_script) / 2 + siglengths
181 | siglen = int(round(float(3 * scriptsig_len + (scriptsig_len + witness_len)) / 4))
182 |
183 | log.debug("Segwit p2sh-p2wsh private keys make ~{} byte signature".format(siglen))
184 | return siglen
185 |
186 | raise ValueError("Unrecognized private key foramt")
187 |
188 |
--------------------------------------------------------------------------------
/virtualchain/lib/blockchain/bitcoin_blockchain/keys.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | """
4 | Virtualchain
5 | ~~~~~
6 | copyright: (c) 2014-2015 by Halfmoon Labs, Inc.
7 | copyright: (c) 2016 by Blockstack.org
8 |
9 | This file is part of Virtualchain
10 |
11 | Virtualchain is free software: you can redistribute it and/or modify
12 | it under the terms of the GNU General Public License as published by
13 | the Free Software Foundation, either version 3 of the License, or
14 | (at your option) any later version.
15 |
16 | Virtualchain is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | GNU General Public License for more details.
20 | You should have received a copy of the GNU General Public License
21 | along with Virtualchain. If not, see .
22 | """
23 |
24 | import keylib
25 | import os
26 | import binascii
27 | import jsonschema
28 | import re
29 | from opcodes import *
30 | from bech32 import *
31 | from jsonschema import ValidationError
32 |
33 | from ....lib import hashing, encoding, ecdsalib
34 | from ....lib.config import get_features
35 |
36 | MAX_DATA_LEN = 80 # 80 bytes per data output
37 |
38 | OP_BASE58CHECK_PATTERN = r'^([123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]+)$'
39 | OP_ADDRESS_PATTERN = OP_BASE58CHECK_PATTERN
40 | OP_PRIVKEY_PATTERN = OP_BASE58CHECK_PATTERN
41 | OP_HEX_PATTERN = r'^([0-9a-fA-F]+)$'
42 | OP_SCRIPT_PATTERN = OP_HEX_PATTERN
43 |
44 | PRIVKEY_SINGLESIG_SCHEMA_WIF = {
45 | 'type': 'string',
46 | 'pattern': OP_PRIVKEY_PATTERN
47 | }
48 |
49 | PRIVKEY_SINGLESIG_SCHEMA_HEX = {
50 | 'type': 'string',
51 | 'pattern': OP_HEX_PATTERN
52 | }
53 |
54 | PRIVKEY_SINGLESIG_SCHEMA = {
55 | 'anyOf': [
56 | PRIVKEY_SINGLESIG_SCHEMA_WIF,
57 | PRIVKEY_SINGLESIG_SCHEMA_HEX
58 | ],
59 | }
60 |
61 | PRIVKEY_MULTISIG_SCHEMA = {
62 | 'type': 'object',
63 | 'properties': {
64 | 'address': {
65 | 'type': 'string',
66 | 'pattern': OP_ADDRESS_PATTERN,
67 | },
68 | 'redeem_script': {
69 | 'type': 'string',
70 | 'pattern': OP_SCRIPT_PATTERN,
71 | },
72 | 'private_keys': {
73 | 'type': 'array',
74 | 'items': PRIVKEY_SINGLESIG_SCHEMA
75 | },
76 | 'segwit': {
77 | 'type': 'boolean'
78 | },
79 | },
80 | 'required': [
81 | 'address',
82 | 'redeem_script',
83 | 'private_keys'
84 | ],
85 | }
86 |
87 |
88 | # depending on whether or not we're talking to
89 | # -testnet/-regtest or mainnet, determine which private
90 | # and public key classes to use.
91 |
92 | if os.environ.get("BLOCKSTACK_TESTNET", None) == "1" or os.environ.get("BLOCKSTACK_TESTNET3", None) == "1":
93 |
94 | version_byte = 111
95 | multisig_version_byte = 196
96 |
97 | # using testnet keys
98 | class TestnetPublicKey(keylib.ECPublicKey):
99 | _version_byte = 111
100 |
101 | class TestnetPrivateKey(keylib.ECPrivateKey):
102 | _pubkeyhash_version_byte = 111
103 |
104 | BitcoinPrivateKey = TestnetPrivateKey
105 | BitcoinPublicKey = TestnetPublicKey
106 |
107 | else:
108 |
109 | version_byte = 0
110 | multisig_version_byte = 5
111 |
112 | # using mainnet keys
113 | BitcoinPrivateKey = keylib.ECPrivateKey
114 | BitcoinPublicKey = keylib.ECPublicKey
115 |
116 |
117 | def bin_hash160_to_address(bin_hash160, version_byte=version_byte):
118 | # b58 addresses only!
119 | return keylib.b58check.b58check_encode(bin_hash160, version_byte=version_byte)
120 |
121 |
122 | def hex_hash160_to_address(hash160, version_byte=version_byte):
123 | # b58 addresses only!
124 | return bin_hash160_to_address(binascii.unhexlify(hash160), version_byte=version_byte)
125 |
126 |
127 | def address_to_bin_hash160(address):
128 | # b58 addresses only!
129 | return keylib.b58check.b58check_decode(address)
130 |
131 |
132 | def address_to_hex_hash160(address):
133 | # b58 addresses only!
134 | return binascii.hexlify(address_to_bin_hash160(address))
135 |
136 |
137 | def btc_script_to_hex(script):
138 | """ Parse the string representation of a script and return the hex version.
139 | Example: "OP_DUP OP_HASH160 c629...a6db OP_EQUALVERIFY OP_CHECKSIG"
140 | """
141 |
142 | hex_script = ''
143 | parts = script.split(' ')
144 | for part in parts:
145 | if part[0:3] == 'OP_':
146 | value = OPCODE_VALUES.get(part)
147 | if not value:
148 | raise ValueError("Unrecognized opcode {}".format(part))
149 |
150 | hex_script += "%0.2x" % value
151 |
152 | elif hashing.is_hex(part):
153 | hex_script += '%0.2x' % hashing.count_bytes(part) + part
154 |
155 | else:
156 | raise Exception('Invalid script - only opcodes and hex characters allowed.')
157 |
158 | return hex_script
159 |
160 |
161 | def btc_script_deserialize(script):
162 | """
163 | Given a script (hex or bin), decode it into its list of opcodes and data.
164 | Return a list of strings and ints.
165 |
166 | Based on code in pybitcointools (https://github.com/vbuterin/pybitcointools)
167 | by Vitalik Buterin
168 | """
169 |
170 | if isinstance(script, str) and re.match('^[0-9a-fA-F]*$', script):
171 | script = binascii.unhexlify(script)
172 |
173 | # output buffer
174 | out = []
175 | pos = 0
176 |
177 | while pos < len(script):
178 | # next script op...
179 | code = encoding.from_byte_to_int(script[pos])
180 |
181 | if code == 0:
182 | # empty (OP_0)
183 | out.append(None)
184 | pos += 1
185 |
186 | elif code <= 75:
187 | # literal numeric constant, followed by a slice of data.
188 | # push the slice of data.
189 | out.append(script[pos+1:pos+1+code])
190 | pos += 1 + code
191 |
192 | elif code <= 78:
193 | # OP_PUSHDATA1, OP_PUSHDATA2, OP_PUSHDATA4, followed by length and data
194 | # push the data itself
195 | szsz = pow(2, code - 76)
196 | sz = encoding.decode(script[pos+szsz: pos:-1], 256)
197 | out.append(script[pos + 1 + szsz : pos + 1 + szsz + sz])
198 | pos += 1 + szsz + sz
199 |
200 | elif code <= 96:
201 | # OP_1NEGATE, OP_RESERVED, OP_1 thru OP_16
202 | # pass -1 for OP_1NEGATE
203 | # pass 0 for OP_RESERVED (shouldn't be used anyway)
204 | # pass 1 thru 16 for OP_1 thru OP_16
205 | out.append(code - 80)
206 | pos += 1
207 |
208 | else:
209 | # raw opcode
210 | out.append(code)
211 | pos += 1
212 |
213 | # make sure each string is hex'ed
214 | out = encoding.json_changebase(out, lambda x: encoding.safe_hexlify(x))
215 | return out
216 |
217 |
218 | def _btc_script_serialize_unit(unit):
219 | """
220 | Encode one item of a BTC script
221 | Return the encoded item (as a string)
222 |
223 | Based on code from pybitcointools (https://github.com/vbuterin/pybitcointools)
224 | by Vitalik Buterin
225 | """
226 |
227 | if isinstance(unit, int):
228 | # cannot be less than -1, since btc_script_deserialize() never returns such numbers
229 | if unit < -1:
230 | raise ValueError('Invalid integer: {}'.format(unit))
231 |
232 | if unit < 16:
233 | if unit == 0:
234 | # OP_RESERVED
235 | return encoding.from_int_to_byte(OPCODE_VALUES['OP_RESERVED'])
236 | else:
237 | # OP_1 thru OP_16, or OP_1NEGATE
238 | return encoding.from_int_to_byte(unit + 80)
239 | else:
240 | # pass as numeric literal or raw opcode
241 | return encoding.from_int_to_byte(unit)
242 |
243 | elif unit is None:
244 | # None means OP_0
245 | return b'\x00'
246 |
247 | else:
248 | if len(unit) <= 75:
249 | # length + payload
250 | return encoding.from_int_to_byte(len(unit)) + unit
251 |
252 | elif len(unit) < 256:
253 | # OP_PUSHDATA1 + length (1 byte) + payload
254 | return encoding.from_int_to_byte(OPCODE_VALUES['OP_PUSHDATA1']) + encoding.from_int_to_byte(len(unit)) + unit
255 |
256 | elif len(unit) < 65536:
257 | # OP_PUSHDATA2 + length (2 bytes, big-endian) + payload
258 | return encoding.from_int_to_byte(OPCODE_VALUES['OP_PUSHDATA2']) + encoding.encode(len(unit), 256, 2)[::-1] + unit
259 | else:
260 | # OP_PUSHDATA4 + length (4 bytes, big-endian) + payload
261 | return encoding.from_int_to_byte(OPCODE_VALUES['OP_PUSHDATA4']) + encoding.encode(len(unit), 256, 4)[::-1] + unit
262 |
263 |
264 | def btc_script_serialize(_script):
265 | """
266 | Given a deserialized script (i.e. an array of Nones, ints, and strings), or an existing script,
267 | turn it back into a hex script
268 |
269 | Based on code from pybitcointools (https://github.com/vbuterin/pybitcointools)
270 | by Vitalik Buterin
271 | """
272 | script = _script
273 | if encoding.json_is_base(_script, 16):
274 | # hex-to-bin all hex strings in this script
275 | script = encoding.json_changebase(_script, lambda x: binascii.unhexlify(x))
276 |
277 | # encode each item and return the concatenated list
278 | return encoding.safe_hexlify( ''.join(map(_btc_script_serialize_unit, script)) )
279 |
280 |
281 | def btc_make_payment_script( address, segwit=None, **ignored ):
282 | """
283 | Make a pay-to-address script.
284 | """
285 |
286 | if segwit is None:
287 | segwit = get_features('segwit')
288 |
289 | # is address bech32-encoded?
290 | witver, withash = segwit_addr_decode(address)
291 | if witver is not None and withash is not None:
292 | # bech32 segwit address
293 | if not segwit:
294 | raise ValueError("Segwit is disabled")
295 |
296 | if len(withash) == 20:
297 | # p2wpkh
298 | script_hex = '0014' + withash.encode('hex')
299 | return script_hex
300 |
301 | elif len(withash) == 32:
302 | # p2wsh
303 | script_hex = '0020' + withash.encode('hex')
304 | return script_hex
305 |
306 | else:
307 | raise ValueError("Unrecognized address '%s'" % address )
308 |
309 | else:
310 | # address is b58check-encoded
311 | vb = keylib.b58check.b58check_version_byte(address)
312 | if vb == version_byte:
313 | # p2pkh
314 | hash160 = binascii.hexlify( keylib.b58check.b58check_decode(address) )
315 | script = 'OP_DUP OP_HASH160 {} OP_EQUALVERIFY OP_CHECKSIG'.format(hash160)
316 | script_hex = btc_script_to_hex(script)
317 | return script_hex
318 |
319 | elif vb == multisig_version_byte:
320 | # p2sh
321 | hash160 = binascii.hexlify( keylib.b58check.b58check_decode(address) )
322 | script = 'OP_HASH160 {} OP_EQUAL'.format(hash160)
323 | script_hex = btc_script_to_hex(script)
324 | return script_hex
325 |
326 | else:
327 | raise ValueError("Unrecognized address '%s'" % address )
328 |
329 |
330 | def btc_make_data_script( data, **ignored ):
331 | """
332 | Make a data-bearing transaction output.
333 | Data must be a hex string
334 | Returns a hex string.
335 | """
336 | if len(data) >= MAX_DATA_LEN * 2:
337 | raise ValueError("Data hex string is too long") # note: data is a hex string
338 |
339 | if len(data) % 2 != 0:
340 | raise ValueError("Data hex string is not even length")
341 |
342 | return "6a{:02x}{}".format(len(data)/2, data)
343 |
344 |
345 | def btc_script_hex_to_address( script_hex, segwit=None ):
346 | """
347 | Examine a script (hex-encoded) and extract an address.
348 | Return the address on success
349 | Return None on error
350 | """
351 | # TODO: make this support more than bitcoin-like scripts
352 | if script_hex.startswith("76a914") and script_hex.endswith("88ac") and len(script_hex) == 50:
353 | # p2pkh script
354 | hash160_bin = binascii.unhexlify(script_hex[6:-4])
355 | return bin_hash160_to_address(hash160_bin, version_byte=version_byte)
356 |
357 | elif script_hex.startswith("a914") and script_hex.endswith("87") and len(script_hex) == 46:
358 | # p2sh script
359 | hash160_bin = binascii.unhexlify(script_hex[4:-2])
360 | return bin_hash160_to_address(hash160_bin, version_byte=multisig_version_byte)
361 |
362 | elif script_hex.startswith('0014') and len(script_hex) == 44:
363 | # p2wpkh script (bech32 address)
364 | hash160_bin = binascii.unhexlify(script_hex[4:])
365 | return segwit_addr_encode(hash160_bin)
366 |
367 | elif script_hex.startswith('0020') and len(script_hex) == 68:
368 | # p2wsh script (bech32 address)
369 | sha256_bin = binascii.unhexlify(script_hex[4:])
370 | return segwit_addr_encode(sha256_bin)
371 |
372 | return None
373 |
374 |
375 | def btc_make_p2sh_address( script_hex ):
376 | """
377 | Make a P2SH address from a hex script
378 | """
379 | h = hashing.bin_hash160(binascii.unhexlify(script_hex))
380 | addr = bin_hash160_to_address(h, version_byte=multisig_version_byte)
381 | return addr
382 |
383 |
384 | def btc_make_p2wpkh_address( pubkey_hex ):
385 | """
386 | Make a p2wpkh address from a hex pubkey
387 | """
388 | pubkey_hex = keylib.key_formatting.compress(pubkey_hex)
389 | hash160_bin = hashing.bin_hash160(pubkey_hex.decode('hex'))
390 | return segwit_addr_encode(hash160_bin)
391 |
392 |
393 | def btc_make_p2sh_p2wpkh_redeem_script( pubkey_hex ):
394 | """
395 | Make the redeem script for a p2sh-p2wpkh witness script
396 | """
397 | pubkey_hash = hashing.bin_hash160(pubkey_hex.decode('hex')).encode('hex')
398 | redeem_script = btc_script_serialize(['0014' + pubkey_hash])
399 | return redeem_script
400 |
401 |
402 | def btc_make_p2sh_p2wpkh_address( witness_script_hex ):
403 | """
404 | Make a p2sh address for a p2wpkh witness script hex
405 | """
406 | redeem_script = btc_make_p2sh_p2wpkh_redeem_script(witness_script_hex)
407 | p2sh_addr = btc_make_p2sh_address(redeem_script)
408 | return p2sh_addr
409 |
410 |
411 | def btc_make_p2wsh_address( witness_script_hex ):
412 | """
413 | Make a p2wsh address from a witness script
414 | """
415 | witness_hash_bin = hashing.bin_sha256(witness_script_hex.decode('hex'))
416 | return segwit_addr_encode(witness_hash_bin)
417 |
418 |
419 | def btc_make_p2sh_p2wsh_redeem_script( witness_script_hex ):
420 | """
421 | Make the redeem script for a p2sh-p2wsh witness script
422 | """
423 | witness_script_hash = hashing.bin_sha256(witness_script_hex.decode('hex')).encode('hex')
424 | redeem_script = btc_script_serialize(['0020' + witness_script_hash])
425 | return redeem_script
426 |
427 |
428 | def btc_make_p2sh_p2wsh_address( witness_script_hex ):
429 | """
430 | Make a p2sh address for a p2wsh witness script hex
431 | """
432 | redeem_script = btc_make_p2sh_p2wsh_redeem_script(witness_script_hex)
433 | p2sh_addr = btc_make_p2sh_address(redeem_script)
434 | return p2sh_addr
435 |
436 |
437 | def btc_is_p2sh_address( address ):
438 | """
439 | Is the given address a p2sh address?
440 | """
441 | vb = keylib.b58check.b58check_version_byte( address )
442 | if vb == multisig_version_byte:
443 | return True
444 | else:
445 | return False
446 |
447 |
448 | def btc_is_p2pkh_address( address ):
449 | """
450 | Is the given address a p2pkh address?
451 | """
452 | vb = keylib.b58check.b58check_version_byte( address )
453 | if vb == version_byte:
454 | return True
455 | else:
456 | return False
457 |
458 |
459 | def btc_is_p2wpkh_address( address ):
460 | """
461 | Is the given address a p2wpkh address?
462 | """
463 | wver, whash = segwit_addr_decode(address)
464 | if whash is None:
465 | return False
466 |
467 | if len(whash) != 20:
468 | return False
469 |
470 | return True
471 |
472 |
473 | def btc_is_p2wsh_address( address ):
474 | """
475 | Is the given address a p2wsh address?
476 | """
477 | wver, whash = segwit_addr_decode(address)
478 | if whash is None:
479 | return False
480 |
481 | if len(whash) != 32:
482 | return False
483 |
484 | return True
485 |
486 |
487 | def btc_is_segwit_address(address):
488 | """
489 | Is the given address a segwit (bech32) address?
490 | """
491 | return btc_is_p2wpkh_address(address) or btc_is_p2wsh_address(address)
492 |
493 |
494 | def btc_is_p2sh_script( script_hex ):
495 | """
496 | Is the given scriptpubkey a p2sh script?
497 | """
498 | if script_hex.startswith("a914") and script_hex.endswith("87") and len(script_hex) == 46:
499 | return True
500 | else:
501 | return False
502 |
503 |
504 | def btc_is_p2wsh_script( script_hex ):
505 | """
506 | Is the given scriptpubkey a p2wsh script?
507 | """
508 | if script_hex.startswith('00') and len(script_hex) == 66:
509 | return True
510 | else:
511 | return False
512 |
513 |
514 | def btc_address_reencode( address, **blockchain_opts ):
515 | """
516 | Depending on whether or not we're in testnet
517 | or mainnet, re-encode an address accordingly.
518 | """
519 | # re-encode bitcoin address
520 | network = blockchain_opts.get('network', None)
521 | opt_version_byte = blockchain_opts.get('version_byte', None)
522 |
523 | if btc_is_segwit_address(address):
524 | # bech32 address
525 | hrp = None
526 | if network == 'mainnet':
527 | hrp = 'bc'
528 |
529 | elif network == 'testnet':
530 | hrp = 'tb'
531 |
532 | else:
533 | if os.environ.get('BLOCKSTACK_TESTNET') == '1' or os.environ.get('BLOCKSTACK_TESTNET3') == '1':
534 | hrp = 'tb'
535 |
536 | else:
537 | hrp = 'bc'
538 |
539 | wver, whash = segwit_addr_decode(address)
540 | return segwit_addr_encode(whash, hrp=hrp, witver=wver)
541 |
542 | else:
543 | # base58 address
544 | vb = keylib.b58check.b58check_version_byte( address )
545 |
546 | if network == 'mainnet':
547 | if vb == 0 or vb == 111:
548 | vb = 0
549 |
550 | elif vb == 5 or vb == 196:
551 | vb = 5
552 |
553 | else:
554 | raise ValueError("Unrecognized address %s" % address)
555 |
556 | elif network == 'testnet':
557 | if vb == 0 or vb == 111:
558 | vb = 111
559 |
560 | elif vb == 5 or vb == 196:
561 | vb = 196
562 |
563 | else:
564 | raise ValueError("Unrecognized address %s" % address)
565 |
566 | else:
567 | if opt_version_byte is not None:
568 | vb = opt_version_byte
569 |
570 | elif os.environ.get("BLOCKSTACK_TESTNET") == "1" or os.environ.get("BLOCKSTACK_TESTNET3") == "1":
571 | if vb == 0 or vb == 111:
572 | # convert to testnet p2pkh
573 | vb = 111
574 |
575 | elif vb == 5 or vb == 196:
576 | # convert to testnet p2sh
577 | vb = 196
578 |
579 | else:
580 | raise ValueError("unrecognized address %s" % address)
581 |
582 | else:
583 | if vb == 0 or vb == 111:
584 | # convert to mainnet p2pkh
585 | vb = 0
586 |
587 | elif vb == 5 or vb == 196:
588 | # convert to mainnet p2sh
589 | vb = 5
590 |
591 | else:
592 | raise ValueError("unrecognized address %s" % address)
593 |
594 | return keylib.b58check.b58check_encode( keylib.b58check.b58check_decode(address), vb )
595 |
596 |
597 | def btc_is_multisig(privkey_info, **blockchain_opts):
598 | """
599 | Does the given private key info represent
600 | a multisig bundle?
601 |
602 | For Bitcoin, this is true for multisig p2sh (not p2sh-p2wsh)
603 | """
604 | try:
605 | jsonschema.validate(privkey_info, PRIVKEY_MULTISIG_SCHEMA)
606 | return not privkey_info.get('segwit', False)
607 | except ValidationError as e:
608 | return False
609 |
610 |
611 | def btc_is_multisig_segwit(privkey_info):
612 | """
613 | Does the given private key info represent
614 | a multisig bundle?
615 |
616 | For Bitcoin, this is true for multisig p2sh (not p2sh-p2wsh)
617 | """
618 | try:
619 | jsonschema.validate(privkey_info, PRIVKEY_MULTISIG_SCHEMA)
620 | if len(privkey_info['private_keys']) == 1:
621 | return False
622 |
623 | return privkey_info.get('segwit', False)
624 | except ValidationError as e:
625 | return False
626 |
627 |
628 | def btc_is_multisig_address(addr, **blockchain_opts):
629 | """
630 | Is the given address a multisig address?
631 | """
632 | return btc_is_p2sh_address(addr) or btc_is_p2wsh_address(addr)
633 |
634 |
635 | def btc_is_multisig_script(script_hex, **blockchain_opts):
636 | """
637 | Is the given script hex a multisig script?
638 | """
639 | return btc_is_p2sh_script(script_hex) or btc_is_p2wsh_script(script_hex)
640 |
641 |
642 | def btc_is_singlesig(privkey_info, **blockchain_opts):
643 | """
644 | Does the given private key info represent
645 | a single signature bundle? (i.e. one private key)?
646 |
647 | i.e. is this key a private key string?
648 | """
649 | try:
650 | jsonschema.validate(privkey_info, PRIVKEY_SINGLESIG_SCHEMA)
651 | return True
652 | except ValidationError as e:
653 | return False
654 |
655 |
656 | def btc_get_singlesig_privkey(privkey_info, **blockchain_opts):
657 | """
658 | Get the single-sig private key from the private key info
659 | """
660 | if btc_is_singlesig(privkey_info):
661 | return privkey_info
662 |
663 | elif btc_is_singlesig_segwit(privkey_info):
664 | return privkey_info['private_keys'][0]
665 |
666 | return None
667 |
668 |
669 | def btc_is_singlesig_address(addr, **blockchain_opts):
670 | """
671 | Is the given address a single-sig address?
672 | """
673 | return btc_is_p2pkh_address(addr)
674 |
675 |
676 | def btc_is_singlesig_segwit(privkey_info):
677 | """
678 | Is the given key bundle a p2sh-p2wpkh key bundle?
679 | """
680 | try:
681 | jsonschema.validate(privkey_info, PRIVKEY_MULTISIG_SCHEMA)
682 | if len(privkey_info['private_keys']) > 1:
683 | return False
684 |
685 | return privkey_info.get('segwit', False)
686 | except ValidationError:
687 | return False
688 |
689 |
690 | def btc_get_privkey_address(privkey_info, **blockchain_opts):
691 | """
692 | Get the address for a given private key info bundle
693 | (be it multisig or singlesig)
694 |
695 | Return the address on success
696 | Raise exception on error
697 | """
698 |
699 | from .multisig import make_multisig_segwit_address_from_witness_script
700 |
701 | if btc_is_singlesig(privkey_info):
702 | return btc_address_reencode( ecdsalib.ecdsa_private_key(privkey_info).public_key().address() )
703 |
704 | if btc_is_multisig(privkey_info) or btc_is_singlesig_segwit(privkey_info):
705 | redeem_script = str(privkey_info['redeem_script'])
706 | return btc_make_p2sh_address(redeem_script)
707 |
708 | if btc_is_multisig_segwit(privkey_info):
709 | return make_multisig_segwit_address_from_witness_script(str(privkey_info['redeem_script']))
710 |
711 | raise ValueError("Invalid private key info")
712 |
--------------------------------------------------------------------------------
/virtualchain/lib/blockchain/bitcoin_blockchain/multisig.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | """
4 | Virtualchain
5 | ~~~~~
6 | copyright: (c) 2014-2015 by Halfmoon Labs, Inc.
7 | copyright: (c) 2016 by Blockstack.org
8 |
9 | This file is part of Virtualchain
10 |
11 | Virtualchain is free software: you can redistribute it and/or modify
12 | it under the terms of the GNU General Public License as published by
13 | the Free Software Foundation, either version 3 of the License, or
14 | (at your option) any later version.
15 |
16 | Virtualchain is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | GNU General Public License for more details.
20 | You should have received a copy of the GNU General Public License
21 | along with Virtualchain. If not, see .
22 | """
23 |
24 | import traceback
25 | import sys
26 |
27 | from .opcodes import *
28 | from .keys import *
29 | from .bits import *
30 | from ....lib import hashing
31 | from ....lib.config import get_logger
32 |
33 | import os
34 | import binascii
35 |
36 | log = get_logger('virtualchain')
37 |
38 | def make_multisig_script( pubs, m ):
39 | """
40 | Make a multisig scriptSig/witness script, as a hex string
41 | """
42 | return btc_script_serialize( [m] + pubs + [len(pubs)] + [OPCODE_VALUES['OP_CHECKMULTISIG']] )
43 |
44 |
45 | def make_multisig_address(pubs, m):
46 | """
47 | Make a multisig (p2sh) address, given the list of public keys (as hex strings) and the number required for validation
48 | """
49 | return btc_make_p2sh_address(make_multisig_script(pubs, m))
50 |
51 |
52 | def make_multisig_segwit_address(pubs, m):
53 | """
54 | make an address for p2sh-p2wsh multisig
55 | """
56 | script = make_multisig_script(pubs, m)
57 | return make_multisig_segwit_address_from_witness_script(script)
58 |
59 |
60 | def make_multisig_segwit_address_from_witness_script(script):
61 | """
62 | multisig witness script (p2sh-p2wsh) to address
63 | """
64 | script_hash = hashing.bin_sha256(script.decode('hex')).encode('hex')
65 | scriptsig_script = '0020' + script_hash
66 | addr = btc_make_p2sh_address(scriptsig_script)
67 | return addr
68 |
69 |
70 | def make_multisig_info( m, pks, compressed=None ):
71 | """
72 | Make a multisig address and redeem script.
73 | @m of the given @pks must sign.
74 |
75 | Return {'address': p2sh address, 'redeem_script': redeem script, 'private_keys': private keys, 'segwit': False}
76 | * privkeys will be hex-encoded
77 | * redeem_script will be hex-encoded
78 | """
79 |
80 | pubs = []
81 | privkeys = []
82 | for pk in pks:
83 | priv = None
84 | if compressed in [True, False]:
85 | priv = BitcoinPrivateKey(pk, compressed=compressed)
86 | else:
87 | priv = BitcoinPrivateKey(pk)
88 |
89 | priv_hex = priv.to_hex()
90 | pub_hex = priv.public_key().to_hex()
91 |
92 | privkeys.append(priv_hex)
93 | pubs.append(pub_hex)
94 |
95 | script = make_multisig_script(pubs, m)
96 | addr = btc_make_p2sh_address(script)
97 |
98 | return {
99 | 'address': addr,
100 | 'redeem_script': script,
101 | 'private_keys': privkeys,
102 | 'segwit': False,
103 | }
104 |
105 |
106 | def make_multisig_segwit_info( m, pks ):
107 | """
108 | Make either a p2sh-p2wpkh or p2sh-p2wsh
109 | redeem script and p2sh address.
110 |
111 | Return {'address': p2sh address, 'redeem_script': **the witness script**, 'private_keys': privkeys, 'segwit': True}
112 | * privkeys and redeem_script will be hex-encoded
113 | """
114 | pubs = []
115 | privkeys = []
116 | for pk in pks:
117 | priv = BitcoinPrivateKey(pk, compressed=True)
118 | priv_hex = priv.to_hex()
119 | pub_hex = priv.public_key().to_hex()
120 |
121 | privkeys.append(priv_hex)
122 | pubs.append(keylib.key_formatting.compress(pub_hex))
123 |
124 | script = None
125 |
126 | if len(pubs) == 1:
127 | if m != 1:
128 | raise ValueError("invalid m: len(pubkeys) == 1")
129 |
130 | # 1 pubkey means p2wpkh
131 | key_hash = hashing.bin_hash160(pubs[0].decode('hex')).encode('hex')
132 | script = '160014' + key_hash
133 | addr = btc_make_p2sh_address(script[2:])
134 |
135 | else:
136 | # 2+ pubkeys means p2wsh
137 | script = make_multisig_script(pubs, m)
138 | addr = make_multisig_segwit_address_from_witness_script(script)
139 |
140 | return {
141 | 'address': addr,
142 | 'redeem_script': script,
143 | 'private_keys': privkeys,
144 | 'segwit': True,
145 | 'm': m
146 | }
147 |
148 |
149 | def make_multisig_wallet( m, n ):
150 | """
151 | Create a bundle of information
152 | that can be used to generate an
153 | m-of-n multisig scriptsig.
154 | """
155 |
156 | if m <= 1 and n <= 1:
157 | raise ValueError("Invalid multisig parameters")
158 |
159 | pks = []
160 | for i in xrange(0, n):
161 | pk = BitcoinPrivateKey(compressed=True).to_wif()
162 | pks.append(pk)
163 |
164 | return make_multisig_info( m, pks )
165 |
166 |
167 | def make_segwit_info(privkey=None):
168 | """
169 | Create a bundle of information
170 | that can be used to generate
171 | a p2sh-p2wpkh transaction
172 | """
173 |
174 | if privkey is None:
175 | privkey = BitcoinPrivateKey(compressed=True).to_wif()
176 |
177 | return make_multisig_segwit_info(1, [privkey])
178 |
179 |
180 | def make_multisig_segwit_wallet( m, n ):
181 | """
182 | Create a bundle of information
183 | that can be used to generate an
184 | m-of-n multisig witness script.
185 | """
186 | pks = []
187 | for i in xrange(0, n):
188 | pk = BitcoinPrivateKey(compressed=True).to_wif()
189 | pks.append(pk)
190 |
191 | return make_multisig_segwit_info(m, pks)
192 |
193 |
194 | def parse_multisig_redeemscript( redeem_script_hex ):
195 | """
196 | Given a redeem script (as hex), extract multisig information.
197 | Return m, list of public keys on success
198 | Return (None, None)
199 | """
200 | script_parts = []
201 | redeem_script_hex = str(redeem_script_hex)
202 |
203 | try:
204 | script_parts = btc_script_deserialize(redeem_script_hex)
205 | except:
206 | if os.environ.get("BLOCKSTACK_TEST") == "1":
207 | traceback.print_exc()
208 |
209 | log.error("Invalid redeem script %s" % redeem_script_hex)
210 | return None, None
211 |
212 | try:
213 | assert len(script_parts) > 2
214 | assert script_parts[-1] == OPCODE_VALUES['OP_CHECKMULTISIG']
215 | script_parts.pop(-1)
216 |
217 | # get n
218 | n = script_parts.pop(-1)
219 | pubkeys = []
220 |
221 | # get m
222 | m = script_parts.pop(0)
223 |
224 | for i in xrange(0, n):
225 | pubk = script_parts.pop(0)
226 |
227 | # must be a public key
228 | BitcoinPublicKey(pubk)
229 | pubkeys.append(pubk)
230 |
231 | assert len(script_parts) == 0, "script_parts = %s" % script_parts
232 | return (m, pubkeys)
233 | except Exception, e:
234 | if os.environ.get("BLOCKSTACK_TEST") == "1":
235 | traceback.print_exc()
236 |
237 | log.error("Invalid redeem script %s (parses to %s)" % (redeem_script_hex, script_parts))
238 | return (None, None)
239 |
240 |
241 | def parse_multisig_scriptsig( scriptsig_hex ):
242 | """
243 | Given a scriptsig (as hex), extract the signatures.
244 | Return list of signatures on success
245 | Return None on error
246 | """
247 | try:
248 | script_parts = btc_script_deserialize(scriptsig_hex)
249 | except:
250 | if os.environ.get("BLOCKSTACK_TEST") == "1":
251 | traceback.print_exc()
252 |
253 | return None
254 |
255 | # sanity check
256 | return script_parts
257 |
258 |
259 |
--------------------------------------------------------------------------------
/virtualchain/lib/blockchain/bitcoin_blockchain/opcodes.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | """
4 | Virtualchain
5 | ~~~~~
6 | copyright: (c) 2014-2015 by Halfmoon Labs, Inc.
7 | copyright: (c) 2016 by Blockstack.org
8 |
9 | This file is part of Virtualchain
10 |
11 | Virtualchain is free software: you can redistribute it and/or modify
12 | it under the terms of the GNU General Public License as published by
13 | the Free Software Foundation, either version 3 of the License, or
14 | (at your option) any later version.
15 |
16 | Virtualchain is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | GNU General Public License for more details.
20 | You should have received a copy of the GNU General Public License
21 | along with Virtualchain. If not, see .
22 | """
23 |
24 | OPCODE_VALUES = {
25 | "OP_0": 0,
26 | "OP_PUSHDATA1": 76, # 0x4c
27 | "OP_PUSHDATA2": 77, # 0x4d
28 | "OP_PUSHDATA4": 78, # 0x4e
29 | "OP_1NEGATE": 79,
30 | "OP_RESERVED": 80,
31 | "OP_1": 81,
32 | "OP_2": 82,
33 | "OP_3": 83,
34 | "OP_4": 84,
35 | "OP_5": 85,
36 | "OP_6": 86,
37 | "OP_7": 87,
38 | "OP_8": 88,
39 | "OP_9": 89,
40 | "OP_10": 90,
41 | "OP_11": 91,
42 | "OP_12": 92,
43 | "OP_13": 93,
44 | "OP_14": 94,
45 | "OP_15": 95,
46 | "OP_16": 96,
47 | "OP_NOP": 97,
48 | "OP_VER": 98,
49 | "OP_IF": 99,
50 | "OP_NOTIF": 100,
51 | "OP_VERIF": 101,
52 | "OP_VERNOTIF": 102,
53 | "OP_ELSE": 103,
54 | "OP_ENDIF": 104,
55 | "OP_VERIFY": 105, # 0x69
56 | "OP_RETURN": 106, # 0x6a
57 | "OP_TOALTSTACK": 107,
58 | "OP_FROMALTSTACK": 108,
59 | "OP_2DROP": 109,
60 | "OP_2DUP": 110,
61 | "OP_3DUP": 111,
62 | "OP_2OVER": 112,
63 | "OP_2ROT": 113,
64 | "OP_2SWAP": 114,
65 | "OP_IFDUP": 115,
66 | "OP_DEPTH": 116,
67 | "OP_DROP": 117,
68 | "OP_DUP": 118,
69 | "OP_NIP": 119,
70 | "OP_OVER": 120,
71 | "OP_PICK": 121,
72 | "OP_ROLL": 122,
73 | "OP_ROT": 123,
74 | "OP_SWAP": 124,
75 | "OP_TUCK": 125,
76 | "OP_CAT": 126,
77 | "OP_SUBSTR": 127,
78 | "OP_LEFT": 128,
79 | "OP_RIGHT": 129,
80 | "OP_SIZE": 130,
81 | "OP_INVERT": 131,
82 | "OP_AND": 132,
83 | "OP_OR": 133,
84 | "OP_XOR": 134,
85 | "OP_EQUAL": 135, # 0x87
86 | "OP_EQUALVERIFY": 136, # 0x88
87 | "OP_RESERVED1": 137,
88 | "OP_RESERVED2": 138,
89 | "OP_1ADD": 139,
90 | "OP_1SUB": 140,
91 | "OP_2MUL": 141,
92 | "OP_2DIV": 142,
93 | "OP_NEGATE": 143,
94 | "OP_ABS": 144,
95 | "OP_NOT": 145,
96 | "OP_0NOTEQUAL": 146,
97 | "OP_ADD": 147,
98 | "OP_SUB": 148,
99 | "OP_MUL": 149,
100 | "OP_DIV": 150,
101 | "OP_MOD": 151,
102 | "OP_LSHIFT": 152,
103 | "OP_RSHIFT": 153,
104 | "OP_BOOLAND": 154,
105 | "OP_BOOLOR": 155,
106 | "OP_NUMEQUAL": 156,
107 | "OP_NUMEQUALVERIFY": 157,
108 | "OP_NUMNOTEQUAL": 158,
109 | "OP_LESSTHAN": 159,
110 | "OP_GREATERTHAN": 160,
111 | "OP_LESSTHANOREQUAL": 161,
112 | "OP_GREATERTHANOREQUAL": 162,
113 | "OP_MIN": 163,
114 | "OP_MAX": 164,
115 | "OP_WITHIN": 165,
116 | "OP_RIPEMD160": 166,
117 | "OP_SHA1": 167,
118 | "OP_SHA256": 168,
119 | "OP_HASH160": 169, # 0xa9
120 | "OP_HASH256": 170,
121 | "OP_CODESEPARATOR": 171,
122 | "OP_CHECKSIG": 172, # 0xac
123 | "OP_CHECKSIGVERIFY": 173, # 0xad
124 | "OP_CHECKMULTISIG": 174, # 0xae
125 | "OP_CHECKMULTISIGVERIFY": 175, # 0xaf
126 | "OP_NOP1": 176,
127 | "OP_NOP2": 177,
128 | "OP_NOP3": 178,
129 | "OP_NOP4": 179,
130 | "OP_NOP5": 180,
131 | "OP_NOP6": 181,
132 | "OP_NOP7": 182,
133 | "OP_NOP8": 183,
134 | "OP_NOP9": 184,
135 | "OP_NOP10": 185,
136 | "OP_PUBKEYHASH": 253, # 0xfd
137 | "OP_PUBKEY": 254, # 0xfe
138 | "OP_INVALIDOPCODE": 255
139 | }
140 |
141 | OPCODE_NAMES = dict([(v, k) for (k, v) in OPCODE_VALUES.items()])
142 |
143 |
--------------------------------------------------------------------------------
/virtualchain/lib/blockchain/bitcoin_blockchain/spv.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | """
3 | Parts of this source file are derived from code from Electrum
4 | (https://github.com/spesmilo/electrum), as of December 9, 2015.
5 |
6 | These parts are (c) 2015 by Thomas Voegtlin. All changes are
7 | subject to the following copyright.
8 | """
9 | """
10 | Virtualchain
11 | ~~~~~
12 | copyright: (c) 2014-2015 by Halfmoon Labs, Inc.
13 | copyright: (c) 2016 by Blockstack.org
14 |
15 | This file is part of Virtualchain
16 |
17 | Virtualchain is free software: you can redistribute it and/or modify
18 | it under the terms of the GNU General Public License as published by
19 | the Free Software Foundation, either version 3 of the License, or
20 | (at your option) any later version.
21 |
22 | Virtualchain is distributed in the hope that it will be useful,
23 | but WITHOUT ANY WARRANTY; without even the implied warranty of
24 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 | GNU General Public License for more details.
26 |
27 | You should have received a copy of the GNU General Public License
28 | along with Virtualchain. If not, see .
29 | """
30 |
31 |
32 | import socket
33 | import os
34 | import sys
35 | import time
36 | import logging
37 |
38 | import protocoin
39 | import protocoin.exceptions
40 | from protocoin.clients import *
41 | from protocoin.serializers import *
42 | from protocoin.fields import *
43 | from protocoin.exceptions import *
44 |
45 | from keys import version_byte as VERSION_BYTE
46 |
47 | import bits
48 |
49 | from ....lib import hashing
50 |
51 | DEBUG = True
52 |
53 | try:
54 | from ....lib.config import get_logger
55 | except:
56 | def get_logger(name=None):
57 | """
58 | Get virtualchain's logger
59 | """
60 |
61 | level = logging.CRITICAL
62 | if DEBUG:
63 | logging.disable(logging.NOTSET)
64 | level = logging.DEBUG
65 |
66 | if name is None:
67 | name = ""
68 | level = logging.CRITICAL
69 |
70 | log = logging.getLogger(name=name)
71 | log.setLevel( level )
72 | console = logging.StreamHandler()
73 | console.setLevel( level )
74 | log_format = ('[%(asctime)s] [%(levelname)s] [%(module)s:%(lineno)d] (' + str(os.getpid()) + ') %(message)s' if DEBUG else '%(message)s')
75 | formatter = logging.Formatter( log_format )
76 | console.setFormatter(formatter)
77 | log.propagate = False
78 |
79 | if len(log.handlers) > 0:
80 | for i in xrange(0, len(log.handlers)):
81 | log.handlers.pop(0)
82 |
83 | log.addHandler(console)
84 | return log
85 |
86 |
87 | log = get_logger("virtualchain-bitcoin-spv")
88 |
89 | BLOCK_HEADER_SIZE = 81
90 |
91 | GENESIS_BLOCK_HASH = None
92 | GENESIS_BLOCK_MERKLE_ROOT = None
93 | USE_MAINNET = False
94 | USE_TESTNET = False
95 |
96 | GENESIS_BLOCK_HASH_MAINNET = "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"
97 | GENESIS_BLOCK_MERKLE_ROOT_MAINNET = "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"
98 |
99 | GENESIS_BLOCK_HASH_TESTNET = "0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206"
100 | GENESIS_BLOCK_MERKLE_ROOT_TESTNET = "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"
101 |
102 | if VERSION_BYTE == 0:
103 | # mainnet
104 | log.debug("Using mainnet")
105 | USE_MAINNET = True
106 | GENESIS_BLOCK_HASH = GENESIS_BLOCK_HASH_MAINNET
107 | GENESIS_BLOCK_MERKLE_ROOT = GENESIS_BLOCK_MERKLE_ROOT_MAINNET
108 |
109 | elif VERSION_BYTE == 111:
110 | # testnet
111 | log.debug("Using testnet/regtest")
112 | USE_TESTNET = True
113 | GENESIS_BLOCK_HASH = GENESIS_BLOCK_HASH_TESTNET
114 | GENESIS_BLOCK_MERKLE_ROOT = GENESIS_BLOCK_HASH_TESTNET
115 | else:
116 | raise Exception("Unknown version byte %s" % VERSION_BYTE)
117 |
118 | BLOCK_DIFFICULTY_CHUNK_SIZE = 2016
119 | BLOCK_DIFFICULTY_INTERVAL = 14*24*60*60 # two weeks, in seconds
120 |
121 |
122 | class BlockHash(SerializableMessage):
123 | """
124 | Block hash to request
125 | """
126 | def __init__(self):
127 | self.block_hash = None
128 |
129 | def __repr__(self):
130 | return "<%s %s>" % (self.__class__.__name__, "%064x" % self.block_hash)
131 |
132 |
133 | class GetHeaders(SerializableMessage):
134 | """
135 | getheaders message
136 | """
137 | command = "getheaders"
138 |
139 | def __init__(self):
140 | self.version = PROTOCOL_VERSION
141 | self.block_hashes = []
142 | self.hash_stop = 0
143 |
144 | def add_block_hash( self, block_hash ):
145 | """
146 | Append up to 2000 block hashes for which to get headers.
147 | """
148 | if len(self.block_hashes) > 2000:
149 | raise Exception("A getheaders request cannot have over 2000 block hashes")
150 |
151 | hash_num = int("0x" + block_hash, 16)
152 |
153 | bh = BlockHash()
154 | bh.block_hash = hash_num
155 |
156 | self.block_hashes.append( bh )
157 | self.hash_stop = hash_num
158 |
159 | def num_block_hashes( self ):
160 | """
161 | Get the number of block headers to request
162 | """
163 | return len(self.block_hashes)
164 |
165 | def __repr__(self):
166 | return "<%s block_hashes=[%s]>" % (self.__class__.__name__, ",".join([str(h) for h in self.block_hashes]))
167 |
168 |
169 | class BlockHashSerializer( Serializer ):
170 | """
171 | Serialization class for a BlockHash
172 | """
173 | model_class = BlockHash
174 | block_hash = Hash()
175 |
176 |
177 | class GetHeadersSerializer( Serializer ):
178 | """
179 | Serialization class for a GetHeaders
180 | """
181 | model_class = GetHeaders
182 | version = UInt32LEField()
183 | block_hashes = ListField(BlockHashSerializer)
184 | hash_stop = Hash()
185 |
186 |
187 | # monkey-patch
188 | protocoin.serializers.MESSAGE_MAPPING['getheaders'] = GetHeadersSerializer
189 |
190 |
191 | class BlockHeaderClient( BitcoinBasicClient ):
192 | """
193 | Client to fetch and store block headers.
194 | """
195 |
196 | coin = None
197 |
198 | def __init__(self, socket, headers_path, first_block_hash, last_block_id ):
199 |
200 | if VERSION_BYTE == 0:
201 | self.coin = "bitcoin"
202 | else:
203 | self.coin = "bitcoin_testnet"
204 |
205 | super(BlockHeaderClient, self).__init__(socket)
206 | self.path = headers_path
207 | self.last_block_id = last_block_id
208 | self.finished = False
209 | self.verack = False
210 | self.first_block_hash = first_block_hash
211 |
212 |
213 | def loop_exit( self ):
214 | """
215 | Stop the loop
216 | """
217 | self.finished = True
218 | self.close_stream()
219 |
220 |
221 | def run( self ):
222 | """
223 | Interact with the blockchain peer,
224 | until we get a socket error or we
225 | exit the loop explicitly.
226 | Return True on success
227 | Raise on error
228 | """
229 |
230 | self.handshake()
231 |
232 | try:
233 | self.loop()
234 | except socket.error, se:
235 | if self.finished:
236 | return True
237 | else:
238 | raise
239 |
240 |
241 | def hash_to_string( self, hash_int ):
242 | return "%064x" % hash_int
243 |
244 |
245 | def handle_headers( self, message_header, block_headers_message ):
246 | """
247 | Handle a 'headers' message.
248 | NOTE: we request headers in order, so we will expect to receive them in order here.
249 | Verify that we do so.
250 | """
251 | log.debug("handle headers (%s)" % len(block_headers_message.headers))
252 |
253 | block_headers = block_headers_message.headers
254 |
255 | serializer = BlockHeaderSerializer()
256 |
257 | # verify that the local header chain connects to this sequence
258 | current_height = SPVClient.height( self.path )
259 | if current_height is None:
260 | assert USE_TESTNET
261 | current_height = -1
262 |
263 | assert (current_height >= 0 and USE_MAINNET) or USE_TESTNET, "Invalid height %s" % current_height
264 |
265 | last_header = None
266 |
267 | if current_height >= 0:
268 | last_header = SPVClient.read_header( self.path, current_height )
269 | log.debug("Receive %s headers (%s to %s)" % (len(block_headers), current_height, current_height + len(block_headers)))
270 |
271 | else:
272 | # first testnet header
273 | log.debug("Receive %s testnet headers (%s to %s)" % (len(block_headers), current_height + 1, current_height + len(block_headers)))
274 | last_header = {
275 | "version": block_headers[0].version,
276 | "prev_block_hash": "%064x" % block_headers[0].prev_block,
277 | "merkle_root": "%064x" % block_headers[0].merkle_root,
278 | "timestamp": block_headers[0].timestamp,
279 | "bits": block_headers[0].bits,
280 | "nonce": block_headers[0].nonce,
281 | "hash": block_headers[0].calculate_hash()
282 | }
283 |
284 | if (USE_MAINNET or (USE_TESTNET and current_height >= 0)) and last_header['hash'] != self.hash_to_string(block_headers[0].prev_block):
285 | raise Exception("Received discontinuous block header at height %s: hash '%s' (expected '%s')" % \
286 | (current_height,
287 | self.hash_to_string(block_headers[0].prev_block),
288 | last_header['hash'] ))
289 |
290 | header_start = 1
291 | if USE_TESTNET and current_height < 0:
292 | # save initial header
293 | header_start = 0
294 |
295 | # verify that this sequence of headers constitutes a hash chain
296 | for i in xrange(header_start, len(block_headers)):
297 | prev_block_hash = self.hash_to_string(block_headers[i].prev_block)
298 | if i > 0 and prev_block_hash != block_headers[i-1].calculate_hash():
299 | raise Exception("Block '%s' is not continuous with block '%s'" % \
300 | prev_block_hash,
301 | block_headers[i-1].calculate_hash())
302 |
303 | if current_height < 0:
304 | # save the first header
305 | if not os.path.exists(self.path):
306 | with open(self.path, "wb") as f:
307 | block_header_serializer = BlockHeaderSerializer()
308 | bin_data = block_header_serializer.serialize( block_headers[0] )
309 | f.write( bin_data )
310 |
311 | # got all headers, including the first
312 | current_height = 0
313 |
314 | # insert into to local headers database
315 | next_block_id = current_height + 1
316 | for block_header in block_headers:
317 | with open(self.path, "rb+") as f:
318 |
319 | # omit tx count
320 | block_header.txns_count = 0
321 | bin_data = serializer.serialize( block_header )
322 |
323 | if len(bin_data) != BLOCK_HEADER_SIZE:
324 | raise Exception("Block %s (%s) has %s-byte header" % (next_block_id, block_header.calculate_hash(), len(bin_data)))
325 |
326 | # NOTE: the fact that we use seek + write ensures that we can:
327 | # * restart synchronizing at any point
328 | # * allow multiple processes to work on the chain safely (even if they're duplicating effort)
329 | f.seek( BLOCK_HEADER_SIZE * next_block_id, os.SEEK_SET )
330 | f.write( bin_data )
331 |
332 | if SPVClient.height( self.path ) >= self.last_block_id - 1:
333 | break
334 |
335 | next_block_id += 1
336 |
337 | current_block_id = SPVClient.height( self.path )
338 | if current_block_id >= self.last_block_id - 1:
339 | # got all headers
340 | self.loop_exit()
341 | return
342 |
343 | prev_block_header = SPVClient.read_header( self.path, current_block_id )
344 | prev_block_hash = prev_block_header['hash']
345 | self.send_getheaders( prev_block_hash )
346 |
347 |
348 | def send_getheaders( self, prev_block_hash ):
349 | """
350 | Request block headers from a particular block hash.
351 | Will receive up to 2000 blocks, starting with the block *after*
352 | the given block hash (prev_block_hash)
353 | """
354 |
355 | getheaders = GetHeaders()
356 |
357 | getheaders.add_block_hash( prev_block_hash )
358 |
359 | log.debug("send getheaders")
360 | self.send_message( getheaders )
361 |
362 |
363 | def handshake(self):
364 | """
365 | This method will implement the handshake of the
366 | Bitcoin protocol. It will send the Version message,
367 | and block until it receives a VerAck
368 | """
369 | log.debug("handshake (version %s)" % PROTOCOL_VERSION)
370 | version = Version()
371 | version.services = 0 # can't send blocks
372 | log.debug("send Version")
373 | self.send_message(version)
374 |
375 |
376 | def handle_version(self, message_header, message):
377 | """
378 | This method will handle the Version message and
379 | will send a VerAck message when it receives the
380 | Version message.
381 |
382 | :param message_header: The Version message header
383 | :param message: The Version message
384 | """
385 | log.debug("handle version")
386 | verack = VerAck()
387 | log.debug("send VerAck")
388 | self.send_message(verack)
389 | self.verack = True
390 |
391 | # begin!
392 | self.send_getheaders( self.first_block_hash )
393 |
394 |
395 | def handle_ping(self, message_header, message):
396 | """
397 | This method will handle the Ping message and then
398 | will answer every Ping message with a Pong message
399 | using the nonce received.
400 |
401 | :param message_header: The header of the Ping message
402 | :param message: The Ping message
403 | """
404 | log.debug("handle ping")
405 | pong = Pong()
406 | pong.nonce = message.nonce
407 | log.debug("send pong")
408 | self.send_message(pong)
409 |
410 |
411 | class SPVClient(object):
412 | """
413 | Simplified Payment Verification client.
414 | Accesses locally-stored headers obtained by BlockHeaderClient
415 | to verify and synchronize them with the blockchain.
416 | """
417 |
418 | def __init__(self, path):
419 | SPVClient.init( path )
420 |
421 |
422 | @classmethod
423 | def init(cls, path):
424 | """
425 | Set up an SPV client.
426 | If the locally-stored headers do not exist, then
427 | create a stub headers file with the genesis block information.
428 | """
429 | if not os.path.exists( path ):
430 |
431 | block_header_serializer = BlockHeaderSerializer()
432 | genesis_block_header = BlockHeader()
433 |
434 | if USE_MAINNET:
435 | # we know the mainnet block header
436 | # but we don't know the testnet/regtest block header
437 | genesis_block_header.version = 1
438 | genesis_block_header.prev_block = 0
439 | genesis_block_header.merkle_root = int(GENESIS_BLOCK_MERKLE_ROOT, 16 )
440 | genesis_block_header.timestamp = 1231006505
441 | genesis_block_header.bits = int( "1d00ffff", 16 )
442 | genesis_block_header.nonce = 2083236893
443 | genesis_block_header.txns_count = 0
444 |
445 | with open(path, "wb") as f:
446 | bin_data = block_header_serializer.serialize( genesis_block_header )
447 | f.write( bin_data )
448 |
449 |
450 | @classmethod
451 | def height(cls, path):
452 | """
453 | Get the locally-stored block height
454 | """
455 | if os.path.exists( path ):
456 | sb = os.stat( path )
457 | h = (sb.st_size / BLOCK_HEADER_SIZE) - 1
458 | return h
459 | else:
460 | return None
461 |
462 |
463 | @classmethod
464 | def read_header_at( cls, f):
465 | """
466 | Given an open file-like object, read a block header
467 | from it and return it as a dict containing:
468 | * version (int)
469 | * prev_block_hash (hex str)
470 | * merkle_root (hex str)
471 | * timestamp (int)
472 | * bits (int)
473 | * nonce (ini)
474 | * hash (hex str)
475 | """
476 | header_parser = BlockHeaderSerializer()
477 | hdr = header_parser.deserialize( f )
478 | h = {}
479 | h['version'] = hdr.version
480 | h['prev_block_hash'] = "%064x" % hdr.prev_block
481 | h['merkle_root'] = "%064x" % hdr.merkle_root
482 | h['timestamp'] = hdr.timestamp
483 | h['bits'] = hdr.bits
484 | h['nonce'] = hdr.nonce
485 | h['hash'] = hdr.calculate_hash()
486 | return h
487 |
488 |
489 | @classmethod
490 | def load_header_chain( cls, chain_path ):
491 | """
492 | Load the header chain from disk.
493 | Each chain element will be a dictionary with:
494 | *
495 | """
496 |
497 | header_parser = BlockHeaderSerializer()
498 | chain = []
499 | height = 0
500 | with open(chain_path, "rb") as f:
501 |
502 | h = SPVClient.read_header_at( f )
503 | h['block_height'] = height
504 |
505 | height += 1
506 | chain.append(h)
507 |
508 | return chain
509 |
510 |
511 | @classmethod
512 | def read_header(cls, headers_path, block_height, allow_none=False):
513 | """
514 | Get a block header at a particular height from disk.
515 | Return the header if found
516 | Return None if not.
517 | """
518 | if os.path.exists(headers_path):
519 |
520 | header_parser = BlockHeaderSerializer()
521 | sb = os.stat( headers_path )
522 | if sb.st_size < BLOCK_HEADER_SIZE * block_height:
523 | # beyond EOF
524 | if allow_none:
525 | return None
526 | else:
527 | raise Exception('EOF on block headers')
528 |
529 | with open( headers_path, "rb" ) as f:
530 | f.seek( block_height * BLOCK_HEADER_SIZE, os.SEEK_SET )
531 | hdr = SPVClient.read_header_at( f )
532 |
533 | return hdr
534 | else:
535 | if allow_none:
536 | return None
537 | else:
538 | raise Exception('No such file or directory: {}'.format(headers_path))
539 |
540 |
541 | @classmethod
542 | def get_target(cls, path, index, chain=None):
543 | """
544 | Calculate the target difficulty at a particular difficulty interval (index).
545 | Return (bits, target) on success
546 | """
547 | if chain is None:
548 | chain = [] # Do not use mutables as default values!
549 |
550 | max_target = 0x00000000FFFF0000000000000000000000000000000000000000000000000000
551 | if index == 0:
552 | return 0x1d00ffff, max_target
553 |
554 | first = SPVClient.read_header( path, (index-1)*BLOCK_DIFFICULTY_CHUNK_SIZE)
555 | last = SPVClient.read_header( path, index*BLOCK_DIFFICULTY_CHUNK_SIZE - 1, allow_none=True)
556 | if last is None:
557 | for h in chain:
558 | if h.get('block_height') == index*BLOCK_DIFFICULTY_CHUNK_SIZE - 1:
559 | last = h
560 |
561 | nActualTimespan = last.get('timestamp') - first.get('timestamp')
562 | nTargetTimespan = BLOCK_DIFFICULTY_INTERVAL
563 | nActualTimespan = max(nActualTimespan, nTargetTimespan/4)
564 | nActualTimespan = min(nActualTimespan, nTargetTimespan*4)
565 |
566 | bits = last.get('bits')
567 | # convert to bignum
568 | MM = 256*256*256
569 | a = bits%MM
570 | if a < 0x8000:
571 | a *= 256
572 | target = (a) * pow(2, 8 * (bits/MM - 3))
573 |
574 | # new target
575 | new_target = min( max_target, (target * nActualTimespan)/nTargetTimespan )
576 |
577 | # convert it to bits
578 | c = ("%064X"%new_target)[2:]
579 | i = 31
580 | while c[0:2]=="00":
581 | c = c[2:]
582 | i -= 1
583 |
584 | c = int('0x'+c[0:6],16)
585 | if c >= 0x800000:
586 | c /= 256
587 | i += 1
588 |
589 | new_bits = c + MM * i
590 | return new_bits, new_target
591 |
592 |
593 | @classmethod
594 | def block_header_verify( cls, headers_path, block_id, block_hash, block_header ):
595 | """
596 | Given the block's numeric ID, its hash, and the bitcoind-returned block_data,
597 | use the SPV header chain to verify the block's integrity.
598 |
599 | block_header must be a dict with the following structure:
600 | * version: protocol version (int)
601 | * prevhash: previous block hash (hex str)
602 | * merkleroot: block Merkle root (hex str)
603 | * timestamp: UNIX time stamp (int)
604 | * bits: difficulty bits (hex str)
605 | * nonce: PoW nonce (int)
606 | * hash: block hash (hex str)
607 | (i.e. the format that the reference bitcoind returns via JSON RPC)
608 |
609 | Return True on success
610 | Return False on error
611 | """
612 | prev_header = cls.read_header( headers_path, block_id - 1 )
613 | prev_hash = prev_header['hash']
614 | return bits.block_header_verify( block_header, prev_hash, block_hash )
615 |
616 |
617 | @classmethod
618 | def block_verify( cls, verified_block_header, block_txids ):
619 | """
620 | Given the block's verified header structure (see block_header_verify) and
621 | its list of transaction IDs (as hex strings), verify that the transaction IDs are legit.
622 |
623 | Return True on success
624 | Return False on error.
625 | """
626 |
627 | block_data = {
628 | 'merkleroot': verified_block_header['merkleroot'],
629 | 'tx': block_txids
630 | }
631 |
632 | return bits.block_verify( block_data )
633 |
634 |
635 | @classmethod
636 | def tx_hash( cls, tx ):
637 | """
638 | Calculate the hash of a transction structure given by bitcoind
639 | """
640 | tx_hex = bits.btc_bitcoind_tx_serialize( tx )
641 | tx_hash = hashing.bin_double_sha256(tx_hex.decode('hex'))[::-1].encode('hex')
642 | return tx_hash
643 |
644 |
645 | @classmethod
646 | def tx_verify( cls, verified_block_txids, tx ):
647 | """
648 | Given the block's verified block txids, verify that a transaction is legit.
649 | @tx must be a dict with the following fields:
650 | * locktime: int
651 | * version: int
652 | * vin: list of dicts with:
653 | * vout: int,
654 | * hash: hex str
655 | * sequence: int (optional)
656 | * scriptSig: dict with:
657 | * hex: hex str
658 | * vout: list of dicts with:
659 | * value: float
660 | * scriptPubKey: dict with:
661 | * hex: hex str
662 | """
663 | tx_hash = cls.tx_hash( tx )
664 | return tx_hash in verified_block_txids
665 |
666 |
667 | @classmethod
668 | def tx_index( cls, verified_block_txids, verified_tx ):
669 | """
670 | Given a block's verified block txids and a verified transaction,
671 | find out where it is in the list of txids (i.e. what's its index)?
672 | """
673 | tx_hash = cls.tx_hash( verified_tx )
674 | return verified_block_txids.index( tx_hash )
675 |
676 |
677 | @classmethod
678 | def block_header_index( cls, path, block_header ):
679 | """
680 | Given a block's serialized header, go and find out what its
681 | block ID is (if it is present at all).
682 |
683 | Return the >= 0 index on success
684 | Return -1 if not found.
685 |
686 | NOTE: this is slow
687 | """
688 | with open( path, "rb" ) as f:
689 | chain_raw = f.read()
690 |
691 | for blk in xrange(0, len(chain_raw) / (BLOCK_HEADER_SIZE)):
692 | if chain_raw[blk * BLOCK_HEADER_SIZE : blk * BLOCK_HEADER_SIZE + BLOCK_HEADER_SIZE] == block_header:
693 | return blk
694 |
695 | return -1
696 |
697 |
698 | @classmethod
699 | def verify_header_chain(cls, path, chain=None):
700 | """
701 | Verify that a given chain of block headers
702 | has sufficient proof of work.
703 | """
704 | if chain is None:
705 | chain = SPVClient.load_header_chain( path )
706 |
707 | prev_header = chain[0]
708 |
709 | for i in xrange(1, len(chain)):
710 | header = chain[i]
711 | height = header.get('block_height')
712 | prev_hash = prev_header.get('hash')
713 | if prev_hash != header.get('prev_block_hash'):
714 | log.error("prev hash mismatch: %s vs %s" % (prev_hash, header.get('prev_block_hash')))
715 | return False
716 |
717 | bits, target = SPVClient.get_target( path, height/BLOCK_DIFFICULTY_CHUNK_SIZE, chain)
718 | if bits != header.get('bits'):
719 | log.error("bits mismatch: %s vs %s" % (bits, header.get('bits')))
720 | return False
721 |
722 | _hash = header.get('hash')
723 | if int('0x'+_hash, 16) > target:
724 | log.error("insufficient proof of work: %s vs target %s" % (int('0x'+_hash, 16), target))
725 | return False
726 |
727 | prev_header = header
728 |
729 | return True
730 |
731 |
732 | @classmethod
733 | def sync_header_chain(cls, path, bitcoind_server, last_block_id ):
734 | """
735 | Synchronize our local block headers up to the last block ID given.
736 | @last_block_id is *inclusive*
737 | @bitcoind_server is host:port or just host
738 | """
739 | current_block_id = SPVClient.height( path )
740 | if current_block_id is None:
741 | assert USE_TESTNET
742 | current_block_id = -1
743 |
744 | assert (current_block_id >= 0 and USE_MAINNET) or USE_TESTNET
745 |
746 | if current_block_id < last_block_id:
747 |
748 | if USE_MAINNET:
749 | log.debug("Synchronize %s to %s" % (current_block_id, last_block_id))
750 | else:
751 | log.debug("Synchronize testnet %s to %s" % (current_block_id + 1, last_block_id ))
752 |
753 | # need to sync
754 | if current_block_id >= 0:
755 | prev_block_header = SPVClient.read_header( path, current_block_id )
756 | prev_block_hash = prev_block_header['hash']
757 |
758 | else:
759 | # can only happen when in testnet
760 | prev_block_hash = GENESIS_BLOCK_HASH_TESTNET
761 |
762 | # connect
763 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
764 |
765 | # timeout (10 min)
766 | sock.settimeout(600)
767 |
768 | bitcoind_port = 8333
769 | if ":" in bitcoind_server:
770 | p = bitcoind_server.split(":")
771 | bitcoind_server = p[0]
772 | bitcoind_port = int(p[1])
773 |
774 | log.debug("connect to %s:%s" % (bitcoind_server, bitcoind_port))
775 | sock.connect( (bitcoind_server, bitcoind_port) )
776 |
777 | client = BlockHeaderClient( sock, path, prev_block_hash, last_block_id )
778 |
779 | # get headers
780 | client.run()
781 |
782 | # verify headers
783 | if SPVClient.height(path) < last_block_id:
784 | raise Exception("Did not receive all headers up to %s (only got %s)" % (last_block_id, SPVClient.height(path)))
785 |
786 | # defensive: make sure it's *exactly* that many blocks
787 |
788 | rc = SPVClient.verify_header_chain( path )
789 | if not rc:
790 | raise Exception("Failed to verify headers (stored in '%s')" % path)
791 |
792 | log.debug("synced headers from %s to %s in %s" % (current_block_id, last_block_id, path))
793 | return True
794 |
795 |
796 | if __name__ == "__main__":
797 | # test synchonize headers
798 | try:
799 | bitcoind_server = sys.argv[1]
800 | headers_path = sys.argv[2]
801 | height = int(sys.argv[3])
802 | except:
803 | print >> sys.stderr, "Usage: %s bitcoind_server headers_path blockchain_height" % sys.argv[0]
804 | sys.exit(0)
805 |
806 | log.setLevel(logging.DEBUG)
807 | SPVClient.init( headers_path )
808 | rc = SPVClient.sync_header_chain( headers_path, bitcoind_server, height )
809 | if rc:
810 | print "Headers are up to date with %s and seem to have sufficient proof-of-work" % height
811 |
--------------------------------------------------------------------------------
/virtualchain/lib/blockchain/keys.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | """
4 | Virtualchain
5 | ~~~~~
6 | copyright: (c) 2014 by Halfmoon Labs, Inc.
7 | copyright: (c) 2015-2018 by Blockstack.org
8 |
9 | This file is part of Virtualchain
10 |
11 | Virtualchain is free software: you can redistribute it and/or modify
12 | it under the terms of the GNU General Public License as published by
13 | the Free Software Foundation, either version 3 of the License, or
14 | (at your option) any later version.
15 |
16 | Virtualchain is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | GNU General Public License for more details.
20 | You should have received a copy of the GNU General Public License
21 | along with Virtualchain. If not, see .
22 | """
23 |
24 | from bitcoin_blockchain.keys import btc_is_multisig, btc_is_multisig_address, \
25 | btc_is_multisig_script, btc_is_singlesig, btc_get_singlesig_privkey, \
26 | btc_is_singlesig_address, btc_get_privkey_address
27 |
28 | def is_multisig(privkey_info, blockchain='bitcoin', **blockchain_opts):
29 | """
30 | Is the given private key bundle a multisig bundle?
31 | """
32 | if blockchain == 'bitcoin':
33 | return btc_is_multisig(privkey_info, **blockchain_opts)
34 | else:
35 | raise ValueError('Unknown blockchain "{}"'.format(blockchain))
36 |
37 |
38 | def is_multisig_address(addr, blockchain='bitcoin', **blockchain_opts):
39 | """
40 | Is the given address a multisig address?
41 | """
42 | if blockchain == 'bitcoin':
43 | return btc_is_multisig_address(addr, **blockchain_opts)
44 | else:
45 | raise ValueError('Unknown blockchain "{}"'.format(blockchain))
46 |
47 |
48 | def is_multisig_script(script, blockchain='bitcoin', **blockchain_opts):
49 | """
50 | Is the given script a multisig script?
51 | """
52 | if blockchain == 'bitcoin':
53 | return btc_is_multisig_script(script, **blockchain_opts)
54 | else:
55 | raise ValueError('Unknown blockchain "{}"'.format(blockchain))
56 |
57 |
58 | def is_singlesig(privkey_info, blockchain='bitcoin', **blockchain_opts):
59 | """
60 | Is the given private key bundle a single-sig key bundle?
61 | """
62 | if blockchain == 'bitcoin':
63 | return btc_is_singlesig(privkey_info, **blockchain_opts)
64 | else:
65 | raise ValueError('Unknown blockchain "{}"'.format(blockchain))
66 |
67 |
68 | def get_singlesig_privkey(privkey_info, blockchain='bitcoin', **blockchain_opts):
69 | """
70 | Given a private key bundle, get the (single) private key
71 | """
72 | if blockchain == 'bitcoin':
73 | return btc_get_singlesig_privkey(privkey_info, **blockchain_opts)
74 | else:
75 | raise ValueError('Unknown blockchain "{}"'.format(blockchain))
76 |
77 |
78 | def is_singlesig_address(addr, blockchain='bitcoin', **blockchain_opts):
79 | """
80 | Is the given address a single-sig address?
81 | """
82 | if blockchain == 'bitcoin':
83 | return btc_is_singlesig_address(addr, **blockchain_opts)
84 | else:
85 | raise ValueError('Unknown blockchain "{}"'.format(blockchain))
86 |
87 |
88 | def get_privkey_address(privkey_info, blockchain='bitcoin', **blockchain_opts):
89 | """
90 | Get the address from a private key bundle
91 | """
92 | if blockchain == 'bitcoin':
93 | return btc_get_privkey_address(privkey_info, **blockchain_opts)
94 | else:
95 | raise ValueError('Unknown blockchain "{}"'.format(blockchain))
96 |
97 |
--------------------------------------------------------------------------------
/virtualchain/lib/blockchain/scripts.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | """
4 | Virtualchain
5 | ~~~~~
6 | copyright: (c) 2014 by Halfmoon Labs, Inc.
7 | copyright: (c) 2015-2018 by Blockstack.org
8 |
9 | This file is part of Virtualchain
10 |
11 | Virtualchain is free software: you can redistribute it and/or modify
12 | it under the terms of the GNU General Public License as published by
13 | the Free Software Foundation, either version 3 of the License, or
14 | (at your option) any later version.
15 |
16 | Virtualchain is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | GNU General Public License for more details.
20 | You should have received a copy of the GNU General Public License
21 | along with Virtualchain. If not, see .
22 | """
23 | from bitcoin_blockchain import btc_make_payment_script, btc_make_data_script, btc_script_hex_to_address
24 |
25 | def script_hex_to_address( script_hex, blockchain='bitcoin', **blockchain_opts):
26 | """
27 | High-level API call (meant to be blockchain agnostic)
28 | Examine a script (hex-encoded) and extract an address.
29 | Return the address on success
30 | Return None on error
31 | """
32 | if blockchain == 'bitcoin':
33 | return btc_script_hex_to_address(script_hex, **blockchain_opts)
34 | else:
35 | raise ValueError("Unknown blockchain '{}'".format(blockchain))
36 |
37 |
38 | def make_payment_script(address, blockchain='bitcoin', **blockchain_opts):
39 | """
40 | High-level API call (meant to be blockchain agnostic)
41 | Make a pay-to-address script.
42 | """
43 |
44 | if blockchain == 'bitcoin':
45 | return btc_make_payment_script(address, **blockchain_opts)
46 | else:
47 | raise ValueError("Unknown blockchain '{}'".format(blockchain))
48 |
49 |
50 | def make_data_script( data, blockchain='bitcoin', **blockchain_opts):
51 | """
52 | High-level API call (meant to be blockchain agnostic)
53 | Make a data-bearing transaction output.
54 | Data must be a hex string
55 | Returns a hex string.
56 | """
57 | if blockchain == 'bitcoin':
58 | return btc_make_data_script(data, **blockchain_opts)
59 | else:
60 | raise ValueError("Unknown blockchain '{}'".format(blockchain))
61 |
--------------------------------------------------------------------------------
/virtualchain/lib/blockchain/session.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | """
4 | Virtualchain
5 | ~~~~~
6 | copyright: (c) 2014 by Halfmoon Labs, Inc.
7 | copyright: (c) 2015 by Blockstack.org
8 |
9 | This file is part of Virtualchain
10 |
11 | Virtualchain is free software: you can redistribute it and/or modify
12 | it under the terms of the GNU General Public License as published by
13 | the Free Software Foundation, either version 3 of the License, or
14 | (at your option) any later version.
15 |
16 | Virtualchain is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | GNU General Public License for more details.
20 | You should have received a copy of the GNU General Public License
21 | along with Virtualchain. If not, see .
22 | """
23 |
24 | import logging
25 | import os
26 | import httplib
27 | import ssl
28 | import socket
29 |
30 | from ..config import get_logger, get_bitcoind_config
31 |
32 | log = get_logger("virtualchain_session")
33 |
34 | # various SSL compat measures
35 | create_ssl_authproxy = False
36 | do_wrap_socket = False
37 |
38 | if hasattr( ssl, "_create_unverified_context" ):
39 | ssl._create_default_https_context = ssl._create_unverified_context
40 | create_ssl_authproxy = True
41 |
42 | if not hasattr( ssl, "create_default_context" ):
43 | create_ssl_authproxy = False
44 | do_wrap_socket = True
45 |
46 |
47 | # disable debug logging from bitcoinrpc
48 | bitcoinrpc_logger = logging.getLogger("BitcoinRPC")
49 | bitcoinrpc_logger.setLevel(logging.CRITICAL)
50 |
51 | class BitcoindConnection( httplib.HTTPSConnection ):
52 | """
53 | Wrapped SSL connection, if we can't use SSLContext.
54 | """
55 |
56 | def __init__(self, host, port, timeout=None ):
57 |
58 | httplib.HTTPSConnection.__init__(self, host, port )
59 | self.timeout = timeout
60 |
61 | def connect( self ):
62 |
63 | sock = socket.create_connection((self.host, self.port), self.timeout)
64 | if self._tunnel_host:
65 | self.sock = sock
66 | self._tunnel()
67 |
68 | self.sock = ssl.wrap_socket( sock, cert_reqs=ssl.CERT_NONE )
69 |
70 |
71 | def is_int(i):
72 | """
73 | Is the given object a long or an int?
74 | """
75 | return isinstance(i, (int,long))
76 |
77 |
78 | def is_valid_int(i):
79 | """
80 | Is the given object an integer?
81 | """
82 | if is_int(i):
83 | return True
84 | elif isinstance(i, str):
85 | try:
86 | int_i = int(i)
87 | except:
88 | return False
89 | else:
90 | return True
91 | return False
92 |
93 |
94 | def create_bitcoind_connection( rpc_username, rpc_password, server, port, use_https, timeout ):
95 | """
96 | Creates an RPC client to a bitcoind instance.
97 | It will have ".opts" defined as a member, which will be a dict that stores the above connection options.
98 | """
99 |
100 | from .bitcoin_blockchain import AuthServiceProxy
101 |
102 | global do_wrap_socket, create_ssl_authproxy
103 |
104 | log.debug("[%s] Connect to bitcoind at %s://%s@%s:%s, timeout=%s" % (os.getpid(), 'https' if use_https else 'http', rpc_username, server, port, timeout) )
105 |
106 | protocol = 'https' if use_https else 'http'
107 | if not server or len(server) < 1:
108 | raise Exception('Invalid bitcoind host address.')
109 | if not port or not is_valid_int(port):
110 | raise Exception('Invalid bitcoind port number.')
111 |
112 | authproxy_config_uri = '%s://%s:%s@%s:%s' % (protocol, rpc_username, rpc_password, server, port)
113 |
114 | if use_https:
115 | # TODO: ship with a cert
116 | if do_wrap_socket:
117 | # ssl._create_unverified_context and ssl.create_default_context are not supported.
118 | # wrap the socket directly
119 | connection = BitcoindConnection( server, int(port), timeout=timeout )
120 | ret = AuthServiceProxy(authproxy_config_uri, connection=connection)
121 |
122 | elif create_ssl_authproxy:
123 | # ssl has _create_unverified_context, so we're good to go
124 | ret = AuthServiceProxy(authproxy_config_uri, timeout=timeout)
125 |
126 | else:
127 | # have to set up an unverified context ourselves
128 | ssl_ctx = ssl.create_default_context()
129 | ssl_ctx.check_hostname = False
130 | ssl_ctx.verify_mode = ssl.CERT_NONE
131 | connection = httplib.HTTPSConnection( server, int(port), context=ssl_ctx, timeout=timeout )
132 | ret = AuthServiceProxy(authproxy_config_uri, connection=connection)
133 |
134 | else:
135 | ret = AuthServiceProxy(authproxy_config_uri)
136 |
137 | # remember the options
138 | bitcoind_opts = {
139 | "bitcoind_user": rpc_username,
140 | "bitcoind_passwd": rpc_password,
141 | "bitcoind_server": server,
142 | "bitcoind_port": port,
143 | "bitcoind_use_https": use_https,
144 | "bitcoind_timeout": timeout
145 | }
146 |
147 | setattr( ret, "opts", bitcoind_opts )
148 | return ret
149 |
150 |
151 | def connect_bitcoind_impl( bitcoind_opts ):
152 | """
153 | Create a connection to bitcoind, using a dict of config options.
154 | """
155 |
156 | if 'bitcoind_port' not in bitcoind_opts.keys() or bitcoind_opts['bitcoind_port'] is None:
157 | log.error("No port given")
158 | raise ValueError("No RPC port given (bitcoind_port)")
159 |
160 | if 'bitcoind_timeout' not in bitcoind_opts.keys() or bitcoind_opts['bitcoind_timeout'] is None:
161 | # default
162 | bitcoind_opts['bitcoind_timeout'] = 300
163 |
164 | try:
165 | int(bitcoind_opts['bitcoind_port'])
166 | except:
167 | log.error("Not an int: '%s'" % bitcoind_opts.get('bitcoind_port'))
168 | raise
169 |
170 | try:
171 | float(bitcoind_opts.get('bitcoind_timeout', 300))
172 | except:
173 | log.error("Not a float: '%s'" % bitcoind_opts.get('bitcoind_timeout', 300))
174 | raise
175 |
176 | return create_bitcoind_connection( bitcoind_opts['bitcoind_user'], bitcoind_opts['bitcoind_passwd'], \
177 | bitcoind_opts['bitcoind_server'], int(bitcoind_opts['bitcoind_port']), \
178 | bitcoind_opts.get('bitcoind_use_https', False), float(bitcoind_opts.get('bitcoind_timeout', 300)) )
179 |
180 |
181 | def get_bitcoind_client(config_path=None, bitcoind_opts=None):
182 | """
183 | Connect to bitcoind
184 | """
185 | if bitcoind_opts is None and config_path is None:
186 | raise ValueError("Need bitcoind opts or config path")
187 |
188 | bitcoind_opts = get_bitcoind_config(config_file=config_path)
189 | log.debug("Connect to bitcoind at %s:%s (%s)" % (bitcoind_opts['bitcoind_server'], bitcoind_opts['bitcoind_port'], config_path))
190 | client = connect_bitcoind_impl( bitcoind_opts )
191 |
192 | return client
193 |
194 |
195 |
196 |
--------------------------------------------------------------------------------
/virtualchain/lib/blockchain/transactions.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | """
4 | Virtualchain
5 | ~~~~~
6 | copyright: (c) 2014 by Halfmoon Labs, Inc.
7 | copyright: (c) 2015-2018 by Blockstack.org
8 |
9 | This file is part of Virtualchain
10 |
11 | Virtualchain is free software: you can redistribute it and/or modify
12 | it under the terms of the GNU General Public License as published by
13 | the Free Software Foundation, either version 3 of the License, or
14 | (at your option) any later version.
15 |
16 | Virtualchain is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | GNU General Public License for more details.
20 | You should have received a copy of the GNU General Public License
21 | along with Virtualchain. If not, see .
22 | """
23 |
24 | from bitcoin_blockchain import BlockchainDownloader, SPVClient
25 |
26 | import os
27 | import time
28 | import random
29 | from decimal import *
30 |
31 | from ..config import get_logger
32 |
33 | log = get_logger("virtualchain")
34 |
35 | from bitcoin_blockchain.bits import *
36 | from bitcoin_blockchain.blocks import get_bitcoin_virtual_transactions
37 |
38 | def get_virtual_transactions(blockchain_name, blockchain_opts, first_block_height, last_block_height, tx_filter=None, **hints):
39 | """
40 | Get the sequence of virtualchain transactions from a particular blockchain over a given range of block heights.
41 | Returns a list of tuples in the format of [(block height, [txs])], where
42 | each tx in [txs] is the parsed transaction. The parsed transaction will conform to... # TODO write a spec for this
43 |
44 | Each transaction has at least the following fields:
45 |
46 | `version`: the version of the transaction
47 | `txindex`: the index into the block where this tx occurs
48 | `ins`: a list of transaction inputs, where each member is a dict with:
49 | `outpoint`: a dict of {'hash': txid of transaction that fed it in, 'index': the index into the feeder tx's outputs list}
50 | `script`: the signature script for this input
51 | `outs`: a list of transaction outputs, where each member is a dict with:
52 | `value`: the amount of currency units spent (in the fundamental units of the chain)
53 | `script`: the spending script for this input
54 | `senders`: a list of information in 1-to-1 correspondence with each input regarding the transactions that funded it:
55 | `value`: the amount of currency units sent (in fundamental units of the chain)
56 | `script_pubkey`: the spending script for the sending transaction
57 |
58 | Returns [(block height, [txs])] on success
59 | Returns None on error.
60 | Raises ValueError on unknown blockchain
61 | """
62 | if blockchain_name == 'bitcoin':
63 | return get_bitcoin_virtual_transactions(blockchain_opts, first_block_height, last_block_height, tx_filter=tx_filter, **hints)
64 |
65 | else:
66 | raise ValueError("Unknown blockchain {}".format(blockchain_name))
67 |
68 |
69 | def tx_parse(raw_tx, blockchain='bitcoin', **blockchain_opts):
70 | """
71 | Parse a raw transaction, based on the type of blockchain it's from
72 | Returns a tx dict on success (see get_virtual_transactions)
73 | Raise ValueError for unknown blockchain
74 | Raise some other exception for invalid raw_tx (implementation-specific)
75 | """
76 | if blockchain == 'bitcoin':
77 | return btc_tx_deserialize(raw_tx, **blockchain_opts)
78 | else:
79 | raise ValueError("Unknown blockchain {}".format(blockchain))
80 |
81 |
82 | def tx_output_has_data(output, blockchain='bitcoin', **blockchain_opts):
83 | """
84 | Give a blockchain name and a tx output, determine whether or not it is a
85 | data-bearing script--i.e. one with data for the state engine.
86 |
87 | Return True if so
88 | Return False if not
89 | """
90 | if blockchain == 'bitcoin':
91 | return btc_tx_output_has_data(output, **blockchain_opts)
92 | else:
93 | return ValueError('Unknown blockchain "{}"'.format(blockchain))
94 |
95 |
96 | def tx_is_data_script(out_script, blockchain='bitcoin', **blockchain_opts):
97 | """
98 | Given a blockchain name and an output script (tx['outs'][x]['script']),
99 | determine whether or not it is a data-bearing script---i.e. one with data for the state engine.
100 |
101 | Return True if so
102 | Reurn False if not
103 | """
104 | if blockchain == 'bitcoin':
105 | return btc_tx_output_script_has_data(out_script, **blockchain_opts)
106 | else:
107 | raise ValueError('Unknown blockchain "{}"'.format(blockchain))
108 |
109 |
110 | def tx_extend(partial_tx_hex, new_inputs, new_outputs, blockchain='bitcoin', **blockchain_opts):
111 | """
112 | Add a set of inputs and outputs to a tx.
113 | Return the new tx on success
114 | Raise on error
115 | """
116 | if blockchain == 'bitcoin':
117 | return btc_tx_extend(partial_tx_hex, new_inputs, new_outputs, **blockchain_opts)
118 | else:
119 | raise ValueError('Unknown blockchain "{}"'.format(blockchain))
120 |
121 |
122 | def tx_sign_input(tx_hex, idx, prevout_script, prevout_amount, private_key_info, blockchain='bitcoin', **blockchain_opts):
123 | """
124 | Sign a given input in a transaction, given the previous output script and previous output amount.
125 | Different blockchains can require additional fields; pass thse in **blockchain_opts.
126 |
127 | Return the serialized tx with the given input signed on success
128 | Raise on error
129 | """
130 | if blockchain == 'bitcoin':
131 | return btc_tx_sign_input(tx_hex, idx, prevout_script, prevout_amount, private_key_info, **blockchain_opts)
132 | else:
133 | raise ValueError('Unknown blockchain "{}"'.format(blockchain))
134 |
135 |
136 | def tx_sign_all_unsigned_inputs(privkey_info, prev_outputs, unsigned_tx_hex, blockchain='bitcoin', **blockchain_opts):
137 | """
138 | Sign all unsigned inputs to a given transaction with the given private key. Also, pass in the list of previous outputs to the transaction so they
139 | can be paired with the right input (i.e. prev_outputs is a list of tx outputs that are in 1-to-1 correspondance with the inputs in the serialized tx)
140 |
141 | Different blockchains can require additional fields; pass thse in **blockchain_opts.
142 |
143 | Return the signed transaction on success
144 | Raise on error
145 | """
146 | if blockchain == 'bitcoin':
147 | return btc_tx_sign_all_unsigned_inputs(privkey_info, prev_outputs, unsigned_tx_hex, **blockchain_opts)
148 | else:
149 | raise ValueError('Unknown blockchain "{}"'.format(blockchain))
150 |
151 |
152 | def calculate_change_amount(inputs, send_amount, fee):
153 | """
154 | Find out how much change there exists between a set of tx inputs, the send amount and the tx fee.
155 | @inputs must be a list of transaction inputs, i.e. [{'script_hex': str, 'value': int}]
156 | """
157 | # calculate the total amount coming into the transaction from the inputs
158 | total_amount_in = sum([input['value'] for input in inputs])
159 |
160 | # change = whatever is left over from the amount sent & the transaction fee
161 | change_amount = total_amount_in - send_amount - fee
162 |
163 | # check to ensure the change amount is a non-negative value and return it
164 | if change_amount < 0:
165 | raise ValueError('Not enough inputs for transaction (total: {}, to spend: {}, fee: {}).'.format(total_amount_in, send_amount, fee))
166 |
167 | return change_amount
168 |
169 |
170 |
--------------------------------------------------------------------------------
/virtualchain/lib/config.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | """
4 | Virtualchain
5 | ~~~~~
6 | copyright: (c) 2014-2015 by Halfmoon Labs, Inc.
7 | copyright: (c) 2016 by Blockstack.org
8 |
9 | This file is part of Virtualchain
10 |
11 | Virtualchain is free software: you can redistribute it and/or modify
12 | it under the terms of the GNU General Public License as published by
13 | the Free Software Foundation, either version 3 of the License, or
14 | (at your option) any later version.
15 |
16 | Virtualchain is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | GNU General Public License for more details.
20 | You should have received a copy of the GNU General Public License
21 | along with Virtualchain. If not, see .
22 | """
23 |
24 |
25 | import os
26 | import argparse
27 | from ConfigParser import SafeConfigParser
28 | import logging
29 | import time
30 |
31 | DEBUG = False
32 | if os.environ.get("BLOCKSTACK_DEBUG") == "1" or os.environ.get("BLOCKSTACK_TEST") == "1":
33 | DEBUG = True
34 |
35 | """ virtualchain daemon configs
36 | """
37 |
38 | # RPC_TIMEOUT = 5 # seconds
39 |
40 | BLOCK_BATCH_SIZE = 10
41 |
42 | VIRTUALCHAIN_BTC_DEFAULT_SEGWIT = False
43 |
44 | def get_features(feature_name):
45 | if feature_name == 'segwit':
46 | return VIRTUALCHAIN_BTC_DEFAULT_SEGWIT
47 |
48 | raise ValueError("Unrecognized feature '{}'".format(feature_name))
49 |
50 |
51 | def set_features(feature_name, value):
52 | global VIRTUALCHAIN_BTC_DEFAULT_SEGWIT
53 |
54 | if feature_name == 'segwit':
55 | if value not in [True, False]:
56 | raise ValueError("Invalid value (must be True/False)")
57 |
58 | VIRTUALCHAIN_BTC_DEFAULT_SEGWIT = value
59 | return
60 |
61 | raise ValueError("Unrecognized feature '{}'".format(feature_name))
62 |
63 |
64 | def get_logger(name=None):
65 | """
66 | Get virtualchain's logger
67 | """
68 |
69 | level = logging.CRITICAL
70 | if DEBUG:
71 | logging.disable(logging.NOTSET)
72 | level = logging.DEBUG
73 |
74 | if name is None:
75 | name = ""
76 |
77 | log = logging.getLogger(name=name)
78 | log.setLevel( level )
79 | console = logging.StreamHandler()
80 | console.setLevel( level )
81 | log_format = ('[%(asctime)s] [%(levelname)s] [%(module)s:%(lineno)d] (' + str(os.getpid()) + '.%(thread)d) %(message)s' if DEBUG else '%(message)s')
82 | formatter = logging.Formatter( log_format )
83 | console.setFormatter(formatter)
84 | log.propagate = False
85 |
86 | if len(log.handlers) > 0:
87 | for i in xrange(0, len(log.handlers)):
88 | log.handlers.pop(0)
89 |
90 | log.addHandler(console)
91 | return log
92 |
93 | log = get_logger("virtualchain")
94 |
95 | if not __debug__:
96 | log.error('FATAL: __debug__ must be set')
97 | os.abort()
98 |
99 |
100 | def get_first_block_id(impl):
101 | """
102 | facade to implementation's first block
103 | """
104 | return impl.get_first_block_id()
105 |
106 |
107 | def get_config_filename(impl, working_dir):
108 | """
109 | Get the absolute path to the config file.
110 | """
111 | config_filename = impl.get_virtual_chain_name() + ".ini"
112 | return os.path.join(working_dir, config_filename)
113 |
114 |
115 | def get_db_filename(impl, working_dir):
116 | """
117 | Get the absolute path to the last-block file.
118 | """
119 | db_filename = impl.get_virtual_chain_name() + ".db"
120 | return os.path.join(working_dir, db_filename)
121 |
122 |
123 | def get_snapshots_filename(impl, working_dir):
124 | """
125 | Get the absolute path to the chain's consensus snapshots file.
126 | """
127 | snapshots_filename = impl.get_virtual_chain_name() + ".snapshots"
128 | return os.path.join(working_dir, snapshots_filename)
129 |
130 |
131 | def get_backups_directory(impl, working_dir):
132 | """
133 | Get the absolute path to the chain's backups directory
134 | """
135 | backup_dir = os.path.join( working_dir, 'backups')
136 | return backup_dir
137 |
138 |
139 | def get_lockfile_filename(impl, working_dir):
140 | """
141 | Get the absolute path to the chain's indexing lockfile
142 | """
143 | lockfile_name = impl.get_virtual_chain_name() + ".lock"
144 | return os.path.join(working_dir, lockfile_name)
145 |
146 |
147 | def get_bitcoind_config(config_file=None, impl=None):
148 | """
149 | Set bitcoind options globally.
150 | Call this before trying to talk to bitcoind.
151 | """
152 |
153 | loaded = False
154 |
155 | bitcoind_server = None
156 | bitcoind_port = None
157 | bitcoind_user = None
158 | bitcoind_passwd = None
159 | bitcoind_timeout = None
160 | bitcoind_regtest = None
161 | bitcoind_p2p_port = None
162 | bitcoind_spv_path = None
163 |
164 | regtest = None
165 |
166 | if config_file is not None:
167 |
168 | parser = SafeConfigParser()
169 | parser.read(config_file)
170 |
171 | if parser.has_section('bitcoind'):
172 |
173 | if parser.has_option('bitcoind', 'server'):
174 | bitcoind_server = parser.get('bitcoind', 'server')
175 |
176 | if parser.has_option('bitcoind', 'port'):
177 | bitcoind_port = int(parser.get('bitcoind', 'port'))
178 |
179 | if parser.has_option('bitcoind', 'p2p_port'):
180 | bitcoind_p2p_port = int(parser.get('bitcoind', 'p2p_port'))
181 |
182 | if parser.has_option('bitcoind', 'user'):
183 | bitcoind_user = parser.get('bitcoind', 'user')
184 |
185 | if parser.has_option('bitcoind', 'passwd'):
186 | bitcoind_passwd = parser.get('bitcoind', 'passwd')
187 |
188 | if parser.has_option('bitcoind', 'spv_path'):
189 | bitcoind_spv_path = parser.get('bitcoind', 'spv_path')
190 |
191 | if parser.has_option('bitcoind', 'regtest'):
192 | regtest = parser.get('bitcoind', 'regtest')
193 | else:
194 | regtest = 'no'
195 |
196 | if parser.has_option('bitcoind', 'timeout'):
197 | bitcoind_timeout = float(parser.get('bitcoind', 'timeout'))
198 |
199 | if regtest.lower() in ["yes", "y", "true", "1", "on"]:
200 | bitcoind_regtest = True
201 | else:
202 | bitcoind_regtest = False
203 |
204 | loaded = True
205 |
206 | if not loaded:
207 |
208 | bitcoind_server = 'bitcoin.blockstack.com'
209 | bitcoind_port = 8332
210 | bitcoind_user = 'blockstack'
211 | bitcoind_passwd = 'blockstacksystem'
212 | bitcoind_regtest = False
213 | bitcoind_timeout = 300
214 | bitcoind_p2p_port = 8333
215 | bitcoind_spv_path = os.path.expanduser("~/.virtualchain-spv-headers.dat")
216 |
217 | default_bitcoin_opts = {
218 | "bitcoind_user": bitcoind_user,
219 | "bitcoind_passwd": bitcoind_passwd,
220 | "bitcoind_server": bitcoind_server,
221 | "bitcoind_port": bitcoind_port,
222 | "bitcoind_timeout": bitcoind_timeout,
223 | "bitcoind_regtest": bitcoind_regtest,
224 | "bitcoind_p2p_port": bitcoind_p2p_port,
225 | "bitcoind_spv_path": bitcoind_spv_path
226 | }
227 |
228 | return default_bitcoin_opts
229 |
230 |
231 |
--------------------------------------------------------------------------------
/virtualchain/lib/ecdsalib.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | """
4 | Virtualchain
5 | ~~~~~
6 | copyright: (c) 2014-2015 by Halfmoon Labs, Inc.
7 | copyright: (c) 2016-2017 by Blockstack.org
8 |
9 | This file is part of Virtualchain
10 |
11 | Virtualchain is free software: you can redistribute it and/or modify
12 | it under the terms of the GNU General Public License as published by
13 | the Free Software Foundation, either version 3 of the License, or
14 | (at your option) any later version.
15 |
16 | Virtualchain is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | GNU General Public License for more details.
20 | You should have received a copy of the GNU General Public License
21 | along with Virtualchain. If not, see .
22 | """
23 |
24 | import keylib
25 |
26 | from cryptography.hazmat.backends import default_backend
27 | from cryptography.hazmat.primitives import hashes
28 | from cryptography.hazmat.primitives.asymmetric import ec, utils
29 | from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature, encode_dss_signature
30 | from cryptography.exceptions import InvalidSignature
31 |
32 | from .config import get_logger
33 |
34 | import base64
35 | import hashlib
36 | import re
37 | from binascii import hexlify
38 |
39 | log = get_logger("virtualchain-ecdsalib")
40 |
41 | SECP256k1_order = 115792089237316195423570985008687907852837564279074904382605163141518161494337L
42 |
43 | class ECSigner(object):
44 | """
45 | Generic ECDSA signer object
46 | """
47 | def __init__(self, privkey_hex):
48 | """
49 | Instantiate a signer with a hex-encoded ECDSA private key
50 | """
51 | pk_i = decode_privkey_hex(privkey_hex)
52 | privk = ec.derive_private_key(pk_i, ec.SECP256K1(), default_backend())
53 | self.signer = privk.signer(ec.ECDSA(hashes.SHA256()))
54 |
55 | def update(self, data):
56 | """
57 | Update the hash used to generate the signature
58 | """
59 | try:
60 | self.signer.update(data)
61 | except TypeError:
62 | log.error("Invalid data: {} ({})".format(type(data), data))
63 | raise
64 |
65 | def finalize(self):
66 | """
67 | Get the base64-encoded signature itself.
68 | Can only be called once.
69 | """
70 | signature = self.signer.finalize()
71 | sig_r, sig_s = decode_dss_signature(signature)
72 | sig_b64 = encode_signature(sig_r, sig_s)
73 | return sig_b64
74 |
75 |
76 | class ECVerifier(object):
77 | """
78 | Generic ECDSA verifier object
79 | """
80 | def __init__(self, pubkey_hex, sigb64):
81 | """
82 | Instantiate the verifier with a hex-encoded public key and a base64-encoded signature
83 | """
84 | sig_r, sig_s = decode_signature(sigb64)
85 | pubkey_hex_decompressed = keylib.key_formatting.decompress(pubkey_hex)
86 | pubk = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256K1(), pubkey_hex_decompressed.decode('hex')).public_key(default_backend())
87 | signature = encode_dss_signature(sig_r, sig_s)
88 | self.verifier = pubk.verifier(signature, ec.ECDSA(hashes.SHA256()))
89 |
90 | def update(self, data):
91 | """
92 | Update the hash used to generate the signature
93 | """
94 | try:
95 | self.verifier.update(data)
96 | except TypeError:
97 | log.error("Invalid data: {} ({})".format(type(data), data))
98 | raise
99 |
100 | def verify(self):
101 | """
102 | Verify whether or not the public key matches the signature, given the data
103 | """
104 | try:
105 | self.verifier.verify()
106 | return True
107 | except InvalidSignature:
108 | return False
109 |
110 |
111 | class _ECPrivateKey(object):
112 | _pubkeyhash_version_byte = 0
113 |
114 | def __init__(self, private_key=None, compressed=True):
115 | """ Takes in a private key/secret exponent.
116 | """
117 | pk_i = None
118 | if private_key is None:
119 | pk_i = ec.generate_private_key(ec.SECP256K1(), default_backend()).private_numbers().private_value
120 | else:
121 | pk_i = keylib.key_formatting.encode_privkey(private_key, 'decimal')
122 |
123 | privkey_str = '{:064x}'.format(pk_i)
124 | assert len(privkey_str) == 64
125 |
126 | self._ecdsa_private_key_string = privkey_str.decode('hex')
127 | self._compressed = compressed
128 |
129 | @classmethod
130 | def wif_version_byte(cls):
131 | if hasattr(cls, '_wif_version_byte'):
132 | return cls._wif_version_byte
133 | return (cls._pubkeyhash_version_byte + 128) % 256
134 |
135 | def to_bin(self):
136 | if self._compressed:
137 | return keylib.key_formatting.encode_privkey(
138 | self._ecdsa_private_key_string, 'bin_compressed')
139 | else:
140 | return self._ecdsa_private_key_string
141 |
142 | def to_hex(self):
143 | if self._compressed:
144 | return keylib.key_formatting.encode_privkey(
145 | self._ecdsa_private_key_string, 'hex_compressed')
146 | else:
147 | return hexlify(self.to_bin())
148 |
149 | def to_wif(self):
150 | if self._compressed:
151 | return keylib.key_formatting.encode_privkey(
152 | self._ecdsa_private_key_string, 'wif_compressed', vbyte=self._pubkeyhash_version_byte)
153 | else:
154 | return keylib.b58check.b58check_encode(
155 | self.to_bin(), version_byte=self.wif_version_byte())
156 |
157 | def public_key(self):
158 | # lazily calculate and set the public key
159 | if not hasattr(self, '_public_key'):
160 |
161 | privk = ec.derive_private_key(int(self._ecdsa_private_key_string.encode('hex'), 16), ec.SECP256K1(), default_backend())
162 | pubk = privk.public_key()
163 |
164 | ecdsa_public_key_str = pubk.public_numbers().encode_point().encode('hex')
165 | if self._compressed:
166 | ecdsa_public_key_str = keylib.key_formatting.compress(ecdsa_public_key_str)
167 |
168 | self._public_key = _ECPublicKey(ecdsa_public_key_str, version_byte=self._pubkeyhash_version_byte)
169 |
170 | # return the public key object
171 | return self._public_key
172 |
173 |
174 | class _ECPublicKey(object):
175 | _version_byte = 0
176 |
177 | @classmethod
178 | def version_byte(cls):
179 | return cls._version_byte
180 |
181 | def __init__(self, public_key_string, version_byte=None, verify=True):
182 | """ Takes in a public key in hex format.
183 | """
184 | # set the version byte
185 | if version_byte:
186 | self._version_byte = version_byte
187 |
188 | self._charencoding, self._type = keylib.public_key_encoding.get_public_key_format(public_key_string)
189 |
190 | # extract the binary key (compressed/uncompressed w magic byte)
191 | self._bin_public_key = keylib.public_key_encoding.extract_bin_ecdsa_pubkey(public_key_string)
192 |
193 | if verify:
194 | pubkey_hex_decompressed = keylib.key_formatting.decompress(self._bin_public_key.encode('hex'))
195 | pubk = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256K1(), pubkey_hex_decompressed.decode('hex')).public_key(default_backend())
196 |
197 | def to_bin(self):
198 | return self._bin_public_key
199 |
200 | def to_hex(self):
201 | return hexlify(self.to_bin())
202 |
203 | def bin_hash160(self):
204 | if not hasattr(self, '_bin_hash160'):
205 | binary_key = self.to_bin()
206 | if self._type == keylib.public_key_encoding.PubkeyType.compressed:
207 | binary_key = keylib.key_formatting.compress(binary_key)
208 |
209 | self._bin_hash160 = keylib.hashing.bin_hash160(binary_key)
210 | return self._bin_hash160
211 |
212 | def hash160(self):
213 | return hexlify(self.bin_hash160())
214 |
215 | def address(self):
216 | return keylib.address_formatting.bin_hash160_to_address(
217 | self.bin_hash160(), version_byte=self._version_byte)
218 |
219 |
220 |
221 | def ecdsa_private_key(privkey_str=None, compressed=None):
222 | """
223 | Make a private key, but enforce the following rule:
224 | * unless the key's hex encoding specifically ends in '01', treat it as uncompressed.
225 | """
226 | if compressed is None:
227 | compressed = False
228 | if privkey_str is not None:
229 | if len(privkey_str) == 66 and privkey_str[-2:] == '01':
230 | compressed = True
231 |
232 | return _ECPrivateKey(privkey_str, compressed=compressed)
233 |
234 |
235 | def ecdsa_public_key(pubkey_str, compressed=None):
236 | """
237 | Make a public key object, but enforce the following rule:
238 | * if compressed is True or False, make the key compressed/uncompressed.
239 | * otherwise, return whatever the hex encoding is
240 | """
241 | if compressed == True:
242 | pubkey_str = keylib.key_formatting.compress(pubkey_str)
243 | elif compressed == False:
244 | pubkey_str = keylib.key_formatting.decompress(pubkey_str)
245 |
246 | return _ECPublicKey(pubkey_str)
247 |
248 |
249 | def set_privkey_compressed(privkey, compressed=True):
250 | """
251 | Make sure the private key given is compressed or not compressed
252 | """
253 | if len(privkey) != 64 and len(privkey) != 66:
254 | raise ValueError("expected 32-byte private key as a hex string")
255 |
256 | # compressed?
257 | if compressed and len(privkey) == 64:
258 | privkey += '01'
259 |
260 | if not compressed and len(privkey) == 66:
261 | if privkey[-2:] != '01':
262 | raise ValueError("private key does not end in '01'")
263 |
264 | privkey = privkey[:-2]
265 |
266 | return privkey
267 |
268 |
269 | def get_pubkey_hex( privatekey_hex ):
270 | """
271 | Get the uncompressed hex form of a private key
272 | """
273 | if not isinstance(privatekey_hex, (str, unicode)):
274 | raise ValueError("private key is not a hex string but {}".format(str(type(privatekey_hex))))
275 |
276 | # remove 'compressed' hint
277 | if len(privatekey_hex) > 64:
278 | if privatekey_hex[-2:] != '01':
279 | raise ValueError("private key does not end in 01")
280 |
281 | privatekey_hex = privatekey_hex[:64]
282 |
283 | # get hex public key
284 | privatekey_int = int(privatekey_hex, 16)
285 | privk = ec.derive_private_key(privatekey_int, ec.SECP256K1(), default_backend())
286 | pubk = privk.public_key()
287 | x = pubk.public_numbers().x
288 | y = pubk.public_numbers().y
289 |
290 | pubkey_hex = "04{:064x}{:064x}".format(x, y)
291 | return pubkey_hex
292 |
293 |
294 | def get_uncompressed_private_and_public_keys( privkey_str ):
295 | """
296 | Get the private and public keys from a private key string.
297 | Make sure the both are *uncompressed*
298 | """
299 | if not isinstance(privkey_str, (str, unicode)):
300 | raise ValueError("private key given is not a string")
301 |
302 | pk = ecdsa_private_key(str(privkey_str))
303 | pk_hex = pk.to_hex()
304 |
305 | # force uncompressed
306 | if len(pk_hex) > 64:
307 | if pk_hex[-2:] != '01':
308 | raise ValueError("private key does not end in '01'")
309 |
310 | pk_hex = pk_hex[:64]
311 |
312 | pubk_hex = ecdsa_private_key(pk_hex).public_key().to_hex()
313 | return pk_hex, pubk_hex
314 |
315 |
316 | def decode_privkey_hex(privkey_hex):
317 | """
318 | Decode a private key for ecdsa signature
319 | """
320 | if not isinstance(privkey_hex, (str, unicode)):
321 | raise ValueError("private key is not a string")
322 |
323 | # force uncompressed
324 | priv = str(privkey_hex)
325 | if len(priv) > 64:
326 | if priv[-2:] != '01':
327 | raise ValueError("private key does not end in '01'")
328 |
329 | priv = priv[:64]
330 |
331 | pk_i = int(priv, 16)
332 | return pk_i
333 |
334 |
335 | def decode_pubkey_hex(pubkey_hex):
336 | """
337 | Decode a public key for ecdsa verification
338 | """
339 | if not isinstance(pubkey_hex, (str, unicode)):
340 | raise ValueError("public key is not a string")
341 |
342 | pubk = keylib.key_formatting.decompress(str(pubkey_hex))
343 | assert len(pubk) == 130
344 |
345 | pubk_raw = pubk[2:]
346 | pubk_i = (int(pubk_raw[:64], 16), int(pubk_raw[64:], 16))
347 | return pubk_i
348 |
349 |
350 | def encode_signature(sig_r, sig_s):
351 | """
352 | Encode an ECDSA signature, with low-s
353 | """
354 | # enforce low-s
355 | if sig_s * 2 >= SECP256k1_order:
356 | log.debug("High-S to low-S")
357 | sig_s = SECP256k1_order - sig_s
358 |
359 | sig_bin = '{:064x}{:064x}'.format(sig_r, sig_s).decode('hex')
360 | assert len(sig_bin) == 64
361 |
362 | sig_b64 = base64.b64encode(sig_bin)
363 | return sig_b64
364 |
365 |
366 | def decode_signature(sigb64):
367 | """
368 | Decode a signature into r, s
369 | """
370 | sig_bin = base64.b64decode(sigb64)
371 | if len(sig_bin) != 64:
372 | raise ValueError("Invalid base64 signature")
373 |
374 | sig_hex = sig_bin.encode('hex')
375 | sig_r = int(sig_hex[:64], 16)
376 | sig_s = int(sig_hex[64:], 16)
377 | return sig_r, sig_s
378 |
379 |
380 | def sign_raw_data(raw_data, privatekey_hex):
381 | """
382 | Sign a string of data.
383 | Returns signature as a base64 string
384 | """
385 | if not isinstance(raw_data, (str, unicode)):
386 | raise ValueError("Data is not a string")
387 |
388 | raw_data = str(raw_data)
389 |
390 | si = ECSigner(privatekey_hex)
391 | si.update(raw_data)
392 | return si.finalize()
393 |
394 |
395 | def verify_raw_data(raw_data, pubkey_hex, sigb64):
396 | """
397 | Verify the signature over a string, given the public key
398 | and base64-encode signature.
399 | Return True on success.
400 | Return False on error.
401 | """
402 | if not isinstance(raw_data, (str, unicode)):
403 | raise ValueError("data is not a string")
404 |
405 | raw_data = str(raw_data)
406 |
407 | vi = ECVerifier(pubkey_hex, sigb64)
408 | vi.update(raw_data)
409 | return vi.verify()
410 |
411 |
412 | def sign_digest(hash_hex, privkey_hex, hashfunc=hashlib.sha256):
413 | """
414 | Given a digest and a private key, sign it.
415 | Return the base64-encoded signature
416 | """
417 | if not isinstance(hash_hex, (str, unicode)):
418 | raise ValueError("hash hex is not a string")
419 |
420 | hash_hex = str(hash_hex)
421 |
422 | pk_i = decode_privkey_hex(privkey_hex)
423 | privk = ec.derive_private_key(pk_i, ec.SECP256K1(), default_backend())
424 |
425 | sig = privk.sign(hash_hex.decode('hex'), ec.ECDSA(utils.Prehashed(hashes.SHA256())))
426 |
427 | sig_r, sig_s = decode_dss_signature(sig)
428 | sigb64 = encode_signature(sig_r, sig_s)
429 | return sigb64
430 |
431 |
432 | def verify_digest(hash_hex, pubkey_hex, sigb64, hashfunc=hashlib.sha256):
433 | """
434 | Given a digest, public key (as hex), and a base64 signature,
435 | verify that the public key signed the digest.
436 | Return True if so
437 | Return False if not
438 | """
439 | if not isinstance(hash_hex, (str, unicode)):
440 | raise ValueError("hash hex is not a string")
441 |
442 | hash_hex = str(hash_hex)
443 | pubk_uncompressed_hex = keylib.key_formatting.decompress(pubkey_hex)
444 | sig_r, sig_s = decode_signature(sigb64)
445 |
446 | pubk = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SECP256K1(), pubk_uncompressed_hex.decode('hex')).public_key(default_backend())
447 | signature = encode_dss_signature(sig_r, sig_s)
448 |
449 | try:
450 | pubk.verify(signature, hash_hex.decode('hex'), ec.ECDSA(utils.Prehashed(hashes.SHA256())))
451 | return True
452 | except InvalidSignature:
453 | return False
454 |
455 |
--------------------------------------------------------------------------------
/virtualchain/lib/encoding.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python2
2 | # -*- coding: utf-8 -*-
3 | """
4 | Virtualchain
5 | ~~~~~
6 | copyright: (c) 2014-2015 by Halfmoon Labs, Inc.
7 | copyright: (c) 2016-2017 by Blockstack.org
8 |
9 | This file is part of Virtualchain
10 |
11 | Virtualchain is free software: you can redistribute it and/or modify
12 | it under the terms of the GNU General Public License as published by
13 | the Free Software Foundation, either version 3 of the License, or
14 | (at your option) any later version.
15 |
16 | Virtualchain is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | GNU General Public License for more details.
20 | You should have received a copy of the GNU General Public License
21 | along with Virtualchain. If not, see .
22 | """
23 |
24 | import binascii
25 |
26 | # Derived from pybitcointools (https://github.com/vbuterin/pybitcointools)
27 | # Written originally by Vitalik Buterin
28 |
29 | # Base switching
30 | code_strings = {
31 | 2: '01',
32 | 10: '0123456789',
33 | 16: '0123456789abcdef',
34 | 32: 'abcdefghijklmnopqrstuvwxyz234567',
35 | 58: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz',
36 | 256: ''.join([chr(x) for x in range(256)])
37 | }
38 |
39 | def get_code_string_bases():
40 | """
41 | Get the set of supported code strings
42 | """
43 | return code_strings.keys()[:]
44 |
45 |
46 | def get_code_string(base):
47 | """
48 | Get the code string for a given numeric base.
49 | Raise ValueError for unknown base
50 | """
51 | if base in code_strings:
52 | return code_strings[base]
53 | else:
54 | raise ValueError("Invalid base!")
55 |
56 |
57 | def lpad(msg, symbol, length):
58 | """
59 | Left-pad a given string (msg) with a character (symbol) for a given number of bytes (length).
60 | Return the padded string
61 | """
62 | if len(msg) >= length:
63 | return msg
64 | return symbol * (length - len(msg)) + msg
65 |
66 |
67 | def changebase(string, frm, to, minlen=0):
68 | """
69 | Change a string's characters from one base to another.
70 | Return the re-encoded string
71 | """
72 | if frm == to:
73 | return lpad(string, get_code_string(frm)[0], minlen)
74 |
75 | return encode(decode(string, frm), to, minlen)
76 |
77 |
78 | def bytes_to_hex_string(b):
79 | """
80 | Portable byte list to hex
81 | """
82 | return b.encode('hex')
83 |
84 | def safe_from_hex(s):
85 | """
86 | Portable hex string to bytes
87 | """
88 | return s.decode('hex')
89 |
90 |
91 | def from_int_representation_to_bytes(a):
92 | """
93 | Portable string to int
94 | """
95 | return str(a)
96 |
97 |
98 | def from_int_to_byte(a):
99 | """
100 | Portable string to byte
101 | """
102 | return chr(a)
103 |
104 |
105 | def from_byte_to_int(a):
106 | """
107 | Portable byte to int
108 | """
109 | return ord(a)
110 |
111 |
112 | def from_bytes_to_string(s):
113 | """
114 | Portable bytes to string
115 | """
116 | return s
117 |
118 |
119 | def from_string_to_bytes(a):
120 | """
121 | Portable string to bytes
122 | """
123 | return a
124 |
125 |
126 | def safe_hexlify(a):
127 | """
128 | Portable bytes to hex
129 | """
130 | return binascii.hexlify(a)
131 |
132 |
133 | def num_to_var_int(x):
134 | """
135 | (bitcoin-specific): convert an integer into a variable-length integer
136 | """
137 | x = int(x)
138 | if x < 253:
139 | return from_int_to_byte(x)
140 |
141 | elif x < 65536:
142 | return from_int_to_byte(253) + encode(x, 256, 2)[::-1]
143 |
144 | elif x < 4294967296:
145 | return from_int_to_byte(254) + encode(x, 256, 4)[::-1]
146 |
147 | else:
148 | return from_int_to_byte(255) + encode(x, 256, 8)[::-1]
149 |
150 |
151 | def encode(val, base, minlen=0):
152 | """
153 | Given an integer value (val) and a numeric base (base),
154 | encode it into the string of symbols with the given base.
155 | (with minimum length minlen)
156 |
157 | Returns the (left-padded) re-encoded val as a string.
158 | """
159 |
160 | base, minlen = int(base), int(minlen)
161 | code_string = get_code_string(base)
162 | result = ""
163 | while val > 0:
164 | result = code_string[val % base] + result
165 | val //= base
166 | return code_string[0] * max(minlen - len(result), 0) + result
167 |
168 |
169 | def decode(string, base):
170 | """
171 | Given a string (string) and a numeric base (base),
172 | decode the string into an integer.
173 |
174 | Returns the integer
175 | """
176 |
177 | base = int(base)
178 | code_string = get_code_string(base)
179 | result = 0
180 | if base == 16:
181 | string = string.lower()
182 | while len(string) > 0:
183 | result *= base
184 | result += code_string.find(string[0])
185 | string = string[1:]
186 | return result
187 |
188 |
189 | def json_is_base(obj, base):
190 | """
191 | Given a primitive compound Python object
192 | (i.e. a dict, string, int, or list) and a numeric base,
193 | verify whether or not the object and all relevant
194 | sub-components have the given numeric base.
195 |
196 | Return True if so.
197 | Return False if not.
198 | """
199 |
200 | alpha = get_code_string(base)
201 | if isinstance(obj, (str, unicode)):
202 | for i in range(len(obj)):
203 | if alpha.find(obj[i]) == -1:
204 | return False
205 |
206 | return True
207 |
208 | elif isinstance(obj, (int, long, float)) or obj is None:
209 | return True
210 |
211 | elif isinstance(obj, list):
212 | for i in range(len(obj)):
213 | if not json_is_base(obj[i], base):
214 | return False
215 |
216 | return True
217 |
218 | else:
219 | for x in obj:
220 | if not json_is_base(obj[x], base):
221 | return False
222 |
223 | return True
224 |
225 |
226 | def json_changebase(obj, changer):
227 | """
228 | Given a primitive compound Python object (i.e. a dict,
229 | string, int, or list) and a changer function that takes
230 | a primitive Python object as an argument, apply the
231 | changer function to the object and each sub-component.
232 |
233 | Return the newly-reencoded object.
234 | """
235 |
236 | if isinstance(obj, (str, unicode)):
237 | return changer(obj)
238 |
239 | elif isinstance(obj, (int, long)) or obj is None:
240 | return obj
241 |
242 | elif isinstance(obj, list):
243 | return [json_changebase(x, changer) for x in obj]
244 |
245 | elif isinstance(obj, dict):
246 | return dict((x, json_changebase(obj[x], changer)) for x in obj)
247 |
248 | else:
249 | raise ValueError("Invalid object")
250 |
251 |
--------------------------------------------------------------------------------
/virtualchain/lib/hashing.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | """
4 | Virtualchain
5 | ~~~~~
6 | copyright: (c) 2014-2015 by Halfmoon Labs, Inc.
7 | copyright: (c) 2016-2017 by Blockstack.org
8 |
9 | This file is part of Virtualchain
10 |
11 | Virtualchain is free software: you can redistribute it and/or modify
12 | it under the terms of the GNU General Public License as published by
13 | the Free Software Foundation, either version 3 of the License, or
14 | (at your option) any later version.
15 |
16 | Virtualchain is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | GNU General Public License for more details.
20 | You should have received a copy of the GNU General Public License
21 | along with Virtualchain. If not, see .
22 | """
23 | from binascii import hexlify, unhexlify
24 | import hashlib
25 | from hashlib import sha256
26 | import re
27 |
28 | def hex_to_int(s):
29 | try:
30 | return int(s, 16)
31 | except:
32 | raise ValueError("Value must be in hex format")
33 |
34 | def is_hex(s):
35 | # make sure that s is a string
36 | if not isinstance(s, str):
37 | return False
38 |
39 | if not re.match('^(0x)?[0-9a-fA-F]+$', s):
40 | return False
41 |
42 | # if there's a leading hex string indicator, strip it
43 | if s[0:2] == '0x':
44 | s = s[2:]
45 |
46 | # try to cast the string as an int
47 | try:
48 | i = hex_to_int(s)
49 | except ValueError:
50 | return False
51 | else:
52 | return True
53 |
54 |
55 | def count_bytes(hex_s):
56 | """ Calculate the number of bytes of a given hex string.
57 | """
58 | assert(is_hex(hex_s))
59 | return len(hex_s)/2
60 |
61 |
62 | def bin_hash160(s, hex_format=False):
63 | """ s is in hex or binary format
64 | """
65 | if hex_format and is_hex(s):
66 | s = unhexlify(s)
67 | return hashlib.new('ripemd160', bin_sha256(s)).digest()
68 |
69 |
70 | def hex_hash160(s, hex_format=False):
71 | """ s is in hex or binary format
72 | """
73 | if hex_format and is_hex(s):
74 | s = unhexlify(s)
75 | return hexlify(bin_hash160(s))
76 |
77 |
78 | def bin_sha256(bin_s):
79 | return sha256(bin_s).digest()
80 |
81 |
82 | def bin_double_sha256(bin_s):
83 | return bin_sha256(bin_sha256(bin_s))
84 |
85 |
86 | def reverse_hash(hash, hex_format=True):
87 | """ hash is in hex or binary format
88 | """
89 | if not hex_format:
90 | hash = hexlify(hash)
91 | return "".join(reversed([hash[i:i+2] for i in range(0, len(hash), 2)]))
92 |
93 |
94 | def hex_to_bin_reversed(s):
95 | return unhexlify(s.encode('utf8'))[::-1]
96 |
97 |
98 | def bin_to_hex_reversed(s):
99 | return hexlify(s[::-1])
100 |
--------------------------------------------------------------------------------
/virtualchain/lib/merkle.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | """
4 | Virtualchain
5 | ~~~~~
6 | copyright: (c) 2014-2015 by Halfmoon Labs, Inc.
7 | copyright: (c) 2016 by Blockstack.org
8 |
9 | This file is part of Virtualchain
10 |
11 | Virtualchain is free software: you can redistribute it and/or modify
12 | it under the terms of the GNU General Public License as published by
13 | the Free Software Foundation, either version 3 of the License, or
14 | (at your option) any later version.
15 |
16 | Virtualchain is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | GNU General Public License for more details.
20 | You should have received a copy of the GNU General Public License
21 | along with Virtualchain. If not, see .
22 | """
23 |
24 | from .hashing import bin_double_sha256, bin_to_hex_reversed, hex_to_bin_reversed
25 |
26 | def calculate_merkle_pairs(bin_hashes, hash_function=bin_double_sha256):
27 | """
28 | Calculate the parents of a row of a merkle tree.
29 | Takes in a list of binary hashes, returns a binary hash.
30 |
31 | The returned parents list is such that parents[i] == hash(bin_hashes[2*i] + bin_hashes[2*i+1]).
32 | """
33 | hashes = list(bin_hashes)
34 |
35 | # if there are an odd number of hashes, double up the last one
36 | if len(hashes) % 2 == 1:
37 | hashes.append(hashes[-1])
38 |
39 | new_hashes = []
40 | for i in range(0, len(hashes), 2):
41 | new_hashes.append(hash_function(hashes[i] + hashes[i+1]))
42 |
43 | return new_hashes
44 |
45 |
46 | def verify_merkle_path(merkle_root_hex, serialized_path, leaf_hash_hex, hash_function=bin_double_sha256):
47 | """
48 | Verify a merkle path. The given path is the path from two leaf nodes to the root itself.
49 |
50 | merkle_root_hex is a little-endian, hex-encoded hash.
51 | serialized_path is the serialized merkle path
52 | path_hex is a list of little-endian, hex-encoded hashes.
53 |
54 | Return True if the path is consistent with the merkle root.
55 | Return False if not.
56 | """
57 |
58 | merkle_root = hex_to_bin_reversed(merkle_root_hex)
59 | leaf_hash = hex_to_bin_reversed(leaf_hash_hex)
60 |
61 | path = MerkleTree.path_deserialize(serialized_path)
62 | path = [{'order': p['order'], 'hash': hex_to_bin_reversed(p['hash'])} for p in path]
63 |
64 | if len(path) == 0:
65 | raise ValueError("Empty path")
66 |
67 | cur_hash = leaf_hash
68 | for i in range(0, len(path)):
69 | if path[i]['order'] == 'l':
70 | # left sibling
71 | cur_hash = hash_function(path[i]['hash'] + cur_hash)
72 | elif path[i]['order'] == 'r':
73 | # right sibling
74 | cur_hash = hash_function(cur_hash + path[i]['hash'])
75 | elif path[i]['order'] == 'm':
76 | # merkle root
77 | assert len(path) == 1
78 | return cur_hash == path[i]['hash']
79 |
80 | return cur_hash == merkle_root
81 |
82 |
83 | class MerkleTree(object):
84 | def __init__(self, hex_hashes, hash_function=bin_double_sha256):
85 | """
86 | Make a merkle tree.
87 | * hashes is a list of hex-encoded hashes.
88 | * hash_function is a callable that takes a string as input and outputs a hash.
89 |
90 | The Merkle tree hashes will be converted to big-endian.
91 | """
92 | if len(hex_hashes) == 0:
93 | raise ValueError("At least one hash is required.")
94 |
95 | self.rows = []
96 |
97 | # convert to binary big-endian
98 | hashes = [hex_to_bin_reversed(h) for h in hex_hashes]
99 |
100 | # build the rows of the merkle tree
101 | self.rows.append(hashes)
102 | while len(hashes) > 1:
103 | hashes = calculate_merkle_pairs(hashes, hash_function=hash_function)
104 | self.rows.append(hashes)
105 |
106 |
107 | def get(self, row_index, column_index):
108 | """
109 | Get the hash at a given row and column index.
110 | Raise ValueError on out-of-bounds
111 | """
112 | if row_index + 1 > len(self.rows):
113 | raise ValueError("There aren't that many rows.")
114 |
115 | row = self.rows[row_index]
116 | if column_index + 1 > len(row):
117 | raise ValueError("There aren't that many items in that row.")
118 |
119 | return row[column_index]
120 |
121 |
122 | def root(self):
123 | """
124 | Returns the hex-encoded root (little-endian)
125 | """
126 | # return the merkle root
127 | bin_merkle_root = self.rows[-1][0]
128 | return bin_to_hex_reversed(bin_merkle_root)
129 |
130 |
131 | @classmethod
132 | def path_serialize(cls, path):
133 | """
134 | Given a list of [{'hash': ..., 'order': ...}], serialize it to a string.
135 | """
136 | # make it into a netstring
137 | path_parts = ['{}-{}'.format(p['order'], p['hash']) for p in path]
138 | path_ns_parts = ['{}:{},'.format(len(pp), pp) for pp in path_parts]
139 | path_str = ''.join(path_ns_parts)
140 | return '{}:{},'.format(len(path_str), path_str)
141 |
142 |
143 | @classmethod
144 | def path_deserialize(cls, serialized_path):
145 | """
146 | Given a netstring of path parts, go and parse it back into [{'hash': ..., 'order': ...}]
147 | """
148 | def _chomp_netstring_payload(s):
149 | try:
150 | ns_len_str, ns_body = s.split(':', 1)
151 | ns_len = int(ns_len_str)
152 | assert ns_body[ns_len] == ','
153 | ns_payload = ns_body[:ns_len]
154 | return ns_payload, ns_body[ns_len+1:]
155 | except:
156 | raise ValueError("Invalid netstring '{}'".format(s))
157 |
158 | path_str, extra = _chomp_netstring_payload(serialized_path)
159 | if len(extra) > 0:
160 | raise ValueError("Danlging data in '{}'".format(serialized_path))
161 |
162 | path = []
163 | while True:
164 | path_part, path_str = _chomp_netstring_payload(path_str)
165 | try:
166 | order, hash_hex = path_part.split('-', 1)
167 | assert order in ['l', 'r', 'm']
168 | path.append({'order': order, 'hash': hash_hex})
169 | except:
170 | raise ValueError("Invalid path entry {}".format(path_part))
171 |
172 | if len(path_str) == 0:
173 | break
174 |
175 | return path
176 |
177 |
178 | def path(self, leaf_hash_hex, serialize=True):
179 | """
180 | Get the path (as a list of hashes) from the leaf hash to the root.
181 | leaf_hash_hex is hex-encoded, little-endian.
182 |
183 | The returned path will be a list of {'hash': hex-encoded little-endian hash, 'order': 'l' or 'r'}
184 |
185 | Raise ValueError if leaf_hash is not present in the tree.
186 | """
187 |
188 | leaf_hash = hex_to_bin_reversed(leaf_hash_hex)
189 |
190 | # sanity check
191 | found = False
192 | ri = None # index into self.rows where leaf_hash occurs. Note that self.rows[0] is the bottom (leaves) of the Merkle tree.
193 | for ri, row in enumerate(self.rows):
194 | found = found or (leaf_hash in row)
195 | if found:
196 | break
197 |
198 | if not found:
199 | raise ValueError("Hash {} is not present in Merkle tree {}".format(leaf_hash, self.root()))
200 |
201 | path = []
202 | cur_hash = leaf_hash
203 | for i in range(ri, len(self.rows)-1):
204 | # find sibling
205 | sibling = {}
206 | leaf_index = self.rows[i].index(cur_hash)
207 | if leaf_index % 2 == 0:
208 | # append left sibling
209 | sibling_hash = None
210 | if leaf_index+1 >= len(self.rows[i]):
211 | # double-up the last hash
212 | assert leaf_index+1 == len(self.rows[i]), 'leaf_index = {}, i = {}, len(rows[i]) = {}, rows[0] = {}'.format(leaf_index, i, len(self.rows[i]), ','.join(r.encode('hex') for r in self.rows[0]))
213 | sibling_hash = self.rows[i][-1]
214 | else:
215 | sibling_hash = self.rows[i][leaf_index+1]
216 |
217 | sibling['hash'] = bin_to_hex_reversed(sibling_hash)
218 | sibling['order'] = 'r'
219 | else:
220 | # append right sibling
221 | sibling['hash'] = bin_to_hex_reversed(self.rows[i][leaf_index-1])
222 | sibling['order'] = 'l'
223 |
224 | path.append(sibling)
225 |
226 | # find parent
227 | cur_hash = self.rows[i+1][leaf_index/2]
228 |
229 | if len(path) == 0:
230 | # single-node merkle tree
231 | path = [{'hash': bin_to_hex_reversed(self.rows[-1][0]), 'order': 'm'}]
232 |
233 | if not serialize:
234 | return path
235 | else:
236 | return self.path_serialize(path)
237 |
238 |
239 | if __name__ == "__main__":
240 | print 'test merkle tree'
241 |
242 | import os
243 |
244 | fixtures = [
245 | [os.urandom(32) for _ in range(0,32)],
246 | [os.urandom(32) for _ in range(0,31)],
247 | [os.urandom(32) for _ in range(0,1)],
248 | ['abcde' for _ in range(0,32)],
249 | ['abcde' for _ in range(0,31)],
250 | ['abcde' for _ in range(0,1)],
251 | [h.decode('hex') for h in ['02125585a9b812347c21c9f1827463ccb93a5096fb1f846b83652353fbb53418','f5c366f5aa9f21b4823ac167e8a062805f54bf99cb56be3fd1bd500bd5a20609','7358bf608d6ed1010cc86c1be5df4f773e7a2d6f00f3f3284bd742a55ea4a382','952dfe16fb9de054e291ef5d6dbacf381a93dffc12fdea74305fe3723016bf4b','a6c38dd08339595abd473c2351018d6d9ec968a44a53c6f06666141ec52568ae','aa950063768b7de1dbb0ae3bc3d872b3b7c8ac63defa02c7fe5e7cae93d11d23','c8d64f8ac60cbae1dd97cf373a4114097586fee63a8fed2e46add59eba7c8072','6a49bc047d9330cadeee4558da2a4da76aff1419d33f4b3d2800a55f26977fe4','b1eb9cae861e31b7177ce87fc3afde1618f69349dc1bf3e11deb86ea8586cf67','d8335aca79d8a0d20edd653905cc5d7a4a3e1986269d56b5949d08baad0046df','b58bfc1ab8c3557fb5de0014c58469f9ff6b68f407983fbe0b5387bd6485fc86']],
252 | ]
253 |
254 | for i, data in enumerate(fixtures):
255 | print '\nfixture {} ({} entries)\n'.format(i, len(data))
256 |
257 | data_hashes = [bin_to_hex_reversed(bin_double_sha256(d)) for d in data]
258 |
259 | mt = MerkleTree(data_hashes)
260 | mps = []
261 | for j, dh in enumerate(data_hashes):
262 | mp = mt.path(dh, serialize=False)
263 | mp_str = mt.path_serialize(mp)
264 | recombined_mp = mt.path_deserialize(mp_str)
265 |
266 | assert mp == recombined_mp
267 |
268 | mps.append(mp_str)
269 |
270 | print 'dh[{}] = {}'.format(j, dh)
271 | print 'path from {} to {} is {}'.format(dh, mt.root(), mp)
272 | print 'path from {} to {} is {}'.format(dh, mt.root(), mp_str)
273 |
274 | for i, mp in enumerate(mps):
275 | assert verify_merkle_path(mt.root(), mp, data_hashes[i]), 'failed to verify {} to {}'.format(data_hashes[i], mt.root())
276 |
277 | for i, mp in enumerate(mps):
278 | # corrupt a hash
279 | mp_obj = mt.path_deserialize(mp)
280 | mp_obj[-1]['hash'] = mp_obj[-1]['hash'][::-1]
281 | mp = mt.path_serialize(mp_obj)
282 |
283 | assert not verify_merkle_path(mt.root(), mp, data_hashes[i]), 'failed to verify {} to {}'.format(data_hashes[i], mt.root())
284 |
--------------------------------------------------------------------------------
/virtualchain/version.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | """
4 | Virtualchain
5 | ~~~~~
6 | copyright: (c) 2014 by Halfmoon Labs, Inc.
7 | copyright: (c) 2015-2018 by Blockstack.org
8 |
9 | This file is part of Virtualchain
10 |
11 | Virtualchain is free software: you can redistribute it and/or modify
12 | it under the terms of the GNU General Public License as published by
13 | the Free Software Foundation, either version 3 of the License, or
14 | (at your option) any later version.
15 |
16 | Virtualchain is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | GNU General Public License for more details.
20 | You should have received a copy of the GNU General Public License
21 | along with Virtualchain. If not, see .
22 | """
23 |
24 | __version__ = '20.0.1.0'
25 |
--------------------------------------------------------------------------------
/virtualchain/virtualchain.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | """
4 | Virtualchain
5 | ~~~~~
6 | copyright: (c) 2014-15 by Halfmoon Labs, Inc.
7 | copyright: (c) 2016 by Blockstack.org
8 |
9 | This file is part of Virtualchain
10 |
11 | Virtualchain is free software: you can redistribute it and/or modify
12 | it under the terms of the GNU General Public License as published by
13 | the Free Software Foundation, either version 3 of the License, or
14 | (at your option) any later version.
15 |
16 | Virtualchain is distributed in the hope that it will be useful,
17 | but WITHOUT ANY WARRANTY; without even the implied warranty of
18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 | GNU General Public License for more details.
20 | You should have received a copy of the GNU General Public License
21 | along with Virtualchain. If not, see .
22 | """
23 |
24 | import os
25 | import datetime
26 |
27 | from .lib import config, indexer
28 | from .lib.blockchain import session
29 |
30 | log = config.get_logger("virtualchain")
31 |
32 | def sync_virtualchain(blockchain_opts, last_block, state_engine, expected_snapshots={}, tx_filter=None ):
33 | """
34 | Synchronize the virtual blockchain state up until a given block.
35 |
36 | Obtain the operation sequence from the blockchain, up to and including last_block.
37 | That is, go and fetch each block we haven't seen since the last call to this method,
38 | extract the operations from them, and record in the given working_dir where we left
39 | off while watching the blockchain.
40 |
41 | Store the state engine state, consensus snapshots, and last block to the working directory.
42 | Return True on success
43 | Return False if we're supposed to stop indexing
44 | Abort the program on error. The implementation should catch timeouts and connection errors
45 | """
46 |
47 | rc = False
48 | start = datetime.datetime.now()
49 | while True:
50 | try:
51 |
52 | # advance state
53 | rc = indexer.StateEngine.build(blockchain_opts, last_block + 1, state_engine, expected_snapshots=expected_snapshots, tx_filter=tx_filter )
54 | break
55 |
56 | except Exception, e:
57 | log.exception(e)
58 | log.error("Failed to synchronize chain; exiting to safety")
59 | os.abort()
60 |
61 | time_taken = "%s seconds" % (datetime.datetime.now() - start).seconds
62 | log.info(time_taken)
63 |
64 | return rc
65 |
66 |
67 | def virtualchain_set_opfields( op, **fields ):
68 | """
69 | Pass along virtualchain-reserved fields to a virtualchain operation.
70 | This layer of indirection is meant to help with future compatibility,
71 | so virtualchain implementations do not try to set operation fields
72 | directly.
73 | """
74 |
75 | # warn about unsupported fields
76 | for f in fields.keys():
77 | if f not in indexer.RESERVED_KEYS:
78 | log.warning("Unsupported virtualchain field '%s'" % f)
79 |
80 | # propagate reserved fields
81 | for f in fields.keys():
82 | if f in indexer.RESERVED_KEYS:
83 | op[f] = fields[f]
84 |
85 | return op
86 |
87 |
88 | def connect_bitcoind(opts):
89 | """
90 | Top-level method to connect to bitcoind,
91 | using either a built-in default, or a module
92 | to be loaded at runtime whose path is referred
93 | to by the environment variable
94 | VIRTUALCHAIN_MOD_CONNECT_BLOCKCHAIN.
95 | """
96 | connect_bitcoind_factory = session.connect_bitcoind_impl
97 | return connect_bitcoind_factory( opts )
98 |
99 |
--------------------------------------------------------------------------------