Full Code of in3rsha/bitcoin-to-neo4j for AI

master 0495bf8ef65a cached
22 files
113.5 KB
32.5k tokens
32 symbols
1 requests
Download .txt
Repository: in3rsha/bitcoin-to-neo4j
Branch: master
Commit: 0495bf8ef65a
Files: 22
Total size: 113.5 KB

Directory structure:
gitextract_r9ptinru/

├── .gitignore
├── LICENSE
├── README.md
├── composer.json
├── config.php
├── cypher/
│   ├── block-genesis.cypher
│   ├── block.cypher
│   ├── tx-coinbase.cypher
│   └── tx.cypher
├── cyphertx.php
├── docs/
│   ├── benchmark.md
│   ├── cypher.md
│   └── how.md
├── functions/
│   ├── README.md
│   ├── basic.php
│   ├── block.php
│   ├── hash.php
│   ├── keys.php
│   ├── readtx.php
│   ├── script.php
│   └── tx.php
└── main.php

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
vendor
composer.lock
.idea


================================================
FILE: LICENSE
================================================
### GNU GENERAL PUBLIC LICENSE

Version 3, 29 June 2007

Copyright (C) 2007 Free Software Foundation, Inc.
<http://fsf.org/>

Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.

### Preamble

The GNU General Public License is a free, copyleft license for
software and other kinds of works.

The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom
to share and change all versions of a program--to make sure it remains
free software for all its users. We, the Free Software Foundation, use
the GNU General Public License for most of our software; it applies
also to any other work released this way by its authors. You can apply
it to your programs, too.

When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you
have certain responsibilities if you distribute copies of the
software, or if you modify it: responsibilities to respect the freedom
of others.

For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.

Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the
manufacturer can do so. This is fundamentally incompatible with the
aim of protecting users' freedom to change the software. The
systematic pattern of such abuse occurs in the area of products for
individuals to use, which is precisely where it is most unacceptable.
Therefore, we have designed this version of the GPL to prohibit the
practice for those products. If such problems arise substantially in
other domains, we stand ready to extend this provision to those
domains in future versions of the GPL, as needed to protect the
freedom of users.

Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish
to avoid the special danger that patents applied to a free program
could make it effectively proprietary. To prevent this, the GPL
assures that patents cannot be used to render the program non-free.

The precise terms and conditions for copying, distribution and
modification follow.

### TERMS AND CONDITIONS

#### 0. Definitions.

"This License" refers to version 3 of the GNU General Public License.

"Copyright" also means copyright-like laws that apply to other kinds
of works, such as semiconductor masks.

"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.

To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of
an exact copy. The resulting work is called a "modified version" of
the earlier work or a work "based on" the earlier work.

A "covered work" means either the unmodified Program or a work based
on the Program.

To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user
through a computer network, with no transfer of a copy, is not
conveying.

An interactive user interface displays "Appropriate Legal Notices" to
the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

#### 1. Source Code.

The "source code" for a work means the preferred form of the work for
making modifications to it. "Object code" means any non-source form of
a work.

A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

The Corresponding Source need not include anything that users can
regenerate automatically from other parts of the Corresponding Source.

The Corresponding Source for a work in source code form is that same
work.

#### 2. Basic Permissions.

All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

You may make, run and propagate covered works that you do not convey,
without conditions so long as your license otherwise remains in force.
You may convey covered works to others for the sole purpose of having
them make modifications exclusively for you, or provide you with
facilities for running those works, provided that you comply with the
terms of this License in conveying all material for which you do not
control copyright. Those thus making or running the covered works for
you must do so exclusively on your behalf, under your direction and
control, on terms that prohibit them from making any copies of your
copyrighted material outside their relationship with you.

Conveying under any other circumstances is permitted solely under the
conditions stated below. Sublicensing is not allowed; section 10 makes
it unnecessary.

#### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.

No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such
circumvention is effected by exercising rights under this License with
respect to the covered work, and you disclaim any intention to limit
operation or modification of the work as a means of enforcing, against
the work's users, your or third parties' legal rights to forbid
circumvention of technological measures.

#### 4. Conveying Verbatim Copies.

You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

#### 5. Conveying Modified Source Versions.

You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these
conditions:

-   a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.
-   b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under
    section 7. This requirement modifies the requirement in section 4
    to "keep intact all notices".
-   c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy. This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged. This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.
-   d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

#### 6. Conveying Non-Source Forms.

You may convey a covered work in object code form under the terms of
sections 4 and 5, provided that you also convey the machine-readable
Corresponding Source under the terms of this License, in one of these
ways:

-   a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.
-   b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the Corresponding
    Source from a network server at no charge.
-   c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source. This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.
-   d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge. You need not require recipients to copy the
    Corresponding Source along with the object code. If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source. Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.
-   e) Convey the object code using peer-to-peer transmission,
    provided you inform other peers where the object code and
    Corresponding Source of the work are being offered to the general
    public at no charge under subsection 6d.

A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal,
family, or household purposes, or (2) anything designed or sold for
incorporation into a dwelling. In determining whether a product is a
consumer product, doubtful cases shall be resolved in favor of
coverage. For a particular product received by a particular user,
"normally used" refers to a typical or common use of that class of
product, regardless of the status of the particular user or of the way
in which the particular user actually uses, or expects or is expected
to use, the product. A product is a consumer product regardless of
whether the product has substantial commercial, industrial or
non-consumer uses, unless such uses represent the only significant
mode of use of the product.

"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to
install and execute modified versions of a covered work in that User
Product from a modified version of its Corresponding Source. The
information must suffice to ensure that the continued functioning of
the modified object code is in no case prevented or interfered with
solely because modification has been made.

If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or
updates for a work that has been modified or installed by the
recipient, or for the User Product in which it has been modified or
installed. Access to a network may be denied when the modification
itself materially and adversely affects the operation of the network
or violates the rules and protocols for communication across the
network.

Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

#### 7. Additional Terms.

"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders
of that material) supplement the terms of this License with terms:

-   a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or
-   b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or
-   c) Prohibiting misrepresentation of the origin of that material,
    or requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or
-   d) Limiting the use for publicity purposes of names of licensors
    or authors of the material; or
-   e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or
-   f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions
    of it) with contractual assumptions of liability to the recipient,
    for any liability that these contractual assumptions directly
    impose on those licensors and authors.

All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions; the
above requirements apply either way.

#### 8. Termination.

You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

However, if you cease all violation of this License, then your license
from a particular copyright holder is reinstated (a) provisionally,
unless and until the copyright holder explicitly and finally
terminates your license, and (b) permanently, if the copyright holder
fails to notify you of the violation by some reasonable means prior to
60 days after the cessation.

Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

#### 9. Acceptance Not Required for Having Copies.

You are not required to accept this License in order to receive or run
a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

#### 10. Automatic Licensing of Downstream Recipients.

Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.

An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

#### 11. Patents.

A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".

A contributor's "essential patent claims" are all patent claims owned
or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

A patent license is "discriminatory" if it does not include within the
scope of its coverage, prohibits the exercise of, or is conditioned on
the non-exercise of one or more of the rights that are specifically
granted under this License. You may not convey a covered work if you
are a party to an arrangement with a third party that is in the
business of distributing software, under which you make payment to the
third party based on the extent of your activity of conveying the
work, and under which the third party grants, to any of the parties
who would receive the covered work from you, a discriminatory patent
license (a) in connection with copies of the covered work conveyed by
you (or copies made from those copies), or (b) primarily for and in
connection with specific products or compilations that contain the
covered work, unless you entered into that arrangement, or that patent
license was granted, prior to 28 March 2007.

Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

#### 12. No Surrender of Others' Freedom.

If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under
this License and any other pertinent obligations, then as a
consequence you may not convey it at all. For example, if you agree to
terms that obligate you to collect a royalty for further conveying
from those to whom you convey the Program, the only way you could
satisfy both those terms and this License would be to refrain entirely
from conveying the Program.

#### 13. Use with the GNU Affero General Public License.

Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

#### 14. Revised Versions of this License.

The Free Software Foundation may publish revised and/or new versions
of the GNU General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in
detail to address new problems or concerns.

Each version is given a distinguishing version number. If the Program
specifies that a certain numbered version of the GNU General Public
License "or any later version" applies to it, you have the option of
following the terms and conditions either of that numbered version or
of any later version published by the Free Software Foundation. If the
Program does not specify a version number of the GNU General Public
License, you may choose any version ever published by the Free
Software Foundation.

If the Program specifies that a proxy can decide which future versions
of the GNU General Public License can be used, that proxy's public
statement of acceptance of a version permanently authorizes you to
choose that version for the Program.

Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

#### 15. Disclaimer of Warranty.

THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
CORRECTION.

#### 16. Limitation of Liability.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

#### 17. Interpretation of Sections 15 and 16.

If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

END OF TERMS AND CONDITIONS

### How to Apply These Terms to Your New Programs

If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these
terms.

To do so, attach the following notices to the program. It is safest to
attach them to the start of each source file to most effectively state
the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.

        <one line to give the program's name and a brief idea of what it does.>
        Copyright (C) <year>  <name of author>

        This program is free software: you can redistribute it and/or modify
        it under the terms of the GNU General Public License as published by
        the Free Software Foundation, either version 3 of the License, or
        (at your option) any later version.

        This program is distributed in the hope that it will be useful,
        but WITHOUT ANY WARRANTY; without even the implied warranty of
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
        GNU General Public License for more details.

        You should have received a copy of the GNU General Public License
        along with this program.  If not, see <http://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper
mail.

If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

        <program>  Copyright (C) <year>  <name of author>
        This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
        This is free software, and you are welcome to redistribute it
        under certain conditions; type `show c' for details.

The hypothetical commands \`show w' and \`show c' should show the
appropriate parts of the General Public License. Of course, your
program's commands might be different; for a GUI interface, you would
use an "about box".

You should also get your employer (if you work as a programmer) or
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. For more information on this, and how to apply and follow
the GNU GPL, see <http://www.gnu.org/licenses/>.

The GNU General Public License does not permit incorporating your
program into proprietary programs. If your program is a subroutine
library, you may consider it more useful to permit linking proprietary
applications with the library. If this is what you want to do, use the
GNU Lesser General Public License instead of this License. But first,
please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.

================================================
FILE: README.md
================================================
**This project is now archived.**

This tool _does_ work for importing blockchain data in to Neo4j, but it's **very slow**.

It imports each block and transaction individually, and there's so much data that it will take years to get up to date with the current tip of the blockchain (if ever).

I haven't got the time to maintain this project, so that's why I'm archiving it. However, if you want to create your own (faster) tool, I've written a guide on [how to import Bitcoin in to Neo4j](docs/how.md) that you may find helpful.

-----

# Bitcoin to Neo4j

![](docs/images/splash.png)

_See the [cypher examples](docs/cypher.md) for cool screenshots._

## Summary.

This script _runs through_ a **bitcoin blockchain** and inserts it in to a **Neo4j graph database**.

I use this script to power my bitcoin blockchain browser: <http://learnmeabitcoin.com/browser> 

**Important:**

* **The resulting Neo4j database is roughly _6x_ the size of the blockchain.** So if the blockchain is 100GB, your Neo4j database will be **600GB**.
* **It may take 60+ days to finish importing the entire blockchain.** Instead of doing a bulk import of the entire blockchain, this script runs through each `blk.dat`<sup>[1](#blkdat)</sup> file and inserts each block and transaction it encounters. So whilst it takes "a while" for an initial import, when it's complete it will continuously add new blocks as they arrive.

Nonetheless, you can still [browse](docs/cypher.md) whatever is in the database whilst this script is running.

## Install.

I have only used this on **Linux (Ubuntu)**.

It should work on OSX and Windows, but I haven't got installation instructions for those.

### Software.

This script makes use of the following software: 

1. **[Bitcoin Core](https://bitcoin.org/en/download)**

```bash
sudo add-apt-repository ppa:bitcoin/bitcoin
sudo apt update
sudo apt install bitcoind
```

2. **[Neo4j 4.0+](https://neo4j.com/)**

```bash
sudo add-apt-repository ppa:webupd8team/java
sudo apt update
sudo apt install oracle-java8-installer

wget -O - https://debian.neo4j.org/neotechnology.gpg.key | sudo apt-key add -
echo 'deb https://debian.neo4j.org/repo stable/' | sudo tee /etc/apt/sources.list.d/neo4j.list
sudo apt update && sudo apt install neo4j
```

3. **[PHP 8.0+](http://php.net/)** - The main script and it's library functions are written in PHP.

```bash
# The following php-* libraries are required for this script to run
sudo apt install php php-dev php-gmp php-curl php-bcmath php-mbstring
```

4. **[Redis 5.0.3+](https://redis.io/)** - This is used for storing the state of the import, so that the script can be stopped and started at any time.

```bash
sudo apt install build-essential
sudo apt install redis-server
```

### Dependencies.

**1. [neo4j-php-client](https://github.com/neo4j-php/neo4j-php-client)** (install via [composer](https://getcomposer.org/doc/00-intro.md)).

This is the driver that allows PHP to connect to your Neo4j database. I have included a `composer.json` file, so navigate to the project's home directory and install it with:

```bash
composer install
```

**2. [phpredis](https://github.com/phpredis/phpredis)**

This allows PHP to connect to Redis. These instructions should install the version needed for _PHP7_ (which is different to the default installation instructions that come with phpredis, which is aimed at PHP5).

```bash
# Install phpredis
sudo apt install php-redis
```

### Config.

The `config.php` file contains all the configuration settings. You probably only need to change:

1. The location of your `~/.bitcoin/blocks` folder 
2. Your Neo4j username and password.

```php
define("BLOCKS", '/home/user/.bitcoin/blocks'); // the location of the blk.dat files you want to read
define("TESTNET", false); // are you reading blk.dat files from Bitcoin's testnet?

define("NEO4J_USER", 'neo4j');
define("NEO4J_PASS", 'neo4j');
define("NEO4J_IP", 'localhost');    
define("NEO4J_PORT", '7687'); // this is the port used for the bolt protocol

define("REDIS_IP", 'localhost');    
define("REDIS_PORT", '6379');

```

## Run.

Make sure Neo4j is running (`sudo service neo4j start`), then start running the script with:

```
php main.php
```

This will start importing in to Neo4j, printing out the results as it goes.

[![](docs/images/stdout-resized.gif)](docs/images/stdout.gif)

Here's an [annotated explanation of the results](docs/images/stdout-explained.png)

### Tip:

**You can stop and restart the script at any time, as the script stores its position using Redis.**

The script sets the following keys in Redis:

* `bitcoin-to-neo4j` - This stores the number of the current blk.dat file, and it's position in that file.
* `bitcoin-to-neo4j:orphans` - This stores the blockhashes of orphan blocks. You see, the blocks in the blk.dat files are not stored in order (based on their height), so by saving blocks that we cannot calculate a height for yet (because we haven't encountered the block it builds upon), we are able set the height later on.
* `bitcoin-to-neo4j:tip` - This is the height of the current longest chain we have got in Neo4j. It's not needed for the script to work, but it's useful for seeing the progress of the script.
* `bitcoin-to-neo4j:log` - Logs showing the amount of time that the blkXXXXX.dat files took to be imported.

When Redis is installed, you can look at each of these with:

```bash
redis-cli hgetall bitcoin-to-neo4j
redis-cli hgetall bitcoin-to-neo4j:orphans
redis-cli hgetall bitcoin-to-neo4j:tip
redis-cli hgetall bitcoin-to-neo4j:log
```

## FAQ

### How does this work?

I've written a complete guide on [how to import Bitcoin in to Neo4j](docs/how.md).

It covers the basic data structures of Bitcoin, and how to represent them in Neo4j.

### How can I query this database?

Here are some [example cypher queries](docs/cypher.md), including some screenshots.

### What are the hardware requirements?

1. A really ****ing big SSD.

Other than that, I run this on my _Thinkpad X220_ (8GB Ram, 4x2.60GHz CPU) without any problems. It took about 2 weeks to import the full _testnet_ blockchain (50GB total), but my laptop didn't explode.

However, if you want to help things along:

* Make sure you're using an **SSD** for fast write speeds.
* Give as much **RAM** to Neo4j as possible. This helps with looking up existing nodes in the database, which this script does continually as it merges new transactions on to old ones.
    * Heap Size: I think a minimum 4GB does the trick.
    * Page Cache: Whatever RAM you have got left over.

CPU isn't much of a factor in comparison to RAM and a fast disk.

_See [Neo4j Performance](http://neo4j.com/docs/operations-manual/current/performance/) for more details._

### How big is this graph database?

It's constantly growing, but as of 17 May 2017 (blockchain height: 466,874, blockchain size: 114GB):

* Nodes: 1,587,199,550 
* Relationships: 2,503,359,310
* Size: 625 GB

### Does this import the _entire_ blockchain?

Yes, no data is left behind. If you really wanted to you could convert the data back in to binary as it is found in the raw `blk.dat` files.

For example, the "serialized" transaction data<sup>[2](#transaction-data)</sup>  on my explorer is actually data from the graph converted back in to it's original format: [Transaction: be56667fed4336efc08c6a1addfba0008169861af906e7f436ffcc86935d2b2e](http://learnmeabitcoin.com/browser/transaction/be56667fed4336efc08c6a1addfba0008169861af906e7f436ffcc86935d2b2e) _(click on "serialized" in the top-right)_

### Why doesn't this use Neo4j's _Bulk Import Tool_?

Because I needed a script that would add blocks as they arrived.

It would involve writing another tool for a bulk import. I haven't tried.

### Why is this written in PHP?

Because it's the language I knew best when I started this.

Or in other words, I'm not the king of programming, and PHP does the job.

## Footnotes

* <a name="blkdat">1</a>: <http://learnmeabitcoin.com/glossary/blkdat>
* <a name="transaction-data">2</a>: <http://learnmeabitcoin.com/glossary/transaction-data>


================================================
FILE: composer.json
================================================
{
    "require": {
        "laudis/neo4j-php-client": "^2.0",
        "ext-redis": "*",
        "ext-gmp": "*",
        "ext-bcmath": "*",
        "ext-ctype": "*"
    },
    "config": {
        "allow-plugins": {
          "php-http/discovery": true
        }
    }
}


================================================
FILE: config.php
================================================
<?php

define("BLOCKS", '/home/user/.bitcoin/blocks');
define("TESTNET", false); // Probably not, but; are you reading blk.dat files from Bitcoin's testnet?

define("NEO4J_USER", 'neo4j');
define("NEO4J_PASS", 'neo4j');
define("NEO4J_IP", 'localhost');    
define("NEO4J_PORT", '7687');       // this is the port used for the bolt protocol

define("REDIS_IP", 'localhost');    
define("REDIS_PORT", '6379');


================================================
FILE: cypher/block-genesis.cypher
================================================
// Create Block
MERGE (block:block {hash:$blockhash})
MERGE (block)-[:coinbase]->(:output:coinbase)
SET
    block.size=$blocksize,
    block.txcount=$txcount,
    block.version=$version,
    block.prevblock=$prevblock,
    block.merkleroot=$merkleroot,
    block.time=$timestamp,
    block.bits=$bits,
    block.nonce=$nonce

// Set Height
SET block.height=0

// Return
RETURN block.height as height, block.prevblock as prevblock

================================================
FILE: cypher/block.cypher
================================================
// Create Block
MERGE (block:block {hash:$blockhash})
MERGE (block)-[:coinbase]->(:output:coinbase)
SET
    block.size=$blocksize,
    block.txcount=$txcount,
    block.version=$version,
    block.prevblock=$prevblock,
    block.merkleroot=$merkleroot,
    block.time=$timestamp,
    block.bits=$bits,
    block.nonce=$nonce

// Create Chain
MERGE (prevblock:block {hash:$prevblock})
MERGE (block)-[:chain]->(prevblock)

// Set Height
SET block.height=prevblock.height+1

// Return
RETURN block.height as height, block.prevblock as prevblock

================================================
FILE: cypher/tx-coinbase.cypher
================================================
// Create Transaction
MATCH (block :block {hash:$blockhash})-[:coinbase]->(coinbase :coinbase)
MERGE (tx:tx {txid:$txid})
MERGE (tx)-[:inc {i:$t}]->(block)
SET tx += $tx

// Coinbase Input
MERGE (coinbase)-[coinbasein:in {vin:0, scriptSig:$coinbase_script, sequence:$coinbase_sequence}]->(tx)
FOREACH (input in $inputs |
  SET coinbasein.witness = input.witness
)

// Outputs
WITH tx
FOREACH (output in $outputs |
  MERGE (out :output {index: output.index})
  MERGE (tx)-[:out {vout: output.vout}]->(out)
  // This uses the foreach hack to only create an address node if the address value is not an empty string
  FOREACH(ignoreMe IN CASE WHEN output.addresses <> '' THEN [1] ELSE [] END |
    MERGE (address :address {address: output.addresses})
		MERGE (out)-[:locked]->(address)
	)

  MERGE (out)-[:in]->(existing)
  ON CREATE SET
    out.value= output.value,
    out.scriptPubKey= output.scriptPubKey
  ON MATCH SET
    out.value= output.value,
    out.scriptPubKey= output.scriptPubKey,
    existing.fee = existing.fee + output.value
)

// Fee
WITH tx
MATCH (i :output)-[:in]->(tx)
WITH tx, sum(i.value) - $outtotal as fee
SET tx.fee=fee

// Return
RETURN fee

================================================
FILE: cypher/tx.cypher
================================================
// Create Transaction
MATCH (block :block {hash:$blockhash})
MERGE (tx:tx {txid:$txid})
MERGE (tx)-[:inc {i:$t}]->(block)
SET tx += $tx

// Inputs
WITH tx
FOREACH (input in $inputs |
	MERGE (in :output {index: input.index})
	MERGE (in)-[:in {vin: input.vin, scriptSig: input.scriptSig, sequence: input.sequence, witness: input.witness}]->(tx)
	REMOVE in:unspent
)

// Outputs
FOREACH (output in $outputs |
	MERGE (out :output {index: output.index})
	MERGE (tx)-[:out {vout: output.vout}]->(out)
  // This uses the foreach hack to only create an address node if the address value is not an empty string
	FOREACH(ignoreMe IN CASE WHEN output.addresses <> '' THEN [1] ELSE [] END |
		MERGE (address :address {address: output.addresses})
		MERGE (out)-[:locked]->(address)
	)

	MERGE (out)-[:in]->(existing)
	ON CREATE SET
		out.value= output.value,
		out.scriptPubKey= output.scriptPubKey
	ON MATCH SET
		out.value= output.value,
		out.scriptPubKey= output.scriptPubKey,
		existing.fee = existing.fee + output.value
)

// Fee
WITH tx
MATCH (i :output)-[:in]->(tx)
WITH tx, sum(i.value) - $outtotal as fee
SET tx.fee=fee

// Return
RETURN fee

================================================
FILE: cyphertx.php
================================================
<?php
/*
 * author:  Greg Walker
 * website: http://learnmeabitcoin.com
 * license: GPLv3
*/

function cypherTx($neo, $transaction, $t, $blockhash, $cypher) {

	// =================
	// Cypher Parameters
	// =================
	$decoded = decoderawtransaction($transaction); // decode the raw transaction string

	$size = strlen($transaction)/2; $sizedisplay = str_pad('['. $size .' bytes]', 15, ' ');
	$relationshipsdisplay = str_pad('('. count($decoded['vin']) .':'. count($decoded['vout']) .')', 7, ' ');
	$txid = $decoded['txid'];
	$t_display = str_pad($t.'.', 5, ' ');

	echo "   $t_display $txid $sizedisplay $relationshipsdisplay ";

	// skip transaction if it already exists in database
	$check = $neo->run('MATCH (tx :tx {txid:$txid}) RETURN tx', ['txid' => $txid]);
	$exists = !$check->isEmpty(); // is there a record for this txid?

	if ($exists) {

		// if this is a coinbase transaction, always merge it to the block (because two coinbase txs can have the same txid)
		if ($decoded['vin'][0]['txid'] == '0000000000000000000000000000000000000000000000000000000000000000') {
			$vin_coinbase = $decoded['vin'][0]['scriptSig']['hex']; // miners can put what they like in it
			$vin_sequence = $decoded['vin'][0]['sequence'];

			$neo->run('
			MATCH (tx :tx {txid:$txid}), (block :block {hash:$blockhash})-[:coinbase]->(coinbase :output:coinbase)
			WITH tx, block, coinbase
			MERGE (tx)-[:inc {i:$t}]->(block)
			MERGE (coinbase)-[in :in]->(tx)
			ON CREATE SET
				in.vin=0,
				in.scriptSig=$vin_coinbase,
				in.sequence=$vin_sequence
			',
			[
				'txid'         => $txid,
				'blockhash'    => $blockhash,
				't'            => $t,
				'vin_coinbase' => $vin_coinbase,
				'vin_sequence' => $vin_sequence,
			]
			);

			echo 'exists->block (+coinbase)';
		}

		else {
			// just connect this transaction to the block (in case we've got a transaction from an orphan block - don't want to forget to connect it to the block)
			$neo->run('
			MATCH (tx :tx {txid:$txid}), (block :block {hash:$blockhash})
			WITH tx, block
			MERGE (tx)-[:inc {i:$t}]->(block)
			',
			[
				'txid'         => $txid,
				'blockhash'    => $blockhash,
				't'            => $t,
			]
			);

			echo 'exists->block';
		}

	}
	// if this transaction doesn't exist in neo4j...
	else {

		// Build Parameter Array
		$parameters = array();
		$parameters['txid']      = $txid;
		$parameters['blockhash'] = $blockhash;
		$parameters['t']         = $t;

		// ----------
		// 1. TX node
		// ----------
		$parameters['tx']['version']  = $decoded['version'];
		$parameters['tx']['locktime'] = $decoded['locktime'];
		$parameters['tx']['size']     = $decoded['size'];
		if ($decoded['segwit']) {
			$parameters['tx']['segwit'] = $decoded['segwit']; // [marker][flag]
		}

		// ---------
		// 2. Inputs
		// ---------
		$i=0;
		$inputs = array();
		$coinbase = false; // will use this later to choose correct cypher query (coinbase transaction is slightly different to standard transaction)

		foreach ($decoded['vin'] as $vin) {

			// Store new witness data if this is a new Segregated Witness transaction
			if (array_key_exists('witness', $vin)) {
				$witness = $vin['witness']['hex'];
			}
			else {
				$witness = '';
			}

			$vin_txid                = $vin['txid']; // (no need to swapEndian - txid is already in searchable order)
			$vin_vout                = $vin['vout'];
			$vin_scriptSig           = $vin['scriptSig']['hex'];
			$vin_sequence            = $vin['sequence'];
				
			$inputs[$i]['vin']       = $i;
			$inputs[$i]['index']     = "$vin_txid:$vin_vout";
			$inputs[$i]['scriptSig'] = $vin_scriptSig;
			$inputs[$i]['sequence']  = $vin_sequence;
			$inputs[$i]['witness']   = $witness;

			$i++;
		}

		// If coinbase transaction
		if ($decoded['vin'][0]['txid'] == '0000000000000000000000000000000000000000000000000000000000000000') { // the input txid is all zeros for coinbase transactions
			$coinbase = true;
			$parameters['coinbase_script'] = $inputs[0]['scriptSig']; // miners can put what they like in this
			$parameters['coinbase_sequence'] = $inputs[0]['sequence'];
		}

		$parameters['inputs'] = $inputs;

		// ----------
		// 3. Outputs
		// ----------
		$i=0;
		$outputs = [];
		$outtotal = 0; // keep track of output values (for calculating fee later)

		foreach ($decoded['vout'] as $vout) {

			$value = $vout['value'];
			$scriptPubKey = $vout['scriptPubKey']['hex'];
			$addresses = $vout['scriptPubKey']['addresses'];

			$outputs[$i]['vout'] = $i;
			$outputs[$i]['index'] = "$txid:$i";
			$outputs[$i]['value'] = $value;
			$outputs[$i]['scriptPubKey'] = $scriptPubKey;
			$outputs[$i]['addresses'] = $addresses;
			
			$outtotal += $value;
			$i++;

		}

		$parameters['outputs'] = $outputs;
		$parameters['outtotal'] = $outtotal;


		// ============
		// Cypher Query
		// ============

		// Select Cypher Query
		if ($coinbase) {
			$query = $cypher['tx-coinbase'];
		}
		else {
			$query = $cypher['tx'];
		}

		// Run the full query to add the tx to the neo4j db (returns input total)
		while (true) {
			// Catch any errors caught by locks on nodes when writing to Neo4j
			try {
				$result = $neo->run($query, $parameters);
				break;
			}
			// Echo the error, then wait a second before trying again.
			catch (Exception $e) {
				echo $e;
				exit;
				sleep(1);
			}
		}

		// Get the fee (just to check) (Note: The fee will be negative if the inputs for this transaction are not in Neo4j yet, which is cool.)
		$fee = $result->first()->get('fee');
		echo "fee: $fee";

		return $fee;

	}

}


================================================
FILE: docs/benchmark.md
================================================
# Benchmarks

I did a few rough tests for common/useful bitcoin queries, each returning various numbers of nodes. I repeated each query 3 times.

Times are in ms (milliseconds).

## Blocks

Getting a block and all the transactions connected to it.

|Rows    |Time  |Time|Time|
|--------|------|----|----|
|2764    |1335  |282 |49  |
|1745    |1261  |37  |35  |
|687     |212   |19  |18  |
|550     |187   |18  |15  |

### Query

```
PROFILE MATCH (b:block)<-[:inc]-(t:tx) WHERE b.hash='000000000000000000ebaa7b3a804d9ba856b3bd61659f8f363bd42dc9c4a94c' RETURN b, t
```

## Transactions

Getting a transaction and all the inputs/outputs connected to it.

|Rows    |Time|Time|Time|
|--------|----|----|----|
|5026    |897 |282 |269 |
|94      |85  |17  |17  |
|4       |33  |8   |6   |

### Query

```
PROFILE MATCH (inputs)-[:in]->(tx:tx)-[:out]->(outputs) WHERE tx.txid='c21e2592abcd3eea532f51f3e18bbc9d9ad23b44f643d9aea580bf0ce0d4d0bc' OPTIONAL MATCH (inputs)-[:locked]->(inputsaddresses) OPTIONAL MATCH (outputs)-[:locked]->(outputsaddresses) OPTIONAL MATCH (tx)-[:inc]->(block) RETURN inputs, tx, outputs, block, inputsaddresses, outputsaddresses
```

## Addresses

Getting an address and all the outputs connected to it.

|Rows    |Time  |Time|Time|
|--------|------|----|----|
|3195800 |-     |-   |-   |
|27071   |12904 |344 |357 |
|830     |560   |13  |15  |
|188     |191   |15  |7   |

Note: The top query took over 60s to run each time, so I didn't get a final time for it.

### Query

```
MATCH (address :address)<-[:locked]-(output :output) WHERE address.address='$address' RETURN address, output
```

## Conclusion

Neo4j is fast enough for practical use.

The only query that really struggles is the addresses that have 300,000+ outputs attached to them. But these are rare. However for those the time becomes impractical.

================================================
FILE: docs/cypher.md
================================================
# Cypher Queries

Here are some example Cypher queries for getting useful data out of the Bitcoin Neo4j database.

## Blockchain

![](images/blockchain.png)

```
MATCH (start :block {height:100})-[chain :chain*0..4]->(block :block)-[:coinbase]->(cb :output)-[:in]->(coinbasetx :tx)
RETURN block, cb
```

Return a chain of blocks from a particular starting height, along with the coinbase (containing the block reward) from each block.

## Transaction.

![](images/transaction.png)

```
MATCH (inputs)-[:in]->(tx:tx)-[:out]->(outputs)
WHERE tx.txid='$txid'
OPTIONAL MATCH (inputs)-[:locked]->(inputsaddresses)
OPTIONAL MATCH (outputs)-[:locked]->(outputsaddresses)
OPTIONAL MATCH (tx)-[:inc]->(block)
RETURN inputs, tx, outputs, block, inputsaddresses, outputsaddresses
```

This will give you a transaction node with all of its inputs and all of its outputs, and any addresses those outputs are locked to. It will also return the block(s) the transaction is included in.

_Note: A transaction can be included in more than one block; in a block on the main chain, and in a block on a fork of the main chain. This typically happens when two different blocks are mined at the same time._

## Block

![](images/block.png)

```
MATCH (block :block)<-[:inc]-(tx :tx)
WHERE block.hash='$blockhash'
RETURN block, tx
```

This returns a block with all the transactions that are included in it.

## Address

![](images/address.png)

```
MATCH (address :address)<-[:locked]-(output :output)
WHERE address.address='$address'
RETURN address, output
```

Show all of the outputs that have been locked to an address.

_Note: Addresses are found from the scriptSig field of an output._

### Address Balance

```
MATCH (address :address)<-[:locked]-(output :output) 
WHERE address.address='$address' 
AND NOT (output)-[:in]->(:tx) 
RETURN sum(output.value) as balance
```

You can calculate the balance of an address by summing the values of the _unspent_ outputs that are locked to an address.

_Note: An unspent output is one that has not been included as an input in another transaction (`AND NOT (output)-[:in]->(:tx)`)._

## Paths

### Between Outputs

![](images/path_output.png)

```
MATCH (start :output {index:'$txid:vout'})
WITH start
MATCH (end :output {index:'$txid:vout'})
MATCH path=shortestPath( (start)-[:in|out*1..100]-(end) )
RETURN path
```

An output is like a single payment of bitcoins. This query allows you to see if two payments (outputs) are connected by a series of transactions.

_Note: Each output has a unique index property, which is a combination of the ID of the transaction it was created in (txid) and, and the output number from that transaction (vout). So an index would look something like this: `302c4757c5eb9f1633d5d076f150d320b8418f3a6295f5e87fc1805b9440cbc0:1`._

### Between Addresses

![](images/path_address.png)

```
MATCH (start :address {address:'$address1'})
WITH start
MATCH (end :address {address:'$address2'})
MATCH path=shortestPath( (start)-[:in|out|locked*1..100]-(end) )
RETURN path
```

This query allows you to see if two address are connected by a series of transactions. It also returns a path if there are common intermediary addresses.

### Between Addresses (Multiple Paths)

```
MATCH (start :address {address:'$address1'})
WITH start
MATCH (end :address {address:'$address2'})
MATCH path=allShortestPaths( (start)-[:in|out|locked*1..100]-(end) )
RETURN path
LIMIT 5
```

This is the most interesting query if you're looking to visualize all the connections between two addresses. It's best to start with a low `LIMIT` (i.e. small number of paths) and go from there.

## Historical Analyses

### First Transctions

The following query finds all non-coinbase transactions in the first 1000 blocks.

```cypher
MATCH (block:block)-[:inc]-(tx:tx)
WHERE block.height < 1000
  AND not exists((tx)<-[:in]-(:coinbase))
RETURN
  block.height AS block,
  tx.txid AS transaction,
  size((tx)<-[:in]-()) AS inputs,
  size((tx)-[:out]->()) AS outputs,
  tx.fee / tx.size AS fee_satoshis_per_byte
ORDER BY block
```

The first few rows returned are:

| block | transaction | inputs | outputs | fee_satoshis_per_byte |
|-------|-------------|--------|---------|-----------------------|
| 170 | f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16 | 1 | 2 | 0 |
| 181 | a16f3ce4dd5deb92d98ef5cf8afeaf0775ebca408f708b2146c4fb42b41e14be | 1 | 2 | 0 |
| 182 | 591e91f809d716912ca1d4a9295e70c3e78bab077683f79350f101da64588073 | 1 | 2 | 0 |


================================================
FILE: docs/how.md
================================================
# How to Import the Blockchain in to Neo4j

![Screenshot of the blockchain in the Neo4j browser.](images/how/neo4j-bitcoin.png)

This guide runs through the _basic_ steps for **importing the bitcoin blockchain in to a Neo4j graph database**.

The whole process is just about taking data from one format (blockchain data), and converting it in to another format (a graph database). The only thing that makes this slightly trickier than typical data conversion is that it's _helpful_ to understand of the structure of bitcoin data before you get started.

However, once you have imported the blockchain in to Neo4j, you can perform analysis on the graph database that would not be possible with SQL databases. For example, you can **follow the path of bitcoins to see if two different addresses are connected**:

![Screenshot of connected Bitcoin addresses in the Neo4j browser.](images/how/neo4j-connected-addresses.png)

In this guide I will cover:

1. How bitcoin works, and what the blockchain is.
2. What blockchain data looks like.
3. How to import the blockchain data in to Neo4j.

This isn't a complete tutorial on how to write your own importer tool. However, if you're interested, you look at my [bitcoin-to-neo4j](https://github.com/in3rsha/bitcoin-to-neo4j) code, although I'm sure you could write something cleaner after reading this guide.


## 1. What is Bitcoin?

Bitcoin is a computer program.

It's a bit like uTorrent; you run the program, it _connects to other computers_ running the same program, and it _shares a file_. However, the cool thing about Bitcoin is that _anyone can add data_ to this shared file, and any data already written to the file _cannot be tampered with_.

![](images/how/bitcoin-network.gif)

As a result, Bitcoin creates a **secure file** that is shared on a **distributed network**.

### What can you do with this?

Well, in Bitcoin, each piece of data that gets added to this file is a **transaction**. Therefore, this decentralised file is being used as a "ledger" for a _digital currency_.

This ledger is called **the blockchain**.

![](images/how/bitcoin-file.gif)

### Where can I find the blockchain?

If you run the [Bitcoin Core](https://bitcoin.org/en/download) program, the blockchain will be stored in a folder on your computer:

* Linux: `~/.bitcoin/blocks`
* Windows: `~/Library/Application Support/Bitcoin/blocks`
* Mac: `C:\Users\YourUserName\Appdata\Roaming\Bitcoin\blocks`

**NOTE:** When you open this directory you should notice that instead of one big file, you will find multiple files with the name `blkXXXXX.dat`. This is the blockchain data, but split across multiple smaller files.




## 2. What does the blockchain look like?

The [blk.dat](https://learnmeabitcoin.com/technical/blkdat) files contain serialized data of **blocks** and **transactions**.

![](images/how/blockchain.png)

### Blocks

Blocks are separated by [magic bytes](https://learnmeabitcoin.com/technical/magic-bytes), which is then followed by the _size_ of the upcoming block.

Each block then begins with a [block header](https://learnmeabitcoin.com/technical/block-header):

![A block is basically a container for a list of transactions. The header is like the meta-data at the top.](images/how/blockchain-block.png)

#### Block Header Example:

```
{
  "version": 00000020,
  "previousblock": "6c77f112319ae21489b66774e8acd379044d4a23ea7498000000000000000000",
  "merkleroot": "821fe1890186779b2cc232d5dbecfb9119fd46f8a9cfd1141649ff1cd9073744",
  "time": 87d8ae59,
  "bits": "e93c0118",
  "nonce": 32ec0399,
}
```

### Transactions

After the block header, there is a byte that tells you the upcoming number of transactions in the block. After that, you get serialized transaction data, one after the other.

A [transaction](https://learnmeabitcoin.com/technical/transaction-data) is just another piece of code again, but they are more structurally interesting.

![](images/how/blockchain-transaction.png)

Each transaction has the same pattern:

1. Select Outputs (we call these _Inputs_).
    * _Unlock_ these inputs so that they can be spent.
2. Create Outputs
    * _Lock_ these outputs to a new address.

So after a series of transactions, you have a transaction structure that looks like something this:

![This is a simplified diagram of what the blockchain looks like. As you can see, it looks like a graph.](images/how/blockchain-transactions.png)


#### Transaction Example:

```
{
  "version": "02000000",
  "inputcount": "01",
  "inputs": [
    {
      "txid": "f2f7ee9dda0ba82031858d30d50d3205eea07246c874a0488532014d3b653f03",
      "vout": "00000000",
      "scriptsigsize": "6a",
      "scriptsig": "47304402204df1839028a05b5b303f5c85a66affb7f6010897d317ac9e88dba113bb5a0fe9022053830b50204af15c85c9af2b446338d049672ecfdeb32d5124e0c3c2256248b7012102c06aec784f797fb400001c60aede8e110b1bbd9f8503f0626ef3a7e0ffbec93b",
      "sequence": "feffffff"
    }
  ],
  "outputcount": "02",
  "outputs": [
    {
      "amount": "00e1f50500000000",
      "scriptpubkeysize": "19",
      "scriptpubkey": "76a9144120275dbeaeb40920fc71cd8e849c563de1610988ac"
    },
    {
      "amount": "9f16641800000000",
      "scriptpubkeysize": "19",
      "scriptpubkey": "76a91493fa3301df8b0a268c7d2c3cc4668ea86fddf81588ac"
    }
  ],
  "locktime": "61610700"
}
```





## 3. How to import the blockchain in to Neo4j.

Well, now we know what the blockchain data represents (and that it looks a lot like a graph), we can go ahead and import it in to Neo4j. We do this by:

1. Reading through the blk.dat files.
2. Decoding each block and transaction we run in to.
3. Converting the decoded block/transaction in to a Cypher query.

Here's a visual guide to how I represent **Blocks**, **Transactions**, and **Addresses** in the database:

### Blocks

![](images/how/import-block.gif)

1. CREATE a `:block` node, and connect it to the previous block it builds upon.
    * SET each field from the **block header** as _properties_ on this node.
3. CREATE a `:coinbase` node coming off each block, as this represents the "new" bitcoins being made available by the block.
    * SET a **value** property on this node, which is equal to the block reward for this block.

### Transactions

![](images/how/import-transaction.gif)

1. CREATE a `:tx` node, and connect it to the `:block` we had just created.
    * SET properties (**version**, **locktime**) on this node.
2. MERGE existing `:output` nodes and relate them `[:in]` to the `:tx`.
    * SET the **unlocking** code as a property on the relationship.
3. CREATE new `:output` nodes that this transaction creates.
    * SET the respective **values** and **locking** codes on these nodes.

#### Addresses

If the **locking** code on an `:output` contains an address...

![](images/how/import-address.gif)

1. CREATE an `:address` node, and connect the output node to it.
    * SET the **address** as a property on this node.
    * _Note: If different outputs are connected to the same address, then they will be connected to the same address node._





## 4. Cypher Queries

Here are some example cypher queries you could use for the basis of inserting blocks and transactions in to Neo4j.

**NOTE:** You will need to decode the **block headers** and **transaction data** to get the _parameters_ for the cypher queries.

### Block

```cypher
MERGE (block:block {hash:$blockhash})
CREATE UNIQUE (block)-[:coinbase]->(:output:coinbase)
SET
   block.size=$size,
   block.prevblock=$prevblock,
   block.merkleroot=$merkleroot,
   block.time=$timestamp,
   block.bits=$bits,
   block.nonce=$nonce,
   block.txcount=$txcount,
   block.version=$version,

MERGE (prevblock:block {hash:$prevblock})
MERGE (block)-[:chain]->(prevblock)
```

#### Parameters (example):
```json
{
    "blockhash": "00000000000003e690288380c9b27443b86e5a5ff0f8ed2473efbfdacb3014f3",
    "version": 536870912,
    "prevblock": "000000000000050bc5c1283dceaff83c44d3853c44e004198c59ce153947cbf4",
    "merkleroot": "64027d8945666017abaf9c1b7dc61c46df63926584bed7efd6ed11a6889b0bac",
    "timestamp": 1500514748,
    "bits": "1a0707c7",
    "nonce": 2919911776,
    "size": 748959,
    "txcount": 1926,
}
```

### Transaction

```cypher
MATCH (block :block {hash:$hash})
MERGE (tx:tx {txid:$txid})
MERGE (tx)-[:inc {i:$i}]->(block)
SET tx += {tx}	  

WITH tx
FOREACH (input in $inputs |
		 MERGE (in :output {index: input.index})
		 MERGE (in)-[:in {vin: input.vin, scriptSig: input.scriptSig, sequence: input.sequence, witness: input.witness}]->(tx)
		 )

FOREACH (output in $outputs |
		 MERGE (out :output {index: output.index})
		 MERGE (tx)-[:out {vout: output.vout}]->(out)
		 SET
		     out.value= output.value,
		     out.scriptPubKey= output.scriptPubKey,
		     out.addresses= output.addresses
		 FOREACH(ignoreMe IN CASE WHEN output.addresses <> '' THEN [1] ELSE [] END |
				 MERGE (address :address {address: output.addresses})
				 MERGE (out)-[:locked]->(address)
				 )
		 )
```

_Note: This query uses the [FOREACH hack](http://www.markhneedham.com/blog/2016/10/30/neo4j-create-dynamic-relationship-type/), which acts as a conditional and will only create the `:address` nodes if the `$addresses` parameter actually contains an address (i.e. is not empty)._

#### Parameters (example):

```json
{
    "txid": "2e2c43d9ef2a07f22e77ed30265cc8c3d669b93b7cab7fe462e84c9f40c7fc5c",
    "hash": "00000000000003e690288380c9b27443b86e5a5ff0f8ed2473efbfdacb3014f3",
    "i": 1,
    "tx": {
        "version": 1,
        "locktime": 0,
        "size": 237,
        "weight": 840,
        "segwit": "0001"
    },
    "inputs": [
        {
            "vin": 0,
            "index": "0000000000000000000000000000000000000000000000000000000000000000:4294967295",
            "scriptSig": "03779c110004bc097059043fa863360c59306259db5b0100000000000a636b706f6f6c212f6d696e65642062792077656564636f646572206d6f6c69206b656b636f696e2f",
            "sequence": 4294967295,
            "witness": "01200000000000000000000000000000000000000000000000000000000000000000"
        }
    ],
    "outputs": [
        {
            "vout": 0,
            "index": "2e2c43d9ef2a07f22e77ed30265cc8c3d669b93b7cab7fe462e84c9f40c7fc5c:0",
            "value": 166396426,
            "scriptPubKey": "76a91427f60a3b92e8a92149b18210457cc6bdc14057be88ac",
            "addresses": "14eJ6e2GC4MnQjgutGbJeyGQF195P8GHXY"
        },
        {
            "vout": 1,
            "index": "2e2c43d9ef2a07f22e77ed30265cc8c3d669b93b7cab7fe462e84c9f40c7fc5c:1",
            "value": 0,
            "scriptPubKey": "6a24aa21a9ed98c67ed590e849bccba142a0f1bf5832bc5c094e197827b02211291e135a0c0e",
            "addresses": ""
        }
    ]
}
```


## 5. Results

If you have inserted the blocks and transactions using the cypher queries above, then these are some examples the kind of results you can get out of the graph database.

### Block

![](images/how/results-block.png)

```
MATCH (block :block)<-[:inc]-(tx :tx)
WHERE block.hash='$blockhash'
RETURN block, tx
```

### Transaction

![](images/how/results-transaction.png)

```
MATCH (inputs)-[:in]->(tx:tx)-[:out]->(outputs)
WHERE tx.txid='$txid'
OPTIONAL MATCH (inputs)-[:locked]->(inputsaddresses)
OPTIONAL MATCH (outputs)-[:locked]->(outputsaddresses)
OPTIONAL MATCH (tx)-[:inc]->(block)
RETURN inputs, tx, outputs, block, inputsaddresses, outputsaddresses
```

### Address

![](images/how/results-address.png)

```
MATCH (address :address {address:'1PNXRAA3dYTzVRLwWG1j3ip9JKtmzvBjdY'})<-[:locked]-(output :output)
WHERE address.address='$address'
RETURN address, output
```

### Paths

Finding paths between transactions and addresses is probably the most interesting thing you can do with a graph database of the bitcoin blockchain, so here are some examples of cypher queries for that:

#### Between Outputs

![](images/how/results-path-output.png)

```
MATCH (start :output {index:'$txid:vout'}), (end :output {index:'$txid:out'})
MATCH path=shortestPath( (start)-[:in|:out*]-(end) )
RETURN path
```

#### Between Addresses

![](images/how/results-path-address.png)


```
MATCH (start :address {address:'$address1'}), (end :address {address:'$address2'})
MATCH path=shortestPath( (start)-[:in|:out|:locked*]-(end) )
RETURN path
```



## 6. Conclusion

This has been a simple guide on how you can take the blocks and transactions from blk.dat files (the blockchain) and import them in to a Neo4j database.

I think it's worth the effort if you're looking to do serious analysis on the blockchain. A graph database is a natural fit for bitcoin data, whereas using an SQL database for bitcoin transactions feels like trying to shove a square peg in to a round hole.

I've tried to keep this guide compact, so I haven't covered things like:

1. **Reading through the blockchain.** Reading the [blk.dat](https://learnmeabitcoin.com/technical/blkdat) files is easy enough. However, the annoying thing about these files is that the **blocks are [not written to these files in sequential order](https://bitcoin.stackexchange.com/questions/41535/how-much-out-of-order-are-the-blocks-stored-in-the-blk-dat-files)**, which makes _setting the height on a block_ or _calculating the fee for a transaction_ a bit trickier (but you can code around it).
2. **Decoding blocks and transactions.** If you want to use the **cypher queries** above, you will need to get the _parameters_ you require by decoding the block headers and raw transaction data as you go. You could write your own decoders, or you could try using an existing bitcoin library.
3. **Segregated Witness**. I've only given a cypher query for an "original" style transaction, which was the only transaction structure used up until block [481,824](https://learnmeabitcoin.com/explorer/blockchain/481824). However, the structure of a [segwit transaction](https://learnmeabitcoin.com/explorer/transaction/c586389e5e4b3acb9d6c8be1c19ae8ab2795397633176f5a6442a261bbdefc3a) is only slightly different (but it might need its own cypher query).

Nonetheless, hopefully this guide has been somewhat helpful.

But as always, if you understand how the data works, converting it to a different format is just a matter of sitting down and writing the tool.

Good luck.


================================================
FILE: functions/README.md
================================================
# Library Functions

This is a bunch of simple library functions for Bitcoin. I use them for decoding the raw transaction data found in Bitcoin's `blk.dat` files (binary files containing the blockchain).

I wrote this library for speed. For a more comprehensive library, check out [bitcoin-php](https://github.com/Bit-Wasp/bitcoin-php)


================================================
FILE: functions/basic.php
================================================
<?php
/*
 * author:  Greg Walker
 * website: http://learnmeabitcoin.com
 * license: GPLv3
*/

function swapEndian($data) {
    return implode('', array_reverse(str_split($data, 2)));
}

function fieldSize($field, $bytes = 4) {
    $length = $bytes * 2;
    $result = str_pad($field, $length, '0', STR_PAD_LEFT);
    return $result;
}

function ascii2hex($ascii) {
	$hex = '';
	for ($i = 0; $i < strlen($ascii); $i++) {
		$byte = strtoupper(dechex(ord($ascii[$i])));
		$byte = str_repeat('0', 2 - strlen($byte)).$byte;
		$hex .= $byte;
	}
	return $hex;
}

function hex2ascii($hex) {
    $str = '';
    for($i=0; $i<strlen($hex); $i+=2) {
		$byte = substr($hex, $i, 2);
		$dec = hexdec($byte);
		$str .= chr($dec);
	}
    return filter_var($str, FILTER_SANITIZE_SPECIAL_CHARS); // Prevent an XSS attack from a hex encoded ascii string
}

function varInt($data) { // Calculates the full variable integer and returns it
    $varint = strtolower(substr($data, 0, 2));

    if     ($varint == 'fd') { $value = substr($data, 2, 4);  $full = $varint.$value; $len = 6;}
    elseif ($varint == 'fe') { $value = substr($data, 2, 8);  $full = $varint.$value; $len = 10;}
    elseif ($varint == 'ff') { $value = substr($data, 2, 16); $full = $varint.$value; $len = 18;}
    else                     { $value = $varint; $full = $varint; $len = 2; }

    $value = hexdec(swapEndian($value)); // convert value to a usable decimal number

    return array($full, $value, $len);
}

function toVarInt($i) {
	if ($i < 253) {
		return fieldSize(dechex($i), 1);
	}
	if (253 <= $i && $i < 65535) {
		return 'fd'.swapEndian(fieldSize(dechex($i), 2));
	}
	if (65535 <= $i && $i < 4294967295) {
		return 'fe'.swapEndian(fieldSize(dechex($i), 4));
	}
	if (4294967295 <= $i) {
		return 'ff'.swapEndian(fieldSize(dechex($i), 8));
	}
}

function bchexdec($hex) {
    if(strlen($hex) == 1) {
        return hexdec($hex);
    } else {
        $remain = substr($hex, 0, -1);
        $last = substr($hex, -1);
        return bcadd(bcmul(16, bchexdec($remain)), hexdec($last));
    }
}

function bcdechex($dec) {
    $last = bcmod($dec, 16);
    $remain = bcdiv(bcsub($dec, $last), 16);

    if($remain == 0) {
        return dechex($last);
    } else {
        return bcdechex($remain).dechex($last);
    }
}



================================================
FILE: functions/block.php
================================================
<?php
/*
 * author:  Greg Walker
 * website: http://learnmeabitcoin.com
 * license: GPLv3
*/

require_once('basic.php');

const TARGET_MAX = '00000000FFFF0000000000000000000000000000000000000000000000000000';

function calculateBlockReward($blockcount) {
    // set the block rewards array
    $reward = 5000000000;
    $i = 1;
    while ($reward >= 1) {
        $blockrewards[$i] = $reward;
        $reward = floor($reward/2);
        $i++;
    }

    // work out the block reward level
    $block = 0;
    $level = 0;
    while ($blockcount >= $block) {
        $block += 210000;
        $level += 1;
    }
	
	// return the value in satoshis
	return $blockrewards[$level];
}

function bitstotarget($bits) {
 
	// remove the 0x prefix (if it's there)
	if (substr($bits, 0, 2) == '0x') {
		$bits = ltrim($bits, '0x');
	}
 
	// get the two parts
	$exponent = substr($bits, 0, 2);
	$coefficient = substr($bits, 2, 6);
 
	// calculate the size of the target in bytes
	$bytes = hexdec($exponent);
 
	// form the size of the target with the coefficient at the start
	$target = str_pad($coefficient, (($bytes) * 2), '0' );
 
	// return a 32-byte target (without the 0x at the start)
	return str_pad($target, 32*2, '0', STR_PAD_LEFT);
 
}

function bitstodifficulty($bits) {

	$targetmax = bchexdec(TARGET_MAX);
	$target    = bchexdec(bitstotarget($bits));
	$difficulty = $targetmax/$target;

	return $difficulty;
}


function difficultytotarget($difficulty) {
	$targetmax = bchexdec(TARGET_MAX); //26959535291011309493156476344723991336010898738574164086137773096960';
	$target = bcdiv($targetmax, $difficulty);
	
	return str_pad(bcdechex($target), 64, '0', STR_PAD_LEFT);
}

function targettobits($target) {
	$bytes = str_split($target, 2);

	// 1. coefficient
	$i = 1;
	$coefficient = '';
	foreach ($bytes as $byte) {
		if ($byte != '00' && $i <= 3) {
			$coefficient .= $byte;
			$i++;
		}
	}

	// 2. exponent
	$position = strpos($target, $coefficient);
	$exponent = dechex((64 - $position) / 2);

	// 3. bits
	$bits = $exponent.$coefficient;
	return $bits;
}

function merklerootbinary($txids) {
 
	// Stop recursion if there is only one hash value left, because that's the merkle root.
	if (count($txids) == 1) {
		$merkleroot = $txids[0];
		return $merkleroot;
	}
 
	else {
 
		// Create the new array of hashes		
		while (count($txids) > 0) {
 
			if (count($txids) >= 2) {
				// Get first two
				$pair_first = $txids[0];
				$pair_second = $txids[1];
 
				// Hash them (double SHA256)
				$pair = $pair_first.$pair_second;
				$pairhashes[] = hash('sha256', hash('sha256', $pair, true), true);
 
				// Remove those two from the array
				unset($txids[0]);
				unset($txids[1]);
 
				// Re-set the indexes (the above just nullifies the values) and make a new array without the original first two slots.
				$txids = array_values($txids);
			}
 
			if (count($txids) == 1) {
				// Get the first one twice
				$pair_first = $txids[0];
				$pair_second = $txids[0];
 
				// Hash it with itself (double SHA256)
				$pair = $pair_first.$pair_second;
				$pairhashes[] = hash('sha256', hash('sha256', $pair, true), true);
 
				// Remove it from the array
				unset($txids[0]);
 
				// Re-set the indexes (the above just nullifies the values) and make a new array without the original first two slots.
				$txids = array_values($txids);
			}
 
		}
 
		// Recursion bit. Re-apply this function to the new array of hashes we've just created.
		return merklerootbinary($pairhashes);
 
	}
 
}
 
function merkleroot($txids) {
 
	// Convert txids in to big endian (BE), because that's the format they need to be in to get the merkle root.
	foreach ($txids as $txid) {
		$txidsBE[] = swapEndian($txid);
	}
 
	// Now convert each of these txids in to binary, because the hash function wants the binary value, not the hex.
	foreach ($txidsBE as $txidBE) {
		$txidsBEbinary[] = hex2bin($txidBE);
	}
 
	// Work out the merkle root (in binary) using that lovely recursive function above.
	$merkleroot = merklerootbinary($txidsBEbinary);
 
	// Convert the merkle root in to hexadecimal and little-endian, because that's how it's stored in the block header.
	$merkleroot = swapEndian(bin2hex($merkleroot));
 
	// Return it :)
	return $merkleroot;
 
}


================================================
FILE: functions/hash.php
================================================
<?php
/*
 * author:  Greg Walker
 * website: http://learnmeabitcoin.com
 * license: GPLv3
*/

function hash256($hex) {
	$binary = hex2bin($hex);
	$hash1 = hash("sha256", $binary, true); // "true" returns binary value (or will return hex by default)
	$hash2 = hash("sha256", $hash1);
	return $hash2;
}
  
function hash160($hex) {
	$binary = hex2bin($hex);
	$hash1 = hash("sha256", $binary, true);
	$hash2 = hash("ripemd160", $hash1);
	return $hash2;
}


================================================
FILE: functions/keys.php
================================================
<?php
/*
 * author:  Greg Walker
 * website: http://learnmeabitcoin.com
 * license: GPLv3
*/

include_once 'hash.php'; // hash256 and hash160

// Taken from bitcoin-lib-php
function base58_encode($hex)
  {
  		$base58chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

      if (strlen($hex) == 0) {
          return '';
      }

      // Convert the hex string to a base10 integer
      $num = gmp_strval(gmp_init($hex, 16), 58);

      // Check that number isn't just 0 - which would be all padding.
      if ($num != '0') {
          $num = strtr(
              $num,
              '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv',
              $base58chars
          );
      } else {
          $num = '';
      }

      // Pad the leading 1's
      $pad = '';
      $n = 0;
      while (substr($hex, $n, 2) == '00') {
          $pad .= '1';
          $n += 2;
      }

      return $pad . $num;
  }

function base58_encode_checksum($hex)
  {
      $checksum = hash256($hex);
      $checksum = substr($checksum, 0, 8);
      $hash = $hex . $checksum;
      return base58_encode($hash);
  }

function hash160_to_address($hash160, $prefix = '00')
	{
	  // 00 = 1address
	  // 05 = 3address
      $hash160 = $prefix.$hash160;
      return base58_encode_checksum($hash160);
	}

function pubkey_to_address($pubkey)
	{
		return hash160_to_address(hash160($pubkey));
	}

// Bech32
function bech32_polymod($values) {
    // Internal function that computes the Bech32 checksum.
    $generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];

    $chk = 1;
    foreach ($values as $value) {
        $top = $chk >> 25;
        $chk = ($chk & 0x1ffffff) << 5 ^ $value;
        for ($i=0; $i<5; $i++) {
            if (($top >> $i) & 1 == 1) {
                $chk ^= $generator[$i];
            }
        }
    }

    return $chk;
}

function bech32_hrp_expand($hrp) {
    // Expand the HRP in to values for checksum computation.
    $expand1 = [];
    $expand2 = [];
    foreach (str_split($hrp) as $c) {
        $expand1[] = ord($c) >> 5; // ord char, right shifted
        $expand2[] = ord($c) & 31;
    }

    return array_merge($expand1, [0], $expand2);
}

function bech32_create_checksum($hrp, $data) {
    // Compute the checksum values given HRP and data.
    $values = array_merge(bech32_hrp_expand($hrp), $data);
    $polymod = bech32_polymod(array_merge($values, [0, 0, 0, 0, 0, 0])) ^ 1;

    $checksum = [];
    for ($i=0; $i<6; $i++) {
        $checksum[] = ($polymod >> 5 * (5 - $i)) & 31;
    }

    return $checksum;
}

function convertbits($data, $from, $to, $pad=true) {
    // General power-of-2 base conversion.
    // This is used to prepare a scriptpubkey ready for bech32 encoding.
    $acc    = 0;
    $bits   = 0;
    $ret    = [];
    $maxv   = (1 << $to) - 1;               // 0b100000 (31)
    $maxacc = (1 << ($from + $to - 1)) - 1; // 0b111111111111 (4095)

    foreach ($data as $value) {
        if ($value < 0 || ($value >> $from) != 0) {
            throw new Bech32Exception("Invalid data range for converting bits.");
        }

        $acc = (($acc << $from) | $value) & $maxacc;
        $bits += $from;
        while ($bits >= $to) {
            $bits -= $to;
            $ret[] = ($acc >> $bits) & $maxv;
        }
    }

    if ($pad) {
        if ($bits) {
            $ret[] = ($acc << ($to - $bits)) & $maxv;
        }
        elseif ($bits >= $from || (($acc << ($to - $bits)) & $maxv)) {
            throw new Bech32Exception("Invalid data.");

        }
    }

    return $ret;
}

function bech32_encode($hrp, $data) {
    // Compute a Bech32 string given HRP and data values.

    // Settings
    $separator = '1'; // always 1
    $charset = ['q', 'p', 'z', 'r', 'y', '9', 'x', '8', 'g', 'f', '2', 't', 'v', 'd', 'w', '0', 's', '3', 'j', 'n', '5', '4', 'k', 'h', 'c', 'e', '6', 'm', 'u', 'a', '7', 'l'];

    // Create the checksum from the data
    $checksum = bech32_create_checksum($hrp, $data);

    // Convert data + checksum to Bech32
    $combined = array_merge($data, $checksum);

    $base32 = [];
    foreach ($combined as $d) {
        $base32[] = $charset[$d];
    }

    // Return Bech32 string
    return $hrp . $separator . implode('', $base32);
    // human readable | separator | bech32 data (with checksum)

}

function bech32_address($scriptpubkey) {
    // Convert scriptpubkey to a Bech32 address.

    // Convert hex scriptpubkey to 8-bit integer values
    $values = unpack("C*", pack("H*", $scriptpubkey));

    // Get the version and witness program bytes
    // |00|14|751e76e8199196d454941c45d1b3a323f1433bd6
    $version = array_slice($values, 0, 1);
    $push = array_slice($values, 1, 1); // not needed
    $program = array_slice($values, 2); // must be in 5-bit groups...

    // Create address
    $programconv = convertbits($program, 8, 5); // 5-bit groups
    $data = array_merge($version, $programconv);
    $bech32 = bech32_encode("bc", $data);

    return $bech32;
    // |hrp|sep|data                             [chk ]|
    //  bc  1   qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4
}


================================================
FILE: functions/readtx.php
================================================
<?php
/*
 * author:  Greg Walker
 * website: http://learnmeabitcoin.com
 * license: GPLv3
*/

include_once "functions/basic.php";

function readtx($transactions, $p=0) {

	// Start Storing
	$txbuffer = ''; // clear the tx buffer, ready to start storing a tx data
	
	// version (4 bytes)
	$txbuffer .= substr($transactions, $p, 8); $p+=8;

	// if segwit [00][01]
	if (hexdec(substr($transactions, $p, 2)) == 0 && hexdec(substr($transactions, $p+2, 2)) > 0) {
		$segwit = true;
		$txbuffer .= substr($transactions, $p, 4); $p+=4; // take the [marker][flag] and move on
	}
	else {
		$segwit = false;
	}

	// inputs
	list($full, $value, $len) = varInt(substr($transactions, $p));
	$txbuffer .= $full; $p+=$len; // inputcount (varint)
	$inputcount = $value;
	
	for ($i=1; $i<=$inputcount; $i++) {
		$txbuffer .= substr($transactions, $p, 64); $p+=64; // txid (32 bytes)
		$txbuffer .= substr($transactions, $p, 8); $p+=8; // vout (4 bytes)
		list($full, $value, $len) = varInt(substr($transactions, $p)); // (varint)
		$txbuffer .= $full; $p+=$len; // scriptSig size
		$size = $value*2; // number of chars
		$txbuffer .= substr($transactions, $p, $size); $p += $size; // scriptSig
		$txbuffer .= substr($transactions, $p, 8); $p+=8; // sequence
	}

	// outputs
	list($full, $value, $len) = varInt(substr($transactions, $p));
	$txbuffer .= $full; $p+=$len; // outputcount (varint)
	$outputcount = $value;

	for ($i=1; $i<=$outputcount; $i++) {
		$txbuffer .= substr($transactions, $p, 16); $p+=16; // value (8 bytes)
		list($full, $value, $len) = varInt(substr($transactions, $p)); // (varint)
		$txbuffer .= $full; $p+=$len; // scriptPubKeysize
		$size = $value*2; //  number of chars
		$txbuffer .= substr($transactions, $p, $size); $p += $size; // scriptPubKey
	}

	// get witnesses (if segwit)
	if ($segwit) {

		// number of witnesses (same as input count)
		for ($i=1; $i<=$inputcount; $i++) {
			
			// number of witness elements
			list($full, $value, $len) = varInt(substr($transactions, $p)); 
			$txbuffer .= $full; $p+=$len;
			$witnesscount = $value;
		
			for ($j=1; $j<=$witnesscount; $j++) {
				// size of witness
				list($full, $value, $len) = varInt(substr($transactions, $p));
				$txbuffer .= $full; $p+=$len;

				// witness
				$size = $value*2;
				$txbuffer .= substr($transactions, $p, $size); $p+=$size;
			}
		}
	}

	// locktime (4 bytes)
	$txbuffer .= substr($transactions, $p, 8); $p+=8;

	return array($txbuffer, $p);

}


================================================
FILE: functions/script.php
================================================
<?php
/*
 * author:  Greg Walker
 * website: http://learnmeabitcoin.com
 * license: GPLv3
*/

include_once 'keys.php';

function decodeScript($script) {

if($script) {

	// store the original
	$hex = $script;

	$opcodes = [

		// Constants (number of bytes to push on to stack)
		// ---------
		'00' => 'OP_FALSE',
		// 01-4b = number of bytes to be pushed on to the stack
		'4c' => 'OP_PUSHDATA1', // next byte = number of bytes to push
		'4d' => 'OP_PUSHDATA2', // next 2 bytes = number of bytes to push
		'4e' => 'OP_PUSHDATA4', // next 4 bytes = number of bytes to push
		'4f' => 'OP_1NEGATE',   // number -1 pushed on to stack
		'51' => 'OP_1',         // number 1 pushed on to stack
		'52' => 'OP_2',
		'53' => 'OP_3',
		'54' => 'OP_4',
		'55' => 'OP_5',
		'56' => 'OP_6',
		'57' => 'OP_7',
		'58' => 'OP_8',
		'59' => 'OP_9',
		'6a' => 'OP_10',
		'6b' => 'OP_11',
		'6c' => 'OP_12',
		'6d' => 'OP_13',
		'6e' => 'OP_14',
		'6f' => 'OP_15',
		'60' => 'OP_16',
		// 52-60 = The number in the word name (OP_2-OP_16) is pushed onto the stack.

		// Flow Control
		// ------------
		'61' => 'OP_NOP', // does nothing
		'63' => 'OP_IF',
		'64' => 'OP_NOTIF',
		'67' => 'OP_ELSE',
		'68' => 'OP_ENDIF',
		'69' => 'OP_VERIFY',
		'6a' => 'OP_RETURN',

		// Stack
		// -----
		'6b' => 'OP_TOALTSTACK',
		'6c' => 'OP_FROMALTSTACK',
		'73' => 'OP_IFDUP',
		'74' => 'OP_DEPTH',
		'75' => 'OP_DROP', // Removes the top stack item.
		'76' => 'OP_DUP',
		'77' => 'OP_NIP',
		'78' => 'OP_OVER',
		'79' => 'OP_PICK',
		'7a' => 'OP_ROLL',
		'7b' => 'OP_ROT',
		'7c' => 'OP_SWAP',
		'7d' => 'OP_TUCK',
		'6d' => 'OP_2DROP',
		'6e' => 'OP_2DUP',
		'6f' => 'OP_3DUP',
		'70' => 'OP_2OVER',
		'71' => 'OP_2ROT',
		'72' => 'OP_2SWAP',

		// Splice
		// ------
		'7e' => 'OP_CAT',
		'7f' => 'OP_SUBSTR',
		'80' => 'OP_LEFT',
		'81' => 'OP_RIGHT',
		'82' => 'OP_SIZE',

		// Bitwise Logit
		// -------------
		'83' => 'OP_INVERT',
		'84' => 'OP_AND',
		'85' => 'OP_OR',
		'86' => 'OP_XOR',
		'87' => 'OP_EQUAL', // Returns 1 if the inputs are exactly equal, 0 otherwise.
		'88' => 'OP_EQUALVERIFY',

		// Arithmetic
		// ----------
		'8b' => 'OP_1ADD',
		'8c' => 'OP_1SUB',
		'8d' => 'OP_2MUL',
		'8e' => 'OP_2DIV',
		'8f' => 'OP_NEGATE',
		'90' => 'OP_ABS', // The input is made positive.
		'91' => 'OP_NOT',
		'92' => 'OP_0NOTEQUAL',
		'93' => 'OP_ADD', // a is added to b
		'94' => 'OP_SUB',
		'95' => 'OP_MUL',
		'96' => 'OP_DIV',
		'97' => 'OP_MOD',
		'98' => 'OP_LSHIFT',
		'99' => 'OP_RSHIFT',
		'9a' => 'OP_BOOLAND',
		'9b' => 'OP_BOOLOR',
		'9c' => 'OP_NUMEQUAL',
		'9d' => 'OP_NUMEQUALVERIFY',
		'9e' => 'OP_NUMNOTEQUAL',
		'9f' => 'OP_LESSTHAN',
		'a0' => 'OP_GREATERTHAN',
		'a1' => 'OP_LESSTHANOREQUAL',
		'a2' => 'OP_GREATERTHANOREQUAL',
		'a3' => 'OP_MIN',
		'a4' => 'OP_MAX',
		'a5' => 'OP_WITHIN',

		// Crypto
		// ------
		'a6' => 'OP_RIPEMD160',
		'a7' => 'OP_SHA1',
		'a8' => 'OP_SHA256',
		'a9' => 'OP_HASH160',
		'aa' => 'OP_HASH256',
		'ab' => 'OP_CODESEPARATOR',
		'ac' => 'OP_CHECKSIG',
		'ad' => 'OP_CHECKSIGVERIFY',
		'ae' => 'OP_CHECKMULTISIG',
		'af' => 'OP_CHECKMULTISIGVERIFY',

		// Locktime
		'b1' => 'OP_CHECKLOCKTIMEVERIFY',
		'b2' => 'OP_CHECKSEQUENCEVERIFY',

		// Pseudo-Words
		'fd' => 'OP_PUBKEYHASH',
		'fe' => 'OP_PUBKEY',
		'ff' => 'OP_INVALIDOPCODE',

		// Reserved Words
		'50' => 'OP_RESERVED',
		'62' => 'OP_VER',
		'65' => 'OP_VERIF',
		'66' => 'OP_VERNOTIF',
		'89' => 'OP_RESERVED1',
		'8a' => 'OP_RESERVED2',
		'b0' => 'OP_NOP1', // The word is ignored. Does not mark transaction as invalid.
		'b2' => 'OP_NOP3',
		'b3' => 'OP_NOP4',
		'b4' => 'OP_NOP5',
		'b5' => 'OP_NOP6',
		'b6' => 'OP_NOP7',
		'b7' => 'OP_NOP8',
		'b8' => 'OP_NOP9',
		'b9' => 'OP_NOP10',

	];

	// run through the string, getting the opcodes or specified number of bytes
	while (strlen($script) > 0) {

		// run through every byte (2 characters)
		$byte = substr($script, 0, 2);

		// store this byte in opcodes array
		$lockpieces[] = $byte;

		// now remove that byte from the string
		$script = substr($script, strpos($script, $byte) + strlen($byte));

		// ----------
		// Push Bytes (0x01 to 0x4e)
		// ----------
		if (ctype_xdigit($byte) && hexdec($byte) >= hexdec('00') && hexdec($byte) < hexdec('4e')) {

			// 00
			if ($byte == '00') { // Push empty bytes on to stack
				$pushbytes = '0';
			}
			// <= 4b
			if (hexdec($byte) >= 1 and hexdec($byte) <= hexdec('4b')) { // $byte indicates the number of bytes
				$pushbytes = substr($script, 0, hexdec($byte)*2);
			}

			// 4c, 4d, 4e
			$pushers = array(
				'4c' => 1,
				'4d' => 2,
				'4e' => 4,
			);
			if (array_key_exists($byte, $pushers)) {
				// get the number of bytes to push
				$bytestopush = substr($script, 0, $pushers[$byte]*2);

				// if no errors
				if ($bytestopush) {
					$script = substr($script, strpos($script, $bytestopush) + strlen($bytestopush)); // remove
					$pushbytes = substr($script, 0, hexdec($bytestopush)*2);
				}
				else {
					$script = NULL;
					$pushbytes = '[error]';
				}
			}

			// pop that opcode off the end of the array and replace it with the specified number of bytes
			array_pop($lockpieces);
			if ($pushbytes) {
				$lockpieces[] = $pushbytes;
			}

			// now remove those bytes from the string too
			if ($pushbytes) {
				$script = substr($script, strpos($script, $pushbytes) + strlen($pushbytes));
			}

		}

	}

	// convert the hex values to their corresponding opcodes
	$i=0;
	$lockops = [];
	foreach ($lockpieces as $piece) {

		// GET OPCODES

		if (strlen($piece) == 2) {
			if (array_key_exists($piece, $opcodes)) {
				$lockops[] = $opcodes[$piece];
			}
			else {
				$lockops[] = 'OP_???';
			}
		}
		else {
			$lockops[] = $piece;
		}

		$i++;
	}


	// -------------
	// GET ADDRESSES
	// -------------
	$addresses = [];

	if (count($lockops) > 0) {

		// 1. pubkey (P2PK): <pubkey> OP_CHECKSIG
		if (count($lockops) == 2) {
			if ($lockops[1] == 'OP_CHECKSIG') {
				if (ctype_xdigit($lockops[0]) && (strlen($lockops[0]) == 66 or strlen($lockops[0]) == 130)) {
					$addresses[] = pubkey_to_address($lockops[0]);
				}
			}
		}


		// 2. pubkeyhash (P2PKH): OP_DUP OP_HASH160 <hash160> OP_EQUALVERIFY OP_CHECKSIG
		if (count($lockops) == 5) {
			if ($lockops[0] == 'OP_DUP' && $lockops[1] == 'OP_HASH160' && $lockops[3] == 'OP_EQUALVERIFY' && $lockops[4] == 'OP_CHECKSIG') {

				// check the "hash160" is hex and 40 chars
				if (ctype_xdigit($lockops[2]) && strlen($lockops[2]) == 40) {
					$addresses[] = hash160_to_address($lockops[2], '00');
				}
			}
		}

		// 3. scripthash (P2SH): OP_HASH160 <hash160> OP_EQUAL
		if (count($lockops) == 3) {
			if ($lockops[0] == 'OP_HASH160' && $lockops[2] == 'OP_EQUAL') {

				// check the "hash160" is hex and 40 chars
				if (ctype_xdigit($lockops[1]) && strlen($lockops[1]) == 40) {
					$addresses[] = hash160_to_address($lockops[1], '05');
				}
			}
		}

		// 4. <n pubkeys> OP_n OP_CHECKMULTISIG
		if (array_slice($lockops, -1, 1)[0] == 'OP_CHECKMULTISIG') { // last opcode is op_checkmultisig
			if (substr(array_slice($lockops, -2, 1)[0], 0, 3) == 'OP_') { // second to last begins with OP_
				$op_n = preg_replace("/[^0-9]/", '', array_slice($lockops, -2, 1)[0]);
				$pubkeys = array_slice($lockops, -2-$op_n, $op_n); // get the expected number of pubkeys
				foreach ($pubkeys as $pubkey) {

					// check that it is a pubkey
					// example error:
					// OP_2 OP_FALSE 021d69e2b68c3960903b702af7829fadcd80bd89b158150c85c4a75b2c8cb9c394 OP_2 OP_CHECKMULTISIG

					if (ctype_xdigit($pubkey) && (strlen($pubkey) == 66 or strlen($pubkey) == 130)) {
						$addresses[] = pubkey_to_address($pubkey);
					}
				}
			}
		}

	} // if count($lockops) > 0

	// 5. P2WPKH and P2WSH - 0014{20-bytes} or 0020{32-bytes}
	// Use '00' version to identify a native segwit transaction
	if (substr($hex, 0, 2) == '00') { // && (substr($hex, 2, 2) == '14' || substr($hex, 2, 2) == '20')) {
		// |version|push|witnessprogram|
		//  00      14   751e76e8199196d454941c45d1b3a323f1433bd6
		//  00      20   88e2e40cd889901733cb2f922be01199d334f3232a34cffee6143482d8eb6c19

		// [ ] Can remove. Just doing an extra check to make sure we haven't already got an address.
		if (count($addresses) > 0) {
			throw new Exception("Already got an address for what looks like a witness scriptpubkey: ".print_r($addresses));
		}

		// Determine type
		if (substr($hex, 2, 2) == '14') { // 20-byte witess program (hash160 of a public key)
			$type = 'P2WPKH';
			$addresses[] = bech32_address($hex);
		}
		elseif (substr($hex, 2, 2) == '20') { // 32-byte witess program (hash256 of a script)
			$type = 'P2WSH';
			$addresses[] = bech32_address($hex);
		}
		else {
			throw new Exception("Unknown witness program size: $hex");
		}
	}

	// -------
	// RESULT!
	// -------
	$result = array(
		'hex' => $hex,
		'opcodes' => implode(' ', $lockops),
		'addresses' => implode(', ', $addresses),
	);
}

// if script empty
else {
	$result = array(
		'hex' => '',
		'opcodes' => '',
		'addresses' => '',
	);

}

return $result;

}

// test
// print_r(decodeScript('0201'));

?>


================================================
FILE: functions/tx.php
================================================
<?php
/*
 * author:  Greg Walker
 * website: http://learnmeabitcoin.com
 * license: GPLv3
*/

include_once 'basic.php';
include_once 'script.php';

function decoderawtransaction($data) {

	// save the original
	$raw = $data;

	// SegWit
	if (hexdec(substr($data, 8, 2)) == 0 && hexdec(substr($data, 10, 2)) > 0) { // numinputs = 0, numoutputs > 0
		$segwit = true;
		$array['segwit'] = substr($data, 8, 4);
	}
	else {
		$segwit = false;
		$array['segwit'] = false;
	}

	// version
	$version = substr($data, 0, 8);
	$array['version'] = hexdec(swapEndian($version));
	$data = substr($data, 8);


	// remove segwit flag
	if ($segwit) {
		$data = substr($data, 4);
	}


	// inputcount
	list($invarint_full, $invarint_value, $invarint_len) = varInt($data);
	// $array['inputcount'] = $invarint_full;
	$data = substr($data, $invarint_len);

	// txins
	for ($i=0; $i<$invarint_value; $i++) {
		// txids
		$array['vin'][$i]['txid'] = swapEndian(substr($data, 0, 64));
		$data = substr($data, 64);

		// vouts
		$array['vin'][$i]['vout'] = hexdec(swapEndian(substr($data, 0, 8)));
		$data = substr($data, 8);

		// signaturesizes
		list($sigvarint_full, $sigvarint_value, $sigvarint_len) = varInt($data);
		//$array['signaturesizes'][$i] = $sigvarint_full;
		$data = substr($data, $sigvarint_len);

		// signatures
		$signaturelength = 2 * $sigvarint_value;
		$array['vin'][$i]['scriptSig']['hex'] = substr($data, 0, $signaturelength);
		$data = substr($data, $signaturelength);

		// sequence
		$sequence = substr($data, 0, 8);
		$array['vin'][$i]['sequence'] = hexdec(swapEndian($sequence));
		$data = substr($data, 8);
	}

	// outputcount
	list($outvarint_full, $outvarint_value, $outvarint_len) = varInt($data);
	//$array['outputcount'] = $outvarint_full;
	$data = substr($data, $outvarint_len);

	// txouts
	for ($i=0; $i<$outvarint_value; $i++) {
		// value
		$array['vout'][$i]['vout'] = $i;

		// value
		$array['vout'][$i]['value'] = hexdec(swapEndian(substr($data, 0, 16)));
		$data = substr($data, 16);

		// locksize
		list($lockvarint_full, $lockvarint_value, $lockvarint_len) = varInt($data);
		//$array['lockingscriptsizes'][$i] = $lockvarint_full;
		$data = substr($data, $lockvarint_len);

		// lockingscript
		$lockingscriptlength = 2 * $lockvarint_value;
		$lockingscript = substr($data, 0, $lockingscriptlength);
		$array['vout'][$i]['scriptPubKey'] = decodeScript($lockingscript);
		$data = substr($data, $lockingscriptlength);

	}

	if ($segwit) {

		$witnessdata = ''; // start storing all witness data, so it can be subtracted from full data to get the original txid

		// for each input
		for ($i=0; $i<$invarint_value; $i++) {

			$witnesshex = ''; // store individual input's witness hex data
			// 02
			// 48 3045...901
			// 21 0382...0ac

			// number of witness elements
			list($witvarint_full, $witvarint_value, $witvarint_len) = varInt($data);
			$witnesshex .= $witvarint_full;
			$data = substr($data, $witvarint_len);

			for ($j=0; $j<$witvarint_value; $j++) {

				// witnessesizes
				list($witsizevarint_full, $witsizevarint_value, $witsizevarint_len) = varInt($data);
				$witnesshex .= $witsizevarint_full;
				$data = substr($data, $witsizevarint_len);

				// witnesses
				$witnesslength = 2 * $witsizevarint_value;
				$array['vin'][$i]['witness'][$j] = substr($data, 0, $witnesslength);
				$witnesshex .= substr($data, 0, $witnesslength);
				$data = substr($data, $witnesslength);

			}

			$array['vin'][$i]['witness']['hex'] = $witnesshex;
			$witnessdata .= $witnesshex;

		}

	}


	// locktime
	$locktime = substr($data, 0, 8);
	$array['locktime'] = hexdec(swapEndian($locktime));
	$data = substr($data, 8);


	// TXID
	if ($segwit) {
		// wtxid
		$wtxid = hash("sha256", pack('H*', $raw));
		$wtxid = hash("sha256", pack('H*', $wtxid));
		$array['wtxid'] = swapEndian($wtxid);

		// original txid (remove flag and witness data)
		$withoutflag = substr($raw, 0, 8).substr($raw, 12); // remove flag
		$txid_orig = str_replace($witnessdata, '', $withoutflag); // remove witness data

		$txid = hash("sha256", pack('H*', $txid_orig));
		$txid = hash("sha256", pack('H*', $txid));
		$array['txid'] = swapEndian($txid);
	}
	else {
		$txid = hash("sha256", pack('H*', $raw));
		$txid = hash("sha256", pack('H*', $txid));
		$array['txid'] = swapEndian($txid);
	}

	// size
	$array['size'] = strlen($raw)/2;

	// return the PHP array

	return $array;

} // end function

?>


================================================
FILE: main.php
================================================
<?php
/*
 * title:   bitcoin-to-neo4j
 * desc:    Import Bitcoin's blk.dat files (the blockchain) in to a Neo4j graph database.
 * author:  Greg Walker
 * website: http://learnmeabitcoin.com
 * license: GPLv3
*/

// Config
require_once 'config.php';

// Redis
$redis = new Redis();
$redis->connect(REDIS_IP, REDIS_PORT);

// Composer
require_once 'vendor/autoload.php';

// Neo4j
use Laudis\Neo4j\ClientBuilder; // (neo4j-php/neo4j-php-client)

$neo = ClientBuilder::create()
    ->withDriver('bolt', 'bolt://'.NEO4J_USER.':'.NEO4J_PASS.'@'.NEO4J_IP.':'.NEO4J_PORT) // creates a bolt driver
    ->withDefaultDriver('bolt')
    ->build();

// Check Neo4j is running
try {
    $neo->run("SHOW DATABASES");
}
catch (\Throwable $th) {
    echo "Doesn't look like Neo4j is running or available yet. If you've just started Neo4j, give it a few moments.".PHP_EOL;
    exit;
}

// Create Neo4j constraints (for unique indexes, not regular indexes (should be faster))
$neo->run("CREATE CONSTRAINT IF NOT EXISTS FOR (b:block) REQUIRE b.hash IS UNIQUE");
$neo->run("CREATE CONSTRAINT IF NOT EXISTS FOR (t:tx) REQUIRE t.txid IS UNIQUE");
$neo->run("CREATE CONSTRAINT IF NOT EXISTS FOR (o:output) REQUIRE o.index IS UNIQUE");
$neo->run("CREATE INDEX IF NOT EXISTS FOR (b:block) ON (b.height)");
$neo->run("CREATE INDEX IF NOT EXISTS FOR (a:address) ON (a.address)"); // for getting outputs locked to an address

// Cypher Queries
$cypher['tx']            = file_get_contents("cypher/tx.cypher");
$cypher['tx-coinbase']   = file_get_contents("cypher/tx-coinbase.cypher");
$cypher['block']         = file_get_contents("cypher/block.cypher");
$cypher['block-genesis'] = file_get_contents("cypher/block-genesis.cypher");

// Functions
include('functions/tx.php');        // decode transaction
include('functions/block.php');     // calculate block reward
include('functions/readtx.php');    // read single transaction size quickly
include('cyphertx.php');            // insert tx in to neo4j

// Handy Functions
function blk00000($i): string { return 'blk'.str_pad($i, 5, '0', STR_PAD_LEFT).'.dat'; }

// ---------
// PRE-CHECK
// ---------
if (!file_exists(BLOCKS)) {
    exit("Couldn't find ".BLOCKS.PHP_EOL."Make sure you have entered the correct path to Bitcoin's blk*.dat files.\n");
}

// -------------------
// READ THE BLOCKCHAIN
//--------------------

$start = $redis->hget('bitcoin-to-neo4j', 'blk.dat') ?: 0; // which blk.dat file to start with
$startfp = $redis->hget('bitcoin-to-neo4j', 'fp') ?: 0; // Zero if not set

if (!extension_loaded("gmp")) throw new \Error("PHP GMP extension is not installed.");

while(true) { // Keep trying to read files forever

    $file = blk00000($start); // format file number (e.g. blk00420.dat instead of blk420.dat)
    $path = BLOCKS."/$file";

    $fh = fopen($path, 'rb'); echo "Reading $path...\n\n"; sleep(1);

    $dat_start = microtime(true); // track how long it takes to import a blk.dat file
    $b = 1; // for counting the blocks in each file

    // keep track of which blk.dat file we are on (store it in Redis)
    $redis->hset('bitcoin-to-neo4j', 'blk.dat', $start);

    while(true) { // Read through a blk*.dat file

        // pick up from where we left off
        if (isset($startfp)) { fseek($fh, $startfp); unset($startfp); }

        // keep track of where the file pointer is (before each block).
        $fp = ftell($fh);

        // store file pointer in redis (only after a block has been fully ran through)
        $redis->hset('bitcoin-to-neo4j', 'fp', $fp);

        // =====
        // BLOCK
        // =====
        $b_start = microtime(true); // track how long it takes to import a block

        // 1. Read one byte at a time until we hit a block header (magic bytes)
        $buffer = '';
        $bytesread = 0;
        while (true) {

            // Read 1 byte at a time
            $buffer .= bin2hex(fread($fh, 1));
            $bytesread++;
            $buffer = substr($buffer, -8); // magic bytes is 4 bytes

            // Magic Bytes
            $magicbytes = TESTNET ? '0b110907' : 'f9beb4d9';

            if (strlen($buffer) == 8) {
                // hit a block header
                if ($buffer == $magicbytes) {
                    $blocksize = fread($fh, 4);
                    $blocksize = hexdec(swapEndian(bin2hex($blocksize)));

                    // Read the full block of data
                    $block = bin2hex(fread($fh, $blocksize));

                    // if last 500 characters are all zeros, then we probably haven't got the full block data, so wait for it
                    if (hexdec(substr($block, -500)) == 0) {
                        echo "Doesn't look like the blk.dat file has all the bytes of data for the block. Wait a second for it to arrive...\n";
                        file_put_contents('log/blockwait.txt', "$block\n\n");

                        // wait a second
                        sleep(1);

                        // go back to end of last block
                        fseek($fh, $fp);
                        $fp = ftell($fh);
                        $bytesread = 0;     // reset bytes read

                        // go back to start of loop and try reading block again
                        continue;
                    }
                    else {
                        // reset buffer
                        $buffer = '';

                        // break out and start reading transactions
                        break;
                    }

                }
                // if we do not hit a block header
                else {
                    // if we have read forward another 1000 bytes and not found another magic bytes
                    if ($bytesread > 1000) {

                        // go back to end of last block
                        fseek($fh, $fp);
                        $fp = ftell($fh);

                        // reset bytes read
                        $bytesread = 0;
                        sleep(1);

                        echo "Doesn't look like there's another block yet. Re-reading... ($fp)\n";
                    }
                }
            }


            // hit end of file
            if (feof($fh)) {

                // if there is a next file, go to it
                $nextfile = blk00000($start+1);
                if (file_exists(BLOCKS."/$nextfile")) {
                    echo "\nThere is a file $nextfile.\n"; sleep(1);
                    $start = $start+1;  // Set the file number to the next one
                    break 2;            // ... Restart main loop (opens next file)
                }

            }
        }


        // Block Header (human format)
        $version =      hexdec(swapEndian(substr($block, 0, 8)));
        $prevblock =    swapEndian(substr($block, 8, 64)); // searchable byte order
        $merkleroot =   swapEndian(substr($block, 72, 64));
        $timestamp =    hexdec(swapEndian(substr($block, 136, 8)));
        $bits =         swapEndian(substr($block, 144, 8));
        $nonce =        hexdec(swapEndian(substr($block, 152, 8)));


        // i. Work out this block's hash
        $blockheader = substr($block, 0, 160); // header is 80 bytes total
        $blockhash = swapEndian(hash('sha256', hash('sha256', hex2bin($blockheader), true)));
        $hash = $blockhash; // this is for possibly setting the tip height in redis

        // a. Number of upcoming transactions (varint)
        $varint = substr($block, 160); list($full, $value, $len) = varInt($varint);
        $txcount = $value;

        $transactions = substr($block, 160+$len); // +$len: start from the end of the length of the tx count varint

        // 3. Save Block
        $b_start = microtime(true);
        $blocksizekb = number_format($blocksize/1000, 2);
        echo " $b: $blockhash [$blocksizekb kb] (fp:$fp) ";

        // Select Cypher Query
        if ($prevblock == '0000000000000000000000000000000000000000000000000000000000000000') { // Genesis Block
            $query = $cypher['block-genesis'];
        }
        else {
            $query = $cypher['block'];
        }

        // Save this block to Neo4j
        $run = $neo->run($query,
        [
            'blockhash'  => $blockhash,
            'blocksize'  => $blocksize,
            'txcount'    => $txcount,
            'version'    => $version,
            'prevblock'  => $prevblock,
            'merkleroot' => $merkleroot,
            'timestamp'  => $timestamp,
            'bits'       => $bits,
            'nonce'      => $nonce
        ]
        );

        // ------------------
        // HEIGHT BASED STUFF
        // ------------------

        // Get the height
        foreach ($run as $record) {
            $height = $record->get('height');
            echo $height;
            $prevblock = $record->get('prevblock');
        }
        // If we have a height for this block, set value for coinbase input.
        if ($height !== NULL) {
            $blockreward = calculateBlockReward($height);

            $neo->run('
            MATCH (block :block {hash:$blockhash})-[:coinbase]->(coinbase :output:coinbase)
            SET coinbase.value=$blockreward
            ',
            [
                'blockhash' => $blockhash,
                'blockreward' => $blockreward,
            ]
            );

        }

        // If we don't have a height, save this block hash for future updating
        else {
            echo "\n  This block's prevblock is not in database. Saving it.\n";

            // save preblock->blockhash to redis
            $redis->hset("bitcoin-to-neo4j:orphans", $prevblock, $blockhash);

            // print out how many orphan blocks we have saved in Redis
            echo '  - blocks needed = '.$redis->hlen('bitcoin-to-neo4j:orphans')."\n";
        }

        // ----------
        // ORPHAN RUN
        // ----------

        // If we've got a prevblock for a block with no height (and has a height for populating blocks above it)
        if ($redis->hExists('bitcoin-to-neo4j:orphans', $blockhash) && $height !== NULL) {
            echo "\n  Parent block! Updating block height, coinbase values and coinbase tx fees for blocks above it...\n";

            // Get all the blocks that are chained to this one (above it)
            $chainabove = $neo->run('
            MATCH (dependency :block {hash:$blockhash})<-[:chain*]-(blocks :block)
            RETURN collect(blocks.hash) as chainabove
            ',
            [
                'blockhash' => $blockhash
            ]
            );

            // Get the array of blocks to be populated
            foreach ($chainabove as $record) {
                $chainabove = $record->get('chainabove');
            };

            $heights = array();
            // Set height for each of these blocks
            foreach ($chainabove as $orphan) {
                echo "    $orphan ";

                $orphanrun = $neo->run('
                MATCH (block :block {hash:$orphan})-[:chain]->(prevblock :block)
                SET block.height=prevblock.height+1
                RETURN block
                ',
                [
                    'orphan' => $orphan,
                ]
                );

                foreach ($orphanrun as $record) {
                    $orphanblock = $record->get('block');
                }
                $orphanheight = $orphanblock->properties()->get('height');
                $orphanprevblock = $orphanblock->properties()->get('prevblock');

                echo "$orphanheight\n";

                // Set the coinbase values based on the height (can also set the fee now we know the block reward)
                $blockreward = calculateBlockReward($orphanheight);

                // Update coinbase and fee (if the coinbase input value has not been set)
                $coinbaserun = $neo->run('
                MATCH (block:block {hash:$orphan})-[:coinbase]->(coinbase:output:coinbase)-[:in]->(tx:tx)
                WHERE coinbase.value IS NULL
                SET coinbase.value = $blockreward
                SET tx.fee = tx.fee + $blockreward
                ',
                [
                    'orphan'      => $orphan,
                    'blockreward' => $blockreward,
                ]
                );

                // Keep log of heights that have been added
                $heights[$orphan] = $orphanheight;

                // Remove block from redis orphans
                $redis->hdel("bitcoin-to-neo4j:orphans", $orphan);

            }

            // Remove this current block from redis orphan too
            $redis->hdel("bitcoin-to-neo4j:orphans", $blockhash);

            // Find the max height and hash we've managed to get
            asort($heights);
            $max = array_slice($heights, -1, 1);
            $hash = key($max);
            $height = $max[$hash];

        }

        // Store longest known blockchain height in Redis
        if ($height > $redis->hget("bitcoin-to-neo4j:tip", 'height')) {
            $redis->hset("bitcoin-to-neo4j:tip", 'height', $height);
            $redis->hset("bitcoin-to-neo4j:tip", 'hash', $hash);
        }


        // ============
        // TRANSACTIONS
        // ============
        echo "\n  $txcount\n";

        // Read Individual Transactions

        // 1. Read each transaction in this string of transactions
        $p = 0; // pointer
        $t = 1; // tx count
        while (isset($transactions[$p])) { // continue until end of string of transactions
            // store the current pointer in case we need to go back to it
            $pbefore = $p;

            // read one tx (give a start pointer and it returns end pointer)
            list($transaction, $p) = readtx($transactions, $p);

            // get the txid ready so that it can be used in error handler
            $txid = swapEndian(hash('sha256', hash('sha256', hex2bin($transaction), true)));

            // ----------------
            // CYPHER TX INSERT
            // ----------------
            $tx_start =  microtime(true);
            cypherTx($neo, $transaction, $t, $blockhash, $cypher); // IMPORT THE TRANSACTION IN TO NEO4J! (using functions/cyphertx.php)
            $tx_time = microtime(true)-$tx_start;

            // Display the time it took to insert transaction
            echo '  '.number_format($tx_time, 5)."\n";

            // next tx...
            $t++;

        } // transaction block string loop


        $b_end = microtime(true);
        echo '  '.number_format(($b_end-$b_start)/60, 5)." mins \n\n";

        // next block...
        $b++; // update block count for this blk.dat file

    } // blk*.dat loop

    // log that the file has been done
    $dat_end = microtime(true); $dat_time = number_format(($dat_end-$dat_start)/60, 2);
    $b--;
    $redis->hset('bitcoin-to-neo4j:log', $file, "[$b] $dat_time mins");


} // Infinite Loop
Download .txt
gitextract_r9ptinru/

├── .gitignore
├── LICENSE
├── README.md
├── composer.json
├── config.php
├── cypher/
│   ├── block-genesis.cypher
│   ├── block.cypher
│   ├── tx-coinbase.cypher
│   └── tx.cypher
├── cyphertx.php
├── docs/
│   ├── benchmark.md
│   ├── cypher.md
│   └── how.md
├── functions/
│   ├── README.md
│   ├── basic.php
│   ├── block.php
│   ├── hash.php
│   ├── keys.php
│   ├── readtx.php
│   ├── script.php
│   └── tx.php
└── main.php
Download .txt
SYMBOL INDEX (32 symbols across 9 files)

FILE: cyphertx.php
  function cypherTx (line 8) | function cypherTx($neo, $transaction, $t, $blockhash, $cypher) {

FILE: functions/basic.php
  function swapEndian (line 8) | function swapEndian($data) {
  function fieldSize (line 12) | function fieldSize($field, $bytes = 4) {
  function ascii2hex (line 18) | function ascii2hex($ascii) {
  function hex2ascii (line 28) | function hex2ascii($hex) {
  function varInt (line 38) | function varInt($data) { // Calculates the full variable integer and ret...
  function toVarInt (line 51) | function toVarInt($i) {
  function bchexdec (line 66) | function bchexdec($hex) {
  function bcdechex (line 76) | function bcdechex($dec) {

FILE: functions/block.php
  function calculateBlockReward (line 12) | function calculateBlockReward($blockcount) {
  function bitstotarget (line 34) | function bitstotarget($bits) {
  function bitstodifficulty (line 56) | function bitstodifficulty($bits) {
  function difficultytotarget (line 66) | function difficultytotarget($difficulty) {
  function targettobits (line 73) | function targettobits($target) {
  function merklerootbinary (line 95) | function merklerootbinary($txids) {
  function merkleroot (line 150) | function merkleroot($txids) {

FILE: functions/hash.php
  function hash256 (line 8) | function hash256($hex) {
  function hash160 (line 15) | function hash160($hex) {

FILE: functions/keys.php
  function base58_encode (line 11) | function base58_encode($hex)
  function base58_encode_checksum (line 44) | function base58_encode_checksum($hex)
  function hash160_to_address (line 52) | function hash160_to_address($hash160, $prefix = '00')
  function pubkey_to_address (line 60) | function pubkey_to_address($pubkey)
  function bech32_polymod (line 66) | function bech32_polymod($values) {
  function bech32_hrp_expand (line 84) | function bech32_hrp_expand($hrp) {
  function bech32_create_checksum (line 96) | function bech32_create_checksum($hrp, $data) {
  function convertbits (line 109) | function convertbits($data, $from, $to, $pad=true) {
  function bech32_encode (line 144) | function bech32_encode($hrp, $data) {
  function bech32_address (line 168) | function bech32_address($scriptpubkey) {

FILE: functions/readtx.php
  function readtx (line 10) | function readtx($transactions, $p=0) {

FILE: functions/script.php
  function decodeScript (line 10) | function decodeScript($script) {

FILE: functions/tx.php
  function decoderawtransaction (line 11) | function decoderawtransaction($data) {

FILE: main.php
  function blk00000 (line 57) | function blk00000($i): string { return 'blk'.str_pad($i, 5, '0', STR_PAD...
Condensed preview — 22 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (123K chars).
[
  {
    "path": ".gitignore",
    "chars": 27,
    "preview": "vendor\ncomposer.lock\n.idea\n"
  },
  {
    "path": "LICENSE",
    "chars": 34913,
    "preview": "### GNU GENERAL PUBLIC LICENSE\n\nVersion 3, 29 June 2007\n\nCopyright (C) 2007 Free Software Foundation, Inc.\n<http://fsf.o"
  },
  {
    "path": "README.md",
    "chars": 8065,
    "preview": "**This project is now archived.**\n\nThis tool _does_ work for importing blockchain data in to Neo4j, but it's **very slow"
  },
  {
    "path": "composer.json",
    "chars": 269,
    "preview": "{\n    \"require\": {\n        \"laudis/neo4j-php-client\": \"^2.0\",\n        \"ext-redis\": \"*\",\n        \"ext-gmp\": \"*\",\n        "
  },
  {
    "path": "config.php",
    "chars": 408,
    "preview": "<?php\n\ndefine(\"BLOCKS\", '/home/user/.bitcoin/blocks');\ndefine(\"TESTNET\", false); // Probably not, but; are you reading b"
  },
  {
    "path": "cypher/block-genesis.cypher",
    "chars": 429,
    "preview": "// Create Block\nMERGE (block:block {hash:$blockhash})\nMERGE (block)-[:coinbase]->(:output:coinbase)\nSET\n    block.size=$"
  },
  {
    "path": "cypher/block.cypher",
    "chars": 541,
    "preview": "// Create Block\nMERGE (block:block {hash:$blockhash})\nMERGE (block)-[:coinbase]->(:output:coinbase)\nSET\n    block.size=$"
  },
  {
    "path": "cypher/tx-coinbase.cypher",
    "chars": 1164,
    "preview": "// Create Transaction\nMATCH (block :block {hash:$blockhash})-[:coinbase]->(coinbase :coinbase)\nMERGE (tx:tx {txid:$txid}"
  },
  {
    "path": "cypher/tx.cypher",
    "chars": 1138,
    "preview": "// Create Transaction\nMATCH (block :block {hash:$blockhash})\nMERGE (tx:tx {txid:$txid})\nMERGE (tx)-[:inc {i:$t}]->(block"
  },
  {
    "path": "cyphertx.php",
    "chars": 5535,
    "preview": "<?php\n/*\n * author:  Greg Walker\n * website: http://learnmeabitcoin.com\n * license: GPLv3\n*/\n\nfunction cypherTx($neo, $t"
  },
  {
    "path": "docs/benchmark.md",
    "chars": 1835,
    "preview": "# Benchmarks\n\nI did a few rough tests for common/useful bitcoin queries, each returning various numbers of nodes. I repe"
  },
  {
    "path": "docs/cypher.md",
    "chars": 4479,
    "preview": "# Cypher Queries\n\nHere are some example Cypher queries for getting useful data out of the Bitcoin Neo4j database.\n\n## Bl"
  },
  {
    "path": "docs/how.md",
    "chars": 14191,
    "preview": "# How to Import the Blockchain in to Neo4j\n\n![Screenshot of the blockchain in the Neo4j browser.](images/how/neo4j-bitco"
  },
  {
    "path": "functions/README.md",
    "chars": 336,
    "preview": "# Library Functions\n\nThis is a bunch of simple library functions for Bitcoin. I use them for decoding the raw transactio"
  },
  {
    "path": "functions/basic.php",
    "chars": 2276,
    "preview": "<?php\n/*\n * author:  Greg Walker\n * website: http://learnmeabitcoin.com\n * license: GPLv3\n*/\n\nfunction swapEndian($data)"
  },
  {
    "path": "functions/block.php",
    "chars": 4240,
    "preview": "<?php\n/*\n * author:  Greg Walker\n * website: http://learnmeabitcoin.com\n * license: GPLv3\n*/\n\nrequire_once('basic.php');"
  },
  {
    "path": "functions/hash.php",
    "chars": 451,
    "preview": "<?php\n/*\n * author:  Greg Walker\n * website: http://learnmeabitcoin.com\n * license: GPLv3\n*/\n\nfunction hash256($hex) {\n\t"
  },
  {
    "path": "functions/keys.php",
    "chars": 5106,
    "preview": "<?php\n/*\n * author:  Greg Walker\n * website: http://learnmeabitcoin.com\n * license: GPLv3\n*/\n\ninclude_once 'hash.php'; /"
  },
  {
    "path": "functions/readtx.php",
    "chars": 2447,
    "preview": "<?php\n/*\n * author:  Greg Walker\n * website: http://learnmeabitcoin.com\n * license: GPLv3\n*/\n\ninclude_once \"functions/ba"
  },
  {
    "path": "functions/script.php",
    "chars": 9041,
    "preview": "<?php\n/*\n * author:  Greg Walker\n * website: http://learnmeabitcoin.com\n * license: GPLv3\n*/\n\ninclude_once 'keys.php';\n\n"
  },
  {
    "path": "functions/tx.php",
    "chars": 4412,
    "preview": "<?php\n/*\n * author:  Greg Walker\n * website: http://learnmeabitcoin.com\n * license: GPLv3\n*/\n\ninclude_once 'basic.php';\n"
  },
  {
    "path": "main.php",
    "chars": 14897,
    "preview": "<?php\n/*\n * title:   bitcoin-to-neo4j\n * desc:    Import Bitcoin's blk.dat files (the blockchain) in to a Neo4j graph da"
  }
]

About this extraction

This page contains the full source code of the in3rsha/bitcoin-to-neo4j GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 22 files (113.5 KB), approximately 32.5k tokens, and a symbol index with 32 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!